import { useMemo, useState } from 'react'
import useSWR from 'swr'
import { fetcher } from '../../http/axiosInstance'
import { BASE_URL } from '../../constants'
import { setSelectedObjectType } from '../../store/map';
import { setCurrentObjectId, useObjectsStore } from '../../store/objects';
import { Text, Tree, TreeItem, TreeItemLayout } from '@fluentui/react-components';

const ObjectTree = ({
    map_id
}: {
    map_id: string,
}) => {
    const { selectedYear, selectedDistrict } = useObjectsStore().id[map_id]
    const [existingCount, setExistingCount] = useState(0)
    const [planningCount, setPlanningCount] = useState(0)

    const { data: existingObjectsList } = useSWR(
        selectedYear && selectedDistrict ? `/general/objects/list?year=${selectedYear}&city_id=${selectedDistrict}&planning=0` : null,
        (url) => fetcher(url, BASE_URL.nest).then(res => {
            if (Array.isArray(res)) {
                let count = 0
                res.forEach(el => {
                    count = count + el.count
                })
                setExistingCount(count)
            }
            return res
        }),
        {
            revalidateOnFocus: false
        }
    )

    const { data: planningObjectsList } = useSWR(
        selectedYear && selectedDistrict ? `/general/objects/list?year=${selectedYear}&city_id=${selectedDistrict}&planning=1` : null,
        (url) => fetcher(url, BASE_URL.nest).then(res => {
            if (Array.isArray(res)) {
                let count = 0
                res.forEach(el => {
                    count = count + el.count
                })
                setPlanningCount(count)
            }
            return res
        }),
        {
            revalidateOnFocus: false
        }
    )

    if (selectedDistrict) {
        return (
            <div style={{ width: '100%' }}>
                <TypeTree key={'existing'} map_id={map_id} label='Существующие' value={'existing'} count={existingCount} objectList={existingObjectsList} planning={0} />
                <TypeTree key={'planning'} map_id={map_id} label='Планируемые' value={'planning'} count={planningCount} objectList={planningObjectsList} planning={1} />
            </div>
        )
    } else {
        return (
            <Text size={500}>Выберите регион и населённый пункт, чтобы увидеть список объектов.</Text>
        )
    }


}

interface TypeTreeProps {
    label: string;
    value: string;
    count: number;
    objectList: unknown;
    planning: number;
    map_id: string;
}

const TypeTree = ({
    label,
    objectList,
    count,
    planning,
    map_id
}: TypeTreeProps) => {

    return (
        <Tree size="small" aria-label="Small Size Tree">
            <TreeItem key={`branch-${label}`} itemType="branch">
                <TreeItemLayout>{`${label} ${count ? `(${count})` : ''}`}</TreeItemLayout>

                <Tree>
                    {Array.isArray(objectList) && objectList.map(list => (
                        <ObjectList map_id={map_id} key={`${label}-${list.id}`} label={list.name} id={list.id} planning={planning} count={list.count} />
                    ))}
                </Tree>
            </TreeItem>
        </Tree>
    )
}

interface IObjectList {
    label: string;
    id: number;
    planning: number;
    count: number;
    map_id: string;
}

const ObjectList = ({
    label,
    id,
    planning,
    count,
    map_id
}: IObjectList) => {
    const { selectedDistrict, selectedYear } = useObjectsStore().id[map_id]

    const { data } = useSWR(
        selectedDistrict && selectedYear ? `/general/objects/list?type=${id}&city_id=${selectedDistrict}&year=${selectedYear}&planning=${planning}` : null,
        (url) => fetcher(url, BASE_URL.nest),
        {
            revalidateOnFocus: false,
            revalidateIfStale: false
        }
    )

    const navLinks = useMemo(() => (
        Array.isArray(data) ? data.map((type, index) => (
            <TreeItem key={`${label}-${id}-${index}`} itemType='leaf' onClick={() => setCurrentObjectId(map_id, type.object_id)}>
                <TreeItemLayout>{type.caption ? type.caption : 'Без названия'}</TreeItemLayout>
            </TreeItem>
        )) : null
    ), [data, map_id]);

    return (
        <TreeItem itemType='branch' onClick={() => setSelectedObjectType(map_id, id)}>
            <TreeItemLayout>{`${label} ${count ? `(${count})` : ''}`}</TreeItemLayout>

            <Tree>
                {navLinks}
            </Tree>
        </TreeItem>
    )
}

export default ObjectTree