"use client"

import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
// curl 'https://api.jkhsakha.ru/lk/address/' \
// -H 'Accept: application/json' \
// -H 'Accept-Language: ru,en-US;q=0.9,en;q=0.8,de;q=0.7' \
// -H 'Authorization: bearer' \
// -H 'Connection: keep-alive' \
// -H 'Content-Type: application/json' \
// -H 'Origin: https://new.jkhsakha.ru' \
// -H 'Referer: https://new.jkhsakha.ru/' \
// -H 'Sec-Fetch-Dest: empty' \
// -H 'Sec-Fetch-Mode: cors' \
// -H 'Sec-Fetch-Site: same-site' \
// -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36' \
// -H 'sec-ch-ua: "Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"' \
// -H 'sec-ch-ua-mobile: ?0' \
// -H 'sec-ch-ua-platform: "macOS"' \
// --data - raw '{"IDPersonalAccount":0,"IDRegion":0,"IDCity":0,"IDStreet":0,"IDHouse":0,"IDFlat":0}'

interface AddressData {
    IDPersonalAccount: number
    IDRegion: number
    IDCity: number
    IDStreet: number
    IDHouse: number
    IDFlat: number
}

interface Region {
    IDRegion: number
    NameRegion: string
}

interface City {
    IDCity: number
    NameCity: string
}

interface Street {
    IDStreet: number
    NameStreet: string
}

interface House {
    IDHouse: number
    NameHouse: string
}

interface Flat {
    IDPersonalAccount: number
    NameFlat: string
}

const API_BASE_URL = 'https://api.jkhsakha.ru/lk/address/'

const GetLK = () => {
    const [regions, setRegions] = useState<Region[]>([])
    const [cities, setCities] = useState<City[]>([])
    const [streets, setStreets] = useState<Street[]>([])
    const [houses, setHouses] = useState<House[]>([])
    const [flats, setFlats] = useState<Flat[]>([])

    const [selectedAccount, setSelectedAccount] = useState<Flat | null>(null)

    const { register, watch, setValue } = useForm<AddressData>({
        defaultValues: {
            IDPersonalAccount: 0,
            IDRegion: 0,
            IDCity: 0,
            IDStreet: 0,
            IDHouse: 0,
            IDFlat: 0
        }
    })

    const watchRegion = watch('IDRegion')
    const watchCity = watch('IDCity')
    const watchStreet = watch('IDStreet')
    const watchHouse = watch('IDHouse')
    const watchFlat = watch('IDFlat')

    // Fetch regions on component mount
    useEffect(() => {
        const fetchRegions = async () => {
            try {
                const response = await fetch(API_BASE_URL, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        'Authorization': 'bearer',
                    },
                    body: JSON.stringify({
                        IDPersonalAccount: 0,
                        IDRegion: 0,
                        IDCity: 0,
                        IDStreet: 0,
                        IDHouse: 0,
                        IDFlat: 0
                    })
                })
                const data = await response.json()
                setRegions(data)
            } catch (error) {
                console.error('Error fetching regions:', error)
            }
        }

        fetchRegions()
    }, [])

    // Fetch cities when region is selected
    useEffect(() => {
        if (watchRegion && watchRegion !== 0) {
            const fetchCities = async () => {
                try {
                    const response = await fetch(API_BASE_URL, {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'Authorization': 'bearer',
                        },
                        body: JSON.stringify({
                            IDPersonalAccount: 0,
                            IDRegion: watchRegion,
                            IDCity: 0,
                            IDStreet: 0,
                            IDHouse: 0,
                            IDFlat: 0
                        })
                    })
                    const data = await response.json()
                    setCities(data)
                    setValue('IDCity', 0) // Reset city selection
                    setStreets([]) // Clear dependent fields
                    setHouses([])
                    setFlats([])
                } catch (error) {
                    console.error('Error fetching cities:', error)
                }
            }

            fetchCities()
        }
    }, [watchRegion, setValue])

    // Fetch streets when city is selected
    useEffect(() => {
        if (watchCity && watchCity !== 0) {
            const fetchStreets = async () => {
                try {
                    const response = await fetch(API_BASE_URL, {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'Authorization': 'bearer',
                        },
                        body: JSON.stringify({
                            IDPersonalAccount: 0,
                            IDRegion: watchRegion,
                            IDCity: watchCity,
                            IDStreet: 0,
                            IDHouse: 0,
                            IDFlat: 0
                        })
                    })
                    const data = await response.json()
                    setStreets(data)
                    setValue('IDStreet', 0) // Reset street selection
                    setHouses([]) // Clear dependent fields
                    setFlats([])
                } catch (error) {
                    console.error('Error fetching streets:', error)
                }
            }

            fetchStreets()
        }
    }, [watchCity, watchRegion, setValue])

    // Fetch houses when street is selected
    useEffect(() => {
        if (watchStreet && watchStreet !== 0) {
            const fetchHouses = async () => {
                try {
                    const response = await fetch(API_BASE_URL, {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'Authorization': 'bearer',
                        },
                        body: JSON.stringify({
                            IDPersonalAccount: 0,
                            IDRegion: watchRegion,
                            IDCity: watchCity,
                            IDStreet: watchStreet,
                            IDHouse: 0,
                            IDFlat: 0
                        })
                    })
                    const data = await response.json()
                    setHouses(data)
                    setValue('IDHouse', 0) // Reset house selection
                    setFlats([]) // Clear dependent fields
                } catch (error) {
                    console.error('Error fetching houses:', error)
                }
            }

            fetchHouses()
        }
    }, [watchStreet, watchCity, watchRegion, setValue])

    // Fetch flats when house is selected
    useEffect(() => {
        if (watchHouse && watchHouse !== 0) {
            const fetchFlats = async () => {
                try {
                    const response = await fetch(API_BASE_URL, {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'Authorization': 'bearer',
                        },
                        body: JSON.stringify({
                            IDPersonalAccount: 0,
                            IDRegion: watchRegion,
                            IDCity: watchCity,
                            IDStreet: watchStreet,
                            IDHouse: watchHouse,
                            IDFlat: 0
                        })
                    })
                    const data = await response.json()
                    setFlats(data)
                    setValue('IDFlat', 0) // Reset flat selection
                } catch (error) {
                    console.error('Error fetching flats:', error)
                }
            }

            fetchFlats()
        }
    }, [watchHouse, watchStreet, watchCity, watchRegion, setValue])

    // Update selected account when flat is chosen
    useEffect(() => {
        if (watchFlat && watchFlat !== 0) {
            const selectedFlat = flats.find(flat => flat.IDPersonalAccount === watchFlat)
            if (selectedFlat) {
                setSelectedAccount(selectedFlat)
            }
        }
    }, [watchFlat, flats])

    const form = [
        {
            label: 'Выберите район / улус',
            value: 'IDRegion',
            options: regions,
            valueKey: 'IDRegion',
            labelKey: 'NameRegion'
        },
        {
            label: 'Выберите нас.пункт',
            value: 'IDCity',
            options: cities,
            valueKey: 'IDCity',
            labelKey: 'NameCity',
            disabled: !watchRegion || watchRegion === 0
        },
        {
            label: 'Выберите улицу',
            value: 'IDStreet',
            options: streets,
            valueKey: 'IDStreet',
            labelKey: 'NameStreet',
            disabled: !watchCity || watchCity === 0
        },
        {
            label: '№ дома',
            value: 'IDHouse',
            options: houses,
            valueKey: 'IDHouse',
            labelKey: 'NameHouse',
            disabled: !watchStreet || watchStreet === 0
        },
        {
            label: 'Квартира',
            value: 'IDFlat',
            options: flats,
            valueKey: 'IDPersonalAccount',
            labelKey: 'NameFlat',
            disabled: !watchHouse || watchHouse === 0
        }
    ]

    return (
        <div className='flex flex-col gap-4'>
            <div className='text-lg font-medium'>Укажите адрес:</div>

            <div className='flex flex-col gap-3'>
                {form.map((select, index) => (
                    <select
                        key={`select-${index}`}
                        className="select appearance-none p-2 border rounded-md"
                        {...register(select.value as keyof AddressData, {
                            valueAsNumber: true,
                            disabled: select.disabled
                        })}
                        disabled={select.disabled}
                    >
                        <option value={0} disabled={true}>{select.label}</option>
                        {Array.isArray(select.options) && select.options.map((option) => (
                            <option
                                key={option[select.valueKey]}
                                value={option[select.valueKey]}
                            >
                                {option[select.labelKey]}
                            </option>
                        ))}
                    </select>
                ))}
            </div>

            {selectedAccount && (
                <div className='mt-4 p-3 bg-gray-100 rounded-md'>
                    <div className='font-medium'>Выбрано:</div>
                    <div>Лицевой счет: {selectedAccount.IDPersonalAccount}</div>
                    <div>Квартира: {selectedAccount.NameFlat}</div>
                </div>
            )}
        </div>
    )

}

export default GetLK