import { useState, useEffect } from 'react';
import countryIcon from '/src/images/registration/citizenship-country.png';
import { useDispatch, useSelector } from 'react-redux';
import { updateFormFields, updateStep3DataToAPI } from '../../app/reducers/registrationstep3';
import { AppDispatch, RootState } from '../../app/store';

interface Country {
    id: number;
    name: string;
    code: string;
    flag: string;
}

export default function PartnerCountry() {
    const { attributes } = useSelector((state: RootState) => state.profileattributelist);
    const dispatch = useDispatch<AppDispatch>();

    const [selectedCountries, setSelectedCountries] = useState<Country[]>([]);
    const [openToAll, setOpenToAll] = useState(false);
    
    useEffect(() => {
        if (selectedCountries.length > 0) {
            const countryNames = selectedCountries.map(country => country.name);
            dispatch(updateFormFields({
                country: countryNames.join(', ')
            }));
            
            // For API: array of country IDs
            const countryIds = selectedCountries.map(country => country.id);
            dispatch(updateStep3DataToAPI({
                fieldName: 'country',
                value: { preferred_countries: countryIds }
            }));
        } else if (openToAll) {
            dispatch(updateFormFields({
                country: 'all'
            }));
            const allCountryIds = attributes.countries.map(country => country.id);
            dispatch(updateStep3DataToAPI({
                fieldName: 'country',
                value: { preferred_countries: allCountryIds }
            }));
        }
    }, [selectedCountries, openToAll, attributes.countries, dispatch]);
    
    const handleCountryToggle = (country: Country) => {
        if (openToAll) return;
        
        setSelectedCountries(prev => {
            const isSelected = prev.some(c => c.id === country.id);
            
            if (isSelected) {
                return prev.filter(c => c.id !== country.id);
            } else {
                return [...prev, country];
            }
        });
    };
    
    const handleOpenToAllToggle = () => {
        const newOpenToAll = !openToAll;
        setOpenToAll(newOpenToAll);
        
        if (newOpenToAll) {
            // Clear specific selections when switching to "all"
            setSelectedCountries([]);
        }
    };
    
    return (
        <div className="p-6 bg-white rounded-lg shadow-sm">
            <div className="flex flex-col items-center mb-6">
                <div className="w-32 h-32 rounded-full bg-blue-100 flex items-center justify-center mb-4">
                    <img src={countryIcon} alt="Country" className="w-32 h-32" />
                </div>
                <h2 className="text-2xl font-bold text-gray-800">Partner's country</h2>
            </div>
            
            <div className="flex items-center justify-between mb-6">
                <span className="text-lg font-medium">Open to all</span>
                <div 
                    className={`w-12 h-6 rounded-full p-1 cursor-pointer ${openToAll ? 'bg-primary' : 'bg-gray-300'}`}
                    onClick={handleOpenToAllToggle}
                >
                    <div 
                        className={`bg-white w-4 h-4 rounded-full shadow-md transform duration-300 ease-in-out ${
                            openToAll ? 'translate-x-6' : ''
                        }`}
                    ></div>
                </div>
            </div>
            
            <div className="mt-4 h-[300px] overflow-y-auto">
                {attributes.countries && attributes.countries.map((country) => (
                    <div
                        key={country.id}
                        className={`py-3 border-b border-gray-100 flex items-center cursor-pointer ${
                            (selectedCountries.some(c => c.id === country.id) || openToAll) ? 'text-primary' : ''
                        }`}
                        onClick={() => handleCountryToggle({
                            id: country.id,
                            name: country.name,
                            code: country.code || '',
                            flag: country.flag || ''
                        })}
                    >
                        <span className="mr-3 text-xl">{country.code}</span>
                        <span className={selectedCountries.some(c => c.id === country.id) || openToAll ? 'text-primary' : ''}>
                            {country.name}
                        </span>
                        {(selectedCountries.some(c => c.id === country.id) || openToAll) && (
                            <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>
    );
}