import { useEffect, useState } from 'react'
import { Button, CompoundButton, Dropdown, Option, Spinner, Text } from '@fluentui/react-components'
import useSWR from 'swr'
import axios from 'axios'
import { AgGridReact } from 'ag-grid-react'
import { AllCommunityModule, ModuleRegistry } from 'ag-grid-community'
import { ICity, IRegion, ISeason } from '../../interfaces/fuel'
import { useSearchParams } from 'react-router-dom'
import LimitAddForm from './Limits/LimitEditForm'

ModuleRegistry.registerModules([AllCommunityModule])

function LimitsPage() {
    const [searchParams, setSearchParams] = useSearchParams();

    const [year, setYear] = useState<number | undefined>(
        searchParams.get("year") ? Number(searchParams.get("year")) : undefined
    )

    const [regionId, setRegionId] = useState<number | undefined>(
        searchParams.get("region_id") ? Number(searchParams.get("region_id")) : undefined
    );

    const [cityId, setCityId] = useState<number | undefined>(
        searchParams.get("city_id") ? Number(searchParams.get("city_id")) : undefined
    )

    // Load regions
    const { data: regions, isLoading: regionsLoading } = useSWR("/general/regions", () =>
        axios
            .get("/general/regions", { baseURL: import.meta.env.VITE_API_NEST_URL })
            .then((res) => res.data)
    );

    // Load cities when regionId exists
    const { data: cities, isLoading: citiesLoading } = useSWR(
        regionId ? `/general/cities?region_id=${regionId}` : null,
        () =>
            axios
                .get(`/general/cities?region_id=${regionId}`, {
                    baseURL: import.meta.env.VITE_API_NEST_URL,
                })
                .then((res) => res.data)
    );

    // Load seasons
    const { data: seasons } = useSWR(
        `/fuel/seasons`,
        () => [
            {
                name: 'Отопительный сезон 2025-2026',
                year: 2025
            }
        ] as ISeason[]
    );

    // Load boilers when cityId exists
    const { data: limits, isLoading: limitsLoading } = useSWR(
        cityId && year ? `/fuel/limits?city_id=${cityId}&year=${year}&offset=0&limit=100` : null,
        () =>
            axios
                .get(`/fuel/limits?city_id=${cityId}&year=${year}&offset=0&limit=100`, {
                    baseURL: import.meta.env.VITE_API_NEST_URL,
                })
                .then((res) => res.data)
    );

    //
    // Sync regionId → URL
    //
    useEffect(() => {
        if (!regionId) return;

        setSearchParams((prev) => {
            const params = new URLSearchParams(prev);
            params.set("region_id", regionId.toString());
            params.delete("city_id"); // reset city when region changes
            return params;
        });

    }, [regionId]);

    //
    // Sync cityId → URL
    //
    useEffect(() => {
        if (!cityId) return;

        setSearchParams((prev) => {
            const params = new URLSearchParams(prev);
            params.set("city_id", cityId.toString());
            return params;
        });
    }, [cityId]);

    useEffect(() => {
        if (!year) return;

        setSearchParams((prev) => {
            const params = new URLSearchParams(prev);
            params.set("year", year.toString());
            return params;
        });
    }, [year]);

    //
    // Utility: get display values
    //
    const selectedRegion = regions?.find((r: IRegion) => r.id === regionId);
    const selectedCity = cities?.find((c: ICity) => c.id === cityId);
    const selectedSeason = seasons?.find((c: ISeason) => c.year === year);

    useEffect(() => {
        const paramCityId = searchParams.get("city_id");

        if (!paramCityId) return;

        const id = Number(paramCityId);

        // If cityId not yet set OR mismatched with URL
        if (cities && !cityId && cities.some((c: ICity) => c.id === id)) {
            setCityId(id);
        }
    }, [cities])

    useEffect(() => {
        const paramRegionId = searchParams.get("region_id");
        if (!paramRegionId) return;

        const id = Number(paramRegionId);

        if (regions && !regionId && regions.some((r: IRegion) => r.id === id)) {
            setRegionId(id);
        }
    }, [regions]);

    useEffect(() => {
        const paramYear = searchParams.get("year");
        if (!paramYear) return;

        const year = Number(paramYear);

        if (year && seasons) {
            setYear(year);
        }
    }, [seasons]);

    useEffect(() => {
        setCityId(undefined); // clear stale value before SWR runs
        setYear(undefined)
    }, [regionId])

    const [limitAddFormOpen, setLimitAddFormOpen] = useState(false)

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            padding: '1rem',
            width: '100%',
            gap: '1rem'
        }}>
            {/* <Portal mountNode={document.querySelector('#header-portal')}>
                
            </Portal> */}

            <div style={{ display: 'flex', gap: '1rem' }}>
                {regionsLoading ?
                    <Spinner />
                    :
                    <Dropdown
                        placeholder='Выберите район'
                        value={selectedRegion?.name ?? ""}
                        selectedOptions={regionId ? [regionId.toString()] : []}
                        onOptionSelect={(_, data) => {
                            if (!data.optionValue) {
                                setRegionId(undefined);
                                return;
                            }
                            setRegionId(Number(data.optionValue));
                        }}
                    >
                        {regions && Array.isArray(regions) && regions.map((option) => (
                            <Option key={`region-${option.id}`} text={option.name} value={option.id}>
                                {option.name}
                            </Option>
                        ))}
                    </Dropdown>
                }

                {citiesLoading ?
                    <Spinner />
                    :
                    <Dropdown
                        placeholder='Выберите населенный пункт'
                        value={selectedCity?.name ?? ""}
                        selectedOptions={cityId ? [cityId.toString()] : []}
                        onOptionSelect={(_, data) => {
                            if (!data.optionValue) {
                                setCityId(undefined);
                                return;
                            }
                            setCityId(Number(data.optionValue));
                        }}
                    >
                        {cities && Array.isArray(cities) && cities.map((option) => (
                            <Option key={`region-${option.id}`} text={option.name} value={option.id}>
                                {option.name}
                            </Option>
                        ))}
                    </Dropdown>
                }

                <Dropdown
                    placeholder='Выберите отопительный сезон'
                    value={selectedSeason?.name ?? ""}
                    selectedOptions={year ? [year.toString()] : []}
                    onOptionSelect={(_, data) => {
                        if (!data.optionValue) {
                            setYear(undefined);
                            return;
                        }
                        setYear(Number(data.optionValue));
                    }}
                >
                    {seasons && Array.isArray(seasons) && seasons.map((option) => (
                        <Option key={`region-${option.year}`} text={option.name} value={option.year.toString()}>
                            {option.name}
                        </Option>
                    ))}
                </Dropdown>
            </div>

            <div style={{
                display: 'flex',
                width: '100%',
                flexDirection: 'column',
                gap: '1rem'
            }}>
                <Text size={400} weight='medium'>
                    {cityId && cities && Array.isArray(cities) && cities.find(city => city.id === cityId).name}
                </Text>

                {cityId &&
                    <div style={{ display: 'flex', width: '100%', gap: '1rem', justifyContent: 'space-between' }}>
                        <BoilersCard title='Всего объектов' value={limits && Array.isArray(limits) ? limits.length.toString() : ''} subtitle='' />

                        <BoilersCard title='Общий остаток' value={''} subtitle='' />

                        <BoilersCard title='Лимит на сезон' value={''} subtitle='' />

                        <BoilersCard title='Требуют внимания' value={''} subtitle='' />
                    </div>
                }

                <Button appearance='primary' style={{ width: 'min-content' }} onClick={() => setLimitAddFormOpen(true)}>
                    Добавить
                </Button>

                <LimitAddForm cityId={cityId} open={limitAddFormOpen} setOpen={setLimitAddFormOpen} />
            </div>

            <AgGridReact
                key={`boilers-${cityId}`}
                loading={limitsLoading}
                overlayLoadingTemplate='Загрузка...'
                overlayNoRowsTemplate='Нет данных'
                rowData={limits}
                onRowClicked={(e) => {
                    console.log(e.data)
                }
                }
                columnDefs={[
                    {
                        field: 'boiler_name',
                        headerName: 'Наименование'
                    },
                    {
                        field: 'fuel_name',
                        headerName: 'Вид топлива'
                    },
                    // {
                    //     field: 'boiler_code',
                    //     headerName: 'Идент. код'
                    // },
                    // {
                    //     field: 'id_fuels',
                    //     headerName: 'Вид топлива',
                    //     //editable: true,
                    //     //cellEditor: FuelTypeEditor,
                    //     autoHeight: true,
                    //     cellRenderer: FuelRenderer,
                    //     cellStyle: (_) => {
                    //         return { padding: '1px' }
                    //     }
                    //     //enableCellChangeFlash: true
                    // },
                    // {
                    //     field: 'activity',
                    //     headerName: 'Активный',
                    //     cellRenderer: (params: CustomCellRendererProps) => (<span>{params.value === true ? 'Да' : 'Нет'}</span>)
                    // }
                    {
                        field: 'jul',
                        headerName: 'Июль'
                    },
                    {
                        field: 'aug',
                        headerName: 'Август'
                    },
                    {
                        field: 'sep',
                        headerName: 'Сентябрь'
                    },
                    {
                        field: 'oct',
                        headerName: 'Октябрь'
                    },
                    {
                        field: 'nov',
                        headerName: 'Ноябрь'
                    },
                    {
                        field: 'dec',
                        headerName: 'Декабрь'
                    },
                    {
                        field: 'jan',
                        headerName: 'Январь'
                    },
                    {
                        field: 'feb',
                        headerName: 'Февраль'
                    },
                    {
                        field: 'mar',
                        headerName: 'Март'
                    },
                    {
                        field: 'apr',
                        headerName: 'Апрель'
                    },
                    {
                        field: 'may',
                        headerName: 'Май'
                    },
                    {
                        field: 'jun',
                        headerName: 'Июнь'
                    }
                ]}
                defaultColDef={{
                    flex: 1,
                }}
            />
        </div>
    )
}

const BoilersCard = ({
    title,
    value,
    subtitle,
}: {
    title: string
    value: string
    subtitle: string
}) => {
    return (
        <CompoundButton
            onClick={() => { }}
            style={{ display: 'flex', width: '100%', justifyContent: 'flex-start', flexDirection: 'column', gap: '2rem', alignItems: 'flex-start', cursor: 'pointer', userSelect: 'none' }}
        //icon={icon}
        >

            <Text weight='bold' size={300}>
                {title}
            </Text>

            <Text weight='bold' size={500}>
                {value}
            </Text>

            <Text weight='regular' size={200} style={{ color: 'gray' }}>
                {subtitle}
            </Text>
        </CompoundButton>
    )
}

export default LimitsPage