import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/Components/ui/tooltip";
import { HelpCircle, Edit2, List } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';

export default function LocationSelector({ onLocationChange, initialCountry, initialState, initialCity, errorCountry }) {
    const { t } = useTranslation();
    const [countries, setCountries] = useState([]);
    const [states, setStates] = useState([]);
    const [cities, setCities] = useState([]);

    const [selectedCountry, setSelectedCountry] = useState(initialCountry?.toString() || '');
    
    const [selectedState, setSelectedState] = useState(initialState?.toString() || '');
    const [customState, setCustomState] = useState('');
    const [isManualState, setIsManualState] = useState(false);

    const [selectedCity, setSelectedCity] = useState(initialCity?.toString() || '');
    const [customCity, setCustomCity] = useState('');
    const [isManualCity, setIsManualCity] = useState(false);

    const [loading, setLoading] = useState({ countries: true, states: false, cities: false });

    useEffect(() => {
        axios.get('/api/locations/countries').then(res => {
            setCountries(res.data);
            setLoading(prev => ({ ...prev, countries: false }));
        });
    }, []);

    useEffect(() => {
        if (!selectedCountry) return;
        setLoading(prev => ({ ...prev, states: true }));
        axios.get(`/api/locations/countries/${selectedCountry}/states`).then(res => {
            setStates(res.data);
            setLoading(prev => ({ ...prev, states: false }));
        });
    }, [selectedCountry]);

    useEffect(() => {
        if (!selectedState && !isManualState) return;
        if (isManualState) {
            setCities([]);
            return;
        }
        setLoading(prev => ({ ...prev, cities: true }));
        axios.get(`/api/locations/states/${selectedState}/cities`).then(res => {
            setCities(res.data);
            setLoading(prev => ({ ...prev, cities: false }));
        });
    }, [selectedState, isManualState]);

    useEffect(() => {
        const countryObj = countries.find(c => c.id.toString() === selectedCountry);
        onLocationChange({
            country_id: selectedCountry,
            state_id: isManualState ? '' : selectedState,
            city_id: isManualCity ? '' : selectedCity,
            custom_state_name: isManualState ? customState : '',
            custom_city_name: isManualCity ? customCity : '',
            phone_code: countryObj?.phone_code || '' 
        });
    }, [selectedCountry, selectedState, selectedCity, customState, customCity, isManualState, isManualCity, countries]);

    const handleCountryChange = (val) => {
        setSelectedCountry(val);
        setSelectedState('');
        setSelectedCity('');
        setCustomState('');
        setCustomCity('');
        setIsManualState(false);
        setIsManualCity(false);
    };

    return (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 w-full">
            
            {/* COUNTRY SELECT */}
            <div className="space-y-2">
                <Label>{t('Country')} <span className="text-red-500">*</span></Label>
                <Select value={selectedCountry} onValueChange={handleCountryChange} disabled={loading.countries}>
                    <SelectTrigger className={`bg-background ${errorCountry ? "border-destructive" : ""}`}>
                        <SelectValue placeholder={loading.countries ? t('Loading...') : t('Select Country')} />
                    </SelectTrigger>
                    <SelectContent>
                        {countries.map(c => <SelectItem key={c.id} value={c.id.toString()}>{c.name}</SelectItem>)}
                    </SelectContent>
                </Select>
            </div>

            {/* STATE / REGION */}
            <div className="space-y-2">
                <div className="flex items-center justify-between mb-1.5 w-full">
                    <div className="flex items-center gap-2">
                        <Label className="font-semibold text-sm">{t('State / Region')}</Label>
                        <TooltipProvider>
                            <Tooltip delayDuration={100}>
                                <TooltipTrigger type="button" className="cursor-help mt-0.5">
                                    <HelpCircle className="w-3.5 h-3.5 text-muted-foreground hover:text-foreground transition-colors"/>
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p className="text-xs">{t('If your state is missing from the list, click "Type Manually".')}</p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>
                    </div>
                    <button 
                        type="button" 
                        onClick={() => { 
                            setIsManualState(!isManualState); 
                            if (!isManualState) setIsManualCity(true); 
                            setCustomState('');
                        }} 
                        className="text-[10px] text-primary hover:underline flex items-center gap-1 font-bold uppercase shrink-0"
                    >
                        {isManualState ? <><List className="w-3 h-3"/> {t('Select List')}</> : <><Edit2 className="w-3 h-3"/> {t('Type Manually')}</>}
                    </button>
                </div>

                {isManualState ? (
                    <Input value={customState} onChange={e => setCustomState(e.target.value)} placeholder={t('e.g. Texas')} className="bg-background" />
                ) : (
                    <Select value={selectedState} onValueChange={(val) => { setSelectedState(val); setSelectedCity(''); }} disabled={!selectedCountry || loading.states || states.length === 0}>
                        <SelectTrigger className="bg-background">
                            <SelectValue placeholder={loading.states ? t('Loading...') : states.length === 0 ? t('N/A') : t('Select State')} />
                        </SelectTrigger>
                        <SelectContent>
                            {states.map(s => <SelectItem key={s.id} value={s.id.toString()}>{s.name}</SelectItem>)}
                        </SelectContent>
                    </Select>
                )}
            </div>

            {/* CITY */}
            <div className="space-y-2">
                <div className="flex items-center justify-between mb-1.5 w-full">
                    <div className="flex items-center gap-2">
                        <Label className="font-semibold text-sm">{t('City')}</Label>
                        <TooltipProvider>
                            <Tooltip delayDuration={100}>
                                <TooltipTrigger type="button" className="cursor-help mt-0.5">
                                    <HelpCircle className="w-3.5 h-3.5 text-muted-foreground hover:text-foreground transition-colors"/>
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p className="text-xs">{t('If your city is missing, click "Type Manually".')}</p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>
                    </div>
                    <button 
                        type="button" 
                        onClick={() => {
                            setIsManualCity(!isManualCity);
                            setCustomCity('');
                        }} 
                        className="text-[10px] text-primary hover:underline flex items-center gap-1 font-bold uppercase shrink-0"
                    >
                        {isManualCity ? <><List className="w-3 h-3"/> {t('Select List')}</> : <><Edit2 className="w-3 h-3"/> {t('Type Manually')}</>}
                    </button>
                </div>

                {isManualCity || isManualState ? (
                    <Input value={customCity} onChange={e => setCustomCity(e.target.value)} placeholder={t('e.g. Dallas')} className="bg-background" />
                ) : (
                    <Select value={selectedCity} onValueChange={setSelectedCity} disabled={!selectedState || loading.cities || cities.length === 0}>
                        <SelectTrigger className="bg-background">
                            <SelectValue placeholder={loading.cities ? t('Loading...') : cities.length === 0 ? t('N/A') : t('Select City')} />
                        </SelectTrigger>
                        <SelectContent>
                            {cities.map(c => <SelectItem key={c.id} value={c.id.toString()}>{c.name}</SelectItem>)}
                        </SelectContent>
                    </Select>
                )}
            </div>

        </div>
    );
}