import { useState, useEffect, useRef, useCallback } from 'react';
import { ChevronDown, Search, X } from 'lucide-react';
import { useDispatch, useSelector } from 'react-redux';
import { updateFieldAndSaveToAPI, updateFormFields } from '../../app/reducers/registrationstep1';
import { AppDispatch, RootState } from '../../app/store';
import { fetchCities, fetchStates } from '../../app/reducers/profileattributelist';

export default function Hometown() {
    const { attributes } = useSelector((state: RootState) => state.profileattributelist);
    const dispatch = useDispatch<AppDispatch>();
    const [country, setCountry] = useState(0);
    const [district, setDistrict] = useState(0);
    const [upazila, setUpazila] = useState(0);
    
    // Search states
    const [countrySearch, setCountrySearch] = useState('');
    const [districtSearch, setDistrictSearch] = useState('');
    const [upazilaSearch, setUpazilaSearch] = useState('');
    
    // Dropdown visibility states
    const [countryDropdownOpen, setCountryDropdownOpen] = useState(false);
    const [districtDropdownOpen, setDistrictDropdownOpen] = useState(false);
    const [upazilaDropdownOpen, setUpazilaDropdownOpen] = useState(false);

    // Refs for click outside detection
    const countryRef = useRef<HTMLDivElement>(null);
    const districtRef = useRef<HTMLDivElement>(null);
    const upazilaRef = useRef<HTMLDivElement>(null);
    
    const fetchDistricts = useCallback(async (countryId: number) => {
        if (!countryId) return;
        dispatch(fetchStates(countryId));
    }, [dispatch]);

    const fetchUpazilas = useCallback(async (districtId: number) => {
        if (!districtId) return;
        dispatch(fetchCities(districtId));
    }, [dispatch]);
    
    // Filtered data based on search
    const filteredCountries = attributes.countries?.filter(c => 
        c.name.toLowerCase().includes(countrySearch.toLowerCase())
    ) || [];
    
    const filteredDistricts = attributes.states?.filter(d => 
        d.name.toLowerCase().includes(districtSearch.toLowerCase())
    ) || [];
    
    const filteredUpazilas = attributes.cities?.filter(u => 
        u.name.toLowerCase().includes(upazilaSearch.toLowerCase())
    ) || [];
    
    // Handle click outside to close dropdowns
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (countryRef.current && !countryRef.current.contains(event.target as Node)) {
                setCountryDropdownOpen(false);
            }
            if (districtRef.current && !districtRef.current.contains(event.target as Node)) {
                setDistrictDropdownOpen(false);
            }
            if (upazilaRef.current && !upazilaRef.current.contains(event.target as Node)) {
                setUpazilaDropdownOpen(false);
            }
        }
        
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, []);
    
    useEffect(() => {
        if (country) {
            fetchDistricts(country);
        }
        // Reset district and upazila when country changes
        setDistrict(0);
        setUpazila(0);
        setDistrictSearch('');
        setUpazilaSearch('');
    }, [country, fetchDistricts]);

    useEffect(() => {
        if (district) {
            fetchUpazilas(district);
        }

        setUpazila(0);
        setUpazilaSearch('');
    }, [district, fetchUpazilas]);
    
    useEffect(() => {
        const selectedCountry = attributes.countries?.find(c => c.id === country)?.name || '';
        const selectedDistrict = attributes.states?.find(d => d.id === district)?.name || '';
        const selectedUpazila = attributes.cities?.find(u => u.id === upazila)?.name || '';
        
        const hometownValue = [selectedUpazila, selectedDistrict, selectedCountry].filter(Boolean).join(', ');
        
        if (country && district && upazila) {
            dispatch(updateFormFields({
                ['hometown']: hometownValue
            }));
            
            dispatch(updateFieldAndSaveToAPI({
                 fieldName: 'hometown',
                 value: {permanent_country: country, permanent_state: district, permanent_city: upazila} 
                }));
            
        }
    }, [country, district, upazila, dispatch, attributes.countries, attributes.states, attributes.cities]);

    // Find country name by ID
    const getCountryNameById = (id: number) => {
        const foundCountry = attributes.countries?.find(c => c.id === id);
        return foundCountry ? foundCountry.name : '';
    };

    // Find district name by ID
    const getDistrictNameById = (id: number) => {
        const foundDistrict = attributes.states?.find(d => d.id === id);
        return foundDistrict ? foundDistrict.name : '';
    };

    // Find upazila name by ID
    const getUpazilaNameById = (id: number) => {
        const foundUpazila = attributes.cities?.find(u => u.id === id);
        return foundUpazila ? foundUpazila.name : '';
    };

    return (
        <div className="flex flex-col bg-white">
            {/* Hometown icon */}
            <div className="flex justify-center mt-4">
                <div className="w-32 h-32 rounded-full flex items-center justify-center">
                    <img 
                        src="/src/images/registration/hometown.png" 
                        alt="Hometown" 
                        className="w-32 h-32"
                    />
                </div>
            </div>

            {/* Title */}
            <div className="mt-6 px-6">
                <h1 className="text-2xl font-bold text-center">Select your hometown</h1>
            </div>

            {/* Form fields */}
            <div className="mt-8 px-6 space-y-6">
                {/* Country */}
                <div ref={countryRef}>
                    <label className="block text-lg font-medium mb-2">Country</label>
                    <div className="relative">
                        <div 
                            className="w-full p-3 border border-gray-300 rounded-md flex justify-between items-center cursor-pointer"
                            onClick={() => setCountryDropdownOpen(!countryDropdownOpen)}
                        >
                            <span className={country ? '' : 'text-gray-400'}>
                                {country ? getCountryNameById(country) : 'Select Country'}
                            </span>
                            <ChevronDown size={20} className="text-gray-500" />
                        </div>
                        
                        {countryDropdownOpen && (
                            <div className="absolute z-10 mt-1 w-full bg-white border border-gray-300 rounded-md shadow-lg">
                                <div className="p-2 border-b">
                                    <div className="relative">
                                        <input
                                            type="text"
                                            value={countrySearch}
                                            onChange={(e) => setCountrySearch(e.target.value)}
                                            placeholder="Search country..."
                                            className="w-full p-2 pl-8 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary"
                                        />
                                        <Search size={16} className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400" />
                                        {countrySearch && (
                                            <X 
                                                size={16} 
                                                className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer" 
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    setCountrySearch('');
                                                }}
                                            />
                                        )}
                                    </div>
                                </div>
                                <div className="max-h-60 overflow-y-auto">
                                    {filteredCountries.length > 0 ? (
                                        filteredCountries.map((c) => (
                                            <div 
                                                key={c.id} 
                                                className="p-2 hover:bg-gray-100 cursor-pointer"
                                                onClick={() => {
                                                    setCountry(c.id);
                                                    setCountryDropdownOpen(false);
                                                }}
                                            >
                                                {c.name}
                                            </div>
                                        ))
                                    ) : (
                                        <div className="p-4 text-center text-gray-500">No countries found</div>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
                
                {/* District */}
                <div ref={districtRef}>
                    <label className="block text-lg font-medium mb-2">District</label>
                    <div className="relative">
                        <div 
                            className={`w-full p-3 border border-gray-300 rounded-md flex justify-between items-center ${country ? 'cursor-pointer' : 'bg-gray-100 cursor-not-allowed'}`}
                            onClick={() => country && setDistrictDropdownOpen(!districtDropdownOpen)}
                        >
                            <span className={district ? '' : 'text-gray-400'}>
                                {district ? getDistrictNameById(district) : 'Select District'}
                            </span>
                            <ChevronDown size={20} className="text-gray-500" />
                        </div>
                        
                        {districtDropdownOpen && country && (
                            <div className="absolute z-10 mt-1 w-full bg-white border border-gray-300 rounded-md shadow-lg">
                                <div className="p-2 border-b">
                                    <div className="relative">
                                        <input
                                            type="text"
                                            value={districtSearch}
                                            onChange={(e) => setDistrictSearch(e.target.value)}
                                            placeholder="Search district..."
                                            className="w-full p-2 pl-8 border border-gray-300 rounded-md"
                                        />
                                        <Search size={16} className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400" />
                                        {districtSearch && (
                                            <X 
                                                size={16} 
                                                className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer" 
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    setDistrictSearch('');
                                                }}
                                            />
                                        )}
                                    </div>
                                </div>
                                <div className="max-h-60 overflow-y-auto">
                                    {filteredDistricts.length > 0 ? (
                                        filteredDistricts.map((d) => (
                                            <div 
                                                key={d.id} 
                                                className="p-2 hover:bg-gray-100 cursor-pointer"
                                                onClick={() => {
                                                    setDistrict(Number(d.id)); // Ensure it's a number
                                                    setDistrictDropdownOpen(false);
                                                }}
                                            >
                                                {d.name}
                                            </div>
                                        ))
                                    ) : (
                                        <div className="p-4 text-center text-gray-500">No districts found</div>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
                
                {/* Upazila */}
                <div ref={upazilaRef}>
                    <label className="block text-lg font-medium mb-2">Upazila</label>
                    <div className="relative">
                        <div 
                            className={`w-full p-3 border border-gray-300 rounded-md flex justify-between items-center ${district ? 'cursor-pointer' : 'bg-gray-100 cursor-not-allowed'}`}
                            onClick={() => district && setUpazilaDropdownOpen(!upazilaDropdownOpen)}
                        >
                            <span className={upazila ? '' : 'text-gray-400'}>
                                {upazila ? getUpazilaNameById(upazila) : 'Select Upazila'}
                            </span>
                            <ChevronDown size={20} className="text-gray-500" />
                        </div>
                        
                        {upazilaDropdownOpen && district && (
                            <div className="absolute z-10 mt-1 w-full bg-white border border-gray-300 rounded-md shadow-lg">
                                <div className="p-2 border-b">
                                    <div className="relative">
                                        <input
                                            type="text"
                                            value={upazilaSearch}
                                            onChange={(e) => setUpazilaSearch(e.target.value)}
                                            placeholder="Search upazila..."
                                            className="w-full p-2 pl-8 border border-gray-300 rounded-md"
                                        />
                                        <Search size={16} className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400" />
                                        {upazilaSearch && (
                                            <X 
                                                size={16} 
                                                className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer" 
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    setUpazilaSearch('');
                                                }}
                                            />
                                        )}
                                    </div>
                                </div>
                                <div className="max-h-60 overflow-y-auto">
                                    {filteredUpazilas.length > 0 ? (
                                        filteredUpazilas.map((u) => (
                                            <div 
                                                key={u.id} 
                                                className="p-2 hover:bg-gray-100 cursor-pointer"
                                                onClick={() => {
                                                    setUpazila(Number(u.id)); // Ensure it's a number
                                                    setUpazilaDropdownOpen(false);
                                                }}
                                            >
                                                {u.name}
                                            </div>
                                        ))
                                    ) : (
                                        <div className="p-4 text-center text-gray-500">No upazilas found</div>
                                    )}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}
