import { useState, useEffect } from 'react';
import { Search } from 'lucide-react';
import { useDispatch, useSelector } from 'react-redux';
import { updateFieldAndSaveToAPI, updateFormFields } from '../../app/reducers/registrationstep1';
import { AppDispatch, RootState } from '../../app/store';

interface Country {
  id: number;
  name: string;
  code: string;
  flag: string;
}

export default function CitizenshipCountry() {
    const registrationstep1 = useSelector((state: RootState) => state.registrationstep1);
    const { attributes } = useSelector((state: RootState) => state.profileattributelist);

    const dispatch = useDispatch<AppDispatch>();
    const [searchQuery, setSearchQuery] = useState('');
    const [filteredCountries, setFilteredCountries] = useState<Country[]>([]);

    
    useEffect(() => {
        const filtered = attributes.countries
            .filter(country => 
                country.name.toLowerCase().includes(searchQuery.toLowerCase())
            )
            .map(country => ({
                id: country.id,
                name: country.name,
                code: country.code || '',
                flag: country.flag || '' 
            }));
            
        setFilteredCountries(filtered);
    }, [searchQuery, attributes.countries]);

    const handleCountrySelect = (country: Country) => {
        dispatch(updateFormFields({
            ['citizenshipCountry']: country.name
        }));

        dispatch(updateFieldAndSaveToAPI({ fieldName: 'citizenshipCountry', value: {citizenshipCountry: country.id } }));
    };

    return (
        <div className="flex flex-col bg-white">
            {/* Citizenship icon */}
            <div className="flex justify-center mt-4">
                <div className="w-32 h-32 rounded-full bg-blue-100 flex items-center justify-center">
                    <img 
                        src="/src/images/registration/citizenship-country.png" 
                        alt="Citizenship" 
                        className="w-32 h-32"
                    />
                </div>
            </div>

            {/* Title */}
            <div className="mt-6 px-6">
                <h1 className="text-2xl font-bold text-center">Select your citizenship country</h1>
            </div>

            {/* Search bar */}
            <div className="mt-6 px-6">
                <div className="relative">
                    <input
                        type="text"
                        placeholder="Search..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full py-2 px-4 pr-10 bg-gray-100 rounded-full focus:outline-none"
                    />
                    <div className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                        <Search size={20} />
                    </div>
                </div>
            </div>

            {/* Country options */}
            <div className="mt-6 px-6">
                <div className="h-[300px] overflow-y-auto">
                    {filteredCountries.map((country) => (
                        <div 
                            key={country.id}
                            className={`py-3 border-b border-gray-100 flex items-center cursor-pointer ${
                                registrationstep1.formFields.citizenshipCountry.value === country.name ? 'text-primary' : ''
                            }`}
                            onClick={() => handleCountrySelect(country)}
                        >
                            <div className="flex items-center">
                                <span className="text-xl mr-3">{country.code}</span>
                                <span className={registrationstep1.formFields.citizenshipCountry.value === country.name ? 'text-primary' : ''}>{country.name}</span>
                            </div>
                            {registrationstep1.formFields.citizenshipCountry.value === country.name && (
                                <div className="ml-auto">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-primary" viewBox="0 0 20 20" fill="currentColor">
                                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                                    </svg>
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
}