import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { updateFormFields, updateStep3DataToAPI } from '../../app/reducers/registrationstep3';
import { AppDispatch, RootState } from '../../app/store';

export default function PartnerProfession() {
    const { attributes } = useSelector((state: RootState) => state.profileattributelist);
    const dispatch = useDispatch<AppDispatch>();
    const [openToAll, setOpenToAll] = useState(false);
    const [selectedProfessions, setSelectedProfessions] = useState<{id: number, name: string}[]>([]);
    
    useEffect(() => {
        if (openToAll && attributes.profession_list) {
            setSelectedProfessions([...attributes.profession_list]);
        } else if (selectedProfessions.length === attributes.profession_list?.length) {
            // If all professions are manually selected, also set openToAll to true
            setOpenToAll(true);
        }
    }, [openToAll, attributes.profession_list, selectedProfessions.length]);
    
    useEffect(() => {
        const professionNames = selectedProfessions.map(profession => profession.name);
        const professionString = professionNames.join(', ');
        
        if (selectedProfessions.length > 0) {
            dispatch(updateFormFields({
                ['profession']: professionString
            }));
            const professionIds = selectedProfessions.map(profession => profession.name);
            
            dispatch(updateStep3DataToAPI({ 
                fieldName: 'profession', 
                value: {professions: professionIds}
            }));
        }
    }, [selectedProfessions, dispatch]);
    
    const handleProfessionToggle = (profession: {id: number, name: string}) => {
        setSelectedProfessions(prev => {
            // Check if profession is already selected by ID
            const isSelected = prev.some(p => p.id === profession.id);
            
            if (isSelected) {
                // If profession is already selected, remove it
                const newProfessions = prev.filter(p => p.id !== profession.id);
                // If removing a profession means not all are selected, turn off openToAll
                if (newProfessions.length !== attributes.profession_list?.length) {
                    setOpenToAll(false);
                }
                return newProfessions;
            } else {
                // Otherwise add it
                const newProfessions = [...prev, profession];
                // If all professions are now selected, turn on openToAll
                if (newProfessions.length === attributes.profession_list?.length) {
                    setOpenToAll(true);
                }
                return newProfessions;
            }
        });
    };
    
    const handleOpenToAllToggle = () => {
        const newOpenToAll = !openToAll;
        setOpenToAll(newOpenToAll);
        
        if (newOpenToAll && attributes.profession_list) {
            // Select all professions
            setSelectedProfessions([...attributes.profession_list]);
        } else {
            // Deselect all professions
            setSelectedProfessions([]);
        }
    };

    return (
        <div className="flex flex-col bg-white">
            {/* Profession 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/profession.png" 
                        alt="Profession" 
                        className="w-32 h-32"
                    />
                </div>
            </div>

            {/* Title */}
            <div className="mt-6 px-6">
                <h1 className="text-2xl font-bold text-center">Partner's profession</h1>
            </div>

            {/* Open to all toggle */}
            <div className="mt-12 px-6 flex justify-between items-center">
                <span className="text-lg font-medium">Open to all</span>
                <div 
                    className={`w-12 h-6 rounded-full p-1 flex items-center cursor-pointer ${openToAll ? 'bg-primary justify-end' : 'bg-gray-300 justify-start'}`}
                    onClick={handleOpenToAllToggle}
                >
                    <div className="bg-white w-4 h-4 rounded-full shadow-md"></div>
                </div>
            </div>

            {/* Profession options - scrollable */}
            <div className="mt-6 px-6">
                <div className="h-[300px] overflow-y-auto">
                    {attributes.profession_list && attributes.profession_list.map((profession) => (
                        <div 
                            key={profession.id}
                            className={`py-3 border-b border-gray-100 flex items-center cursor-pointer ${
                                selectedProfessions.some(p => p.id === profession.id) ? 'text-primary' : ''
                            }`}
                            onClick={() => handleProfessionToggle(profession)}
                        >
                            <span className={selectedProfessions.some(p => p.id === profession.id) ? 'text-primary' : ''}>{profession.name}</span>
                            {selectedProfessions.some(p => p.id === profession.id) && (
                                <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>
    );
}