"use client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { FiPlus, FiSearch, FiX, FiLoader } from "react-icons/fi"
import { useState, useEffect } from "react"
import { toast } from "sonner"
import { useAuth } from "@/context/AuthContext"
import { getInterests, saveInterests } from "@/services/userPanelService"
import { getCities, City } from "@/lib/api"

const AreasOfInterestPage = () => {
    const { token } = useAuth();
    const [allCities, setAllCities] = useState<City[]>([]);
    const [selectedCities, setSelectedCities] = useState<City[]>([]);
    const [inputValue, setInputValue] = useState('');
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const [lastSavedCityIds, setLastSavedCityIds] = useState<number[]>([]);

    // Load cities and existing interests on mount
    useEffect(() => {
        const load = async () => {
            const [cities, interests] = await Promise.all([
                getCities(),
                token ? getInterests(token) : Promise.resolve(null),
            ]);
            setAllCities(cities);

            if (interests) {
                // Map city IDs to full city objects
                const matched = interests.cityIds
                    .map((id) => cities.find((c) => c.id === id))
                    .filter((c): c is City => !!c);
                setSelectedCities(matched);
                setLastSavedCityIds(interests.cityIds);
            }
            setLoading(false);
        };
        load();
    }, [token]);

    // Filter suggestions based on input
    const suggestions = inputValue.trim()
        ? allCities.filter(
            (city) =>
                city.name.includes(inputValue) &&
                !selectedCities.some((sc) => sc.id === city.id)
        )
        : [];

    const handleAddCity = (city: City) => {
        if (selectedCities.some((sc) => sc.id === city.id)) return;
        setSelectedCities((prev) => [...prev, city]);
        setInputValue('');
        setShowSuggestions(false);
    };

    const handleRemoveCity = (index: number) => {
        const updated = selectedCities.filter((_, i) => i !== index);
        setSelectedCities(updated);

        // If last city is removed, auto-save immediately to sync with backend
        if (updated.length === 0 && lastSavedCityIds.length > 0) {
            handleSave(updated);
        }
    };

    const handleSave = async (citiesToSave = selectedCities) => {
        if (!token) return;
        setSaving(true);
        const cityIds = citiesToSave.map((c) => c.id);
        const success = await saveInterests(token, {
            city_ids: cityIds,
            governorate_ids: [],
            district_ids: [],
        });
        setSaving(false);
        if (success) {
            setLastSavedCityIds(cityIds);
            toast.success("تم حفظ مناطق الاهتمام بنجاح");
        } else {
            toast.error("فشل حفظ مناطق الاهتمام. يرجى المحاولة لاحقاً.");
        }
    };

    if (loading) {
        return (
            <div className="flex-1 flex items-center justify-center py-20">
                <div className="w-8 h-8 border-2 border-[#0092B8] border-t-transparent rounded-full animate-spin" />
            </div>
        );
    }

    return (
        <div>
            <h4 className="mb-2 text-[#1D293D] text-lg font-medium"> مناطق الاهتمام </h4>

            <div className="flex-1 overflow-auto">
                <div className="p-2 pr-7 relative flex gap-2 border border-[#CAD5E2] rounded-full">
                    <FiSearch className="absolute top-1/2 right-2 -translate-y-1/2 text-[#90A1B9]" />
                    <Input
                        type="text"
                        placeholder="ابحث عن المدينه"
                        className="placeholder:text-[#90A1B9] md:text-base p-0 border-0 focus-visible:ring-0 shadow-none"
                        value={inputValue}
                        onChange={(e) => {
                            setInputValue(e.target.value);
                            setShowSuggestions(true);
                        }}
                        onFocus={() => setShowSuggestions(true)}
                        onKeyDown={(e) => {
                            if (e.key === 'Enter' && suggestions.length > 0) {
                                handleAddCity(suggestions[0]);
                            }
                        }}
                    />

                    <Button
                        className="rounded-full font-normal gap-1"
                        onClick={() => { if (suggestions.length > 0) handleAddCity(suggestions[0]); }}
                    >
                        <FiPlus />
                        اضف
                    </Button>
                </div>

                {/* Autocomplete suggestions */}
                {showSuggestions && suggestions.length > 0 && (
                    <div className="mt-1 bg-white border border-[#CAD5E2] rounded-lg shadow-lg max-h-48 overflow-y-auto z-50 relative">
                        {suggestions.map((city) => (
                            <button
                                key={city.id}
                                className="w-full text-right px-4 py-2 hover:bg-[#F1F5F9] transition-colors"
                                onClick={() => handleAddCity(city)}
                            >
                                {city.name}
                            </button>
                        ))}
                    </div>
                )}

                {selectedCities.length > 0 && (
                    <div className="p-4 mt-4 flex flex-wrap gap-2 bg-[#F1F5F9] rounded-xl">
                        {selectedCities.map((city, index) => (
                            <div key={city.id} className="px-3 py-1 flex items-center gap-2 bg-[#E2E8F0] border border-[#CAD5E2] rounded-full">
                                <span className="text-[#0F172B]">{city.name}</span>
                                <Button
                                    className="p-1 w-auto h-auto bg-[#F1F5F9] rounded-full"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => handleRemoveCity(index)}
                                >
                                    <FiX />
                                </Button>
                            </div>
                        ))}
                    </div>
                )}

                {/* Show Save button only if there are unsaved changes AND it's not empty (empty state auto-saves) */}
                {selectedCities.length > 0 &&
                    JSON.stringify(selectedCities.map(c => c.id).sort()) !== JSON.stringify([...lastSavedCityIds].sort()) && (
                        <div className="mt-4 flex justify-end">
                            <Button
                                className="rounded-full font-normal px-6"
                                onClick={() => handleSave()}
                                disabled={saving}
                            >
                                {saving ? <FiLoader className="animate-spin ml-2" /> : null}
                                حفظ
                            </Button>
                        </div>
                    )}
            </div>
        </div>
    )
}

export default AreasOfInterestPage