import { useState, useRef, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { updateFormField, updateFieldAndSaveToAPI } from '../../app/reducers/registrationstep1';
import { AppDispatch } from '../../app/store';
import { Camera } from 'lucide-react';

export default function GuardianGovernmentID() {
    const dispatch = useDispatch<AppDispatch>();
    const [idType, setIdType] = useState<string>('');
    const [idNumber, setIdNumber] = useState<string>('');
    const [frontIdImage, setFrontIdImage] = useState<string | null>(null);
    const [backIdImage, setBackIdImage] = useState<string | null>(null);
    const frontIdInputRef = useRef<HTMLInputElement>(null);
    const backIdInputRef = useRef<HTMLInputElement>(null);
    const idNumberDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);


    useEffect(() => {
        if(idType && idNumber && frontIdImage && backIdImage){
            const guardian_govt_id = idType+' '+idNumber;
            dispatch(updateFormField({
                fieldName: 'guardian_govt_id',
                value: guardian_govt_id
            }));
        }
    }, [idType, idNumber, frontIdImage, backIdImage, dispatch])
    // Handle ID type change
    const handleIdTypeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const value = e.target.value;
        setIdType(value);
        dispatch(updateFieldAndSaveToAPI({ 
            fieldName: 'guardian_govt_id_type', 
            value: { guardian_govt_id_type: value } 
        }));
    };
    
    // Handle ID number change with debounce
    const handleIdNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        setIdNumber(value);
        // Clear any existing timer
        if (idNumberDebounceRef.current) {
            clearTimeout(idNumberDebounceRef.current);
        }
        
        // Set a new timer to trigger API call after 500ms of inactivity
        idNumberDebounceRef.current = setTimeout(() => {
            // Send to API only after user stops typing
            dispatch(updateFieldAndSaveToAPI({ 
                fieldName: 'guardian_govt_id_number', 
                value: { guardian_govt_id_number: value } 
            }));
        }, 500);
    };
    
    // Handle front ID image upload
    const handleFrontIdUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                const base64String = reader.result as string;
                setFrontIdImage(base64String);
                // Send to API
                dispatch(updateFieldAndSaveToAPI({ 
                    fieldName: 'guardian_govt_id_front', 
                    value: { guardian_govt_id_front: file } 
                }));
            };
            reader.readAsDataURL(file);
        }
    };
    
    // Handle back ID image upload
    const handleBackIdUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                const base64String = reader.result as string;
                setBackIdImage(base64String);
                // Send to API
                dispatch(updateFieldAndSaveToAPI({ 
                    fieldName: 'guardian_govt_id_back', 
                    value: { guardian_govt_id_back: file } 
                }));
            };
            reader.readAsDataURL(file);
        }
    };

    return (
        <div className="flex flex-col h-full">
            {/* Main content */}
            <div className="flex flex-col items-center">
                {/* ID Icon */}
                <div className="flex justify-center mt-4 mb-8">
                    <div className="w-32 h-32 rounded-full bg-yellow-100 flex items-center justify-center">
                        <img 
                            src="/src/images/registration/nid-circle.png" 
                            alt="Birthday" 
                            className="w-32 h-32"
                        />
                    </div>
                </div>

                {/* Title */}
                <h1 className="text-2xl font-bold mb-8">Government ID Information</h1>

                {/* ID Type Selection */}
                <div className="w-full mb-6">
                    <label className="block text-left mb-2">Select the Govt ID to verify :</label>
                    <div className="relative">
                        <select 
                            className="w-full p-3 border border-gray-300 rounded-lg appearance-none bg-white"
                            value={idType}
                            onChange={handleIdTypeChange}
                        >
                            <option value="" disabled>Select ID type</option>
                            <option value="nid">National ID Card</option>
                            <option value="passport">Passport</option>
                            <option value="driving">Driving License</option>
                        </select>
                        <div className="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none">
                            <svg className="w-4 h-4 fill-current" viewBox="0 0 20 20">
                                <path d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" />
                            </svg>
                        </div>
                    </div>
                </div>

                {/* ID Number Input */}
                <div className="w-full mb-8">
                    <label className="block text-left mb-2">Government ID number</label>
                    <input
                        type="text"
                        className="w-full p-3 border border-gray-300 rounded-lg"
                        value={idNumber}
                        onChange={handleIdNumberChange}
                        placeholder="19901234567890123"
                    />
                </div>

                {/* Scan Government ID */}
                <div className="w-full mb-6">
                    <h3 className="text-left mb-4">Scan Government ID</h3>
                    <div className="flex gap-4">
                        {/* Front Side */}
                        <div 
                            className="border border-gray-300 rounded-lg p-2 h-32 cursor-pointer relative"
                            onClick={() => frontIdInputRef.current?.click()}
                        >
                            {frontIdImage ? (
                                <>
                                    <img 
                                        src={frontIdImage}
                                        alt="Front Side" 
                                        className="w-full h-full object-contain"
                                    />
                                    <div className="absolute bottom-1 right-1 bg-primary rounded-full p-1">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                            <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path>
                                            <circle cx="12" cy="13" r="4"></circle>
                                        </svg>
                                    </div>
                                </>
                            ) : (
                                <div className="relative w-full h-full">
                                    <img 
                                        src="/src/images/registration/nid-demo.png"
                                        alt="Front Side" 
                                        className="w-full h-full object-contain"
                                    />
                                    <div className="absolute inset-0 bg-gray-500 bg-opacity-50"></div>
                                    <div className="absolute bottom-1 right-1 bg-primary rounded-full p-1">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                                            <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path>
                                            <circle cx="12" cy="13" r="4"></circle>
                                        </svg>
                                    </div>
                                </div>
                            )}
                            <input 
                                type="file" 
                                ref={frontIdInputRef}
                                className="hidden" 
                                accept="image/*"
                                onChange={handleFrontIdUpload}
                            />
                        </div>
                        
                        {/* Back Side */}
                        <div 
                            className="border border-gray-300 rounded-lg p-2 h-32 cursor-pointer relative"
                            onClick={() => backIdInputRef.current?.click()}
                        >
                            {backIdImage ? (
                                <>
                                    <img 
                                        src={backIdImage}
                                        alt="Back Side" 
                                        className="w-full h-full object-contain"
                                    />
                                    <div className="absolute bottom-1 right-1 bg-primary rounded-full p-1">
                                        <Camera className="h-4 w-4 text-white" />
                                    </div>
                                </>
                            ) : (
                                <div className="relative w-full h-full">
                                    <img 
                                        src="/src/images/registration/nid-back.png"
                                        alt="Back Side" 
                                        className="w-full h-full object-contain"
                                    />
                                    <div className="absolute inset-0 bg-gray-500 bg-opacity-50"></div>
                                    <div className="absolute bottom-1 right-1 bg-primary rounded-full p-1">
                                        <Camera className="h-4 w-4 text-white" />
                                    </div>
                                </div>
                            )}
                            <input 
                                type="file" 
                                ref={backIdInputRef}
                                className="hidden" 
                                accept="image/*"
                                onChange={handleBackIdUpload}
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}