import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Camera, ChevronRight, X } from 'lucide-react';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../app/store';
import { setIsModalOpen, updateFormField } from '../../app/reducers/candidateinformation';
import Nickname from '../../components/registration/Nickname';
import { fetchRegistrationStep1Data, setActiveField } from '../../app/reducers/registrationstep1';
import LoadingSpinner from '../../components/partials/LoadingSpinner';
import FullName from '../../components/registration/FullName';
import Gender from '../../components/registration/Gender';
import DateOfBirth from '../../components/registration/DateOfBirth';

export default function CandidateInformation() {
    const candidateinformation = useSelector((state: RootState) => state.candidateInformation);
    const { activeField, dataFetched } = useSelector((state: RootState) => state.registrationstep1);

    const dispatch = useDispatch<AppDispatch>();
    const [profilePicture, setProfilePicture] = useState<string | null>(null);

    useEffect(() => {
        dispatch(fetchRegistrationStep1Data());
      }, [dispatch]);

    const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            const reader = new FileReader();
            reader.onload = (event) => {
                setProfilePicture(event.target?.result as string);
            };
            reader.readAsDataURL(e.target.files[0]);
        }
    };

    const openFieldEditor = (fieldKey: string) => {
        dispatch(setActiveField(fieldKey));
        dispatch(setIsModalOpen(true));
      };
    
    const getNextFieldKey = (currentKey: string ) => {
        const fieldKeys = Object.keys(candidateinformation.formFields);
        const currentIndex = fieldKeys.indexOf(currentKey);
        if (currentIndex < fieldKeys.length - 1) {
          return fieldKeys[currentIndex + 1];
        }
        return null; // No more fields
      };
      const renderActiveField = () => {
        switch (activeField) {
          case 'nickname':
            return <Nickname />;
          case 'fullName':
                return <FullName />;
          case 'gender':
            return <Gender />;
          case 'dateOfBirth':
            return <DateOfBirth />;
          default:
            return null;
        }
      };

    return (
        <div className="w-full max-w-4xl mx-auto px-4 py-6 pt-1">
            {!dataFetched ? <LoadingSpinner /> : ''}
            {/* Progress bar */}
            <div className="mb-0 bg-white p-4 rounded-lg">
                <div className="relative flex items-center justify-between z-2 w-[50%] m-auto">
                {/* Line connecting all circles */}
                <div className="absolute h-0.5 bg-gray-200 w-full"></div>
                
                {/* Active line */}
                <div className="absolute h-0.5 bg-primary w-full"></div>
                
                {/* Step circles */}
                <Link to="/registration/step-1">
                    <div className="relative z-0 flex items-center justify-center w-[24px] h-[25px] rounded-full bg-primary text-white border-2 border-primary">
                        <span className="text-xs">1</span>
                    </div>
                </Link>
                <div className="relative cursor-pointer z-0 flex items-center justify-center w-[24px] h-[25px] rounded-full bg-primary text-white border-2 border-gray-200">
                    <span className="text-xs">2</span>
                </div>
                </div>
        
        {/* Step labels */}
        <div className="flex justify-between mt-2 text-xs z-5">
          <span className="text-primary font-medium"></span>
          <span className="text-primary font-medium"></span>
        </div>
      </div>

            <h1 className="text-2xl font-bold mb-6">Candidate Information</h1>

            {/* Profile Picture Upload */}
            <div className="mb-8 flex justify-start">
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 flex flex-col items-center justify-center w-48 h-60 relative">
                    {profilePicture ? (
                        <img 
                            src={profilePicture} 
                            alt="Profile" 
                            className="w-full h-full object-cover rounded-lg"
                        />
                    ) : (
                        <>
                            <span className="text-gray-400 text-center mb-2">Add Profile picture</span>
                            <label htmlFor="profilePicture" className="cursor-pointer absolute bottom-4 right-5">
                                <div className="bg-gray-200 rounded-full p-2">
                                    <Camera className="h-6 w-6 text-red-400" />
                                </div>
                            </label>
                        </>
                    )}
                    <input 
                        type="file" 
                        id="profilePicture" 
                        className="hidden" 
                        accept="image/*"
                        onChange={handleImageUpload}
                    />
                </div>
            </div>

            {/* Form Fields */}
            <div className="space-y-4">
                {Object.entries(candidateinformation.formFields).map(([key, field]) => (
                <div key={key} className="border-b border-gray-200 py-3">
                    <button 
                    className="w-full flex justify-between items-center"
                    onClick={() => openFieldEditor(key)}
                    >
                    <div>
                        <h3 className="font-bold text-left">{field.label}</h3>
                        {field.value ? (
                        <p className="text-sm text-left text-gray-700">
                            {typeof field.value === 'object' && field.value !== null && 'name' in field.value 
                            ? (field.value.id === 0 ? <span className="text-red-400">{field.placeholder}</span> : field.value.name)
                            : field.value}
                        </p>
                        ) : (
                        <p className="text-sm text-red-400">{field.placeholder}</p>
                        )}
                    </div>
                    <ChevronRight className="h-5 w-5 text-gray-400" />
                    </button>
                </div>
                ))}
            </div>

            {/* Update Button */}
            <div className="mt-8">
                <button className="w-full py-3 px-4 bg-primary text-white rounded-full font-medium hover:bg-pink-600 transition-colors">
                    Update
                </button>
            </div>

            {candidateinformation.isModalOpen && activeField && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                <div className="bg-white rounded-lg w-full max-w-3xl p-6">
                <div className="flex justify-between items-center mb-4">
                    <h3 className="text-lg font-bold">{candidateinformation.formFields[activeField].label}</h3>
                    <button 
                    onClick={() => dispatch(setIsModalOpen(false))}
                    className="text-gray-500 hover:text-gray-700"
                    >
                    <X size={20} />
                    </button>
                </div>
            
                <div className="mb-4">
                    {renderActiveField()}
                </div>
            
                {/* Continue button */}
                <div className="px-6 pb-8">
                    <button
                    onClick={() => {
                        dispatch(updateFormField({
                            fieldName: activeField,
                            value: candidateinformation.formFields[activeField].value
                        }))
                        const nextField = getNextFieldKey(activeField);
                        if (nextField) {
                            setActiveField(nextField);
                        } else {
                            dispatch(setIsModalOpen(false));
                        }
                        }
                    }
                    className="w-full py-3 px-4 bg-primary text-white rounded-full font-medium hover:bg-pink-600 transition-colors"
                    >
                    Continue
                    </button>
                    
                </div>
                </div>
            </div>
            )}
        </div>
    );
}