import React, { useState, useRef, ChangeEvent, KeyboardEvent, ClipboardEvent } from 'react';
import { SunIcon, MoonIcon, SuitcaseIcon } from '../Icons';
import AnimatedBackground from './AnimatedBackground';

interface VerificationPageProps {
    onVerify: (code: string) => void;
    onResend: () => void;
    theme: string;
    toggleTheme: () => void;
}

const VerificationPage: React.FC<VerificationPageProps> = ({ onVerify, onResend, theme, toggleTheme }) => {
    const [otp, setOtp] = useState<string[]>(new Array(6).fill(''));
    const inputsRef = useRef<(HTMLInputElement | null)[]>([]);

    const isDark = theme === 'dark';

    const handleChange = (e: ChangeEvent<HTMLInputElement>, index: number) => {
        const value = e.target.value;
        if (isNaN(Number(value))) return;

        const newOtp = [...otp];
        newOtp[index] = value.substring(value.length - 1);
        setOtp(newOtp);

        if (value && index < 5) {
            inputsRef.current[index + 1]?.focus();
        }
    };

    const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>, index: number) => {
        if (e.key === 'Backspace' && !otp[index] && index > 0) {
            inputsRef.current[index - 1]?.focus();
        }
    };

    const handlePaste = (e: ClipboardEvent<HTMLDivElement>) => {
        e.preventDefault();
        const pasteData = e.clipboardData.getData('text');
        if (pasteData.length === 6 && /^\d+$/.test(pasteData)) {
            const newOtp = pasteData.split('');
            setOtp(newOtp);
            inputsRef.current[5]?.focus();
        }
    };
    
    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        const code = otp.join('');
        if (code.length === 6) {
            onVerify(code);
        } else {
            alert('لطفاً کد 6 رقمی را کامل وارد کنید.');
        }
    };

    return (
        <div className={`relative flex items-center justify-center min-h-screen font-sans overflow-hidden
            ${isDark 
                ? 'bg-custom-dark-blue text-white bg-[radial-gradient(#27314e_1px,transparent_1px)]' 
                : 'bg-gradient-to-br from-gray-100 via-purple-50 to-indigo-100 text-gray-800 bg-[radial-gradient(#c7d2fe_1px,transparent_1px)]'
            } [background-size:16px_16px]`}
        >
            <AnimatedBackground />
            
            {/* دکمه تغییر تم */}
            <div className="absolute top-6 left-6 z-20">
                <button 
                    onClick={toggleTheme} 
                    className={`p-2 rounded-full cursor-pointer shadow-md transition-colors
                        ${isDark 
                            ? 'bg-custom-dark-blue-light' 
                            : 'bg-white border border-gray-200 hover:bg-gray-50'
                        }`}
                    aria-label="Toggle theme"
                >
                    {isDark ? (
                        <SunIcon className="h-6 w-6 text-yellow-400" />
                    ) : (
                        <MoonIcon className="h-6 w-6 text-indigo-600" />
                    )}
                </button>
            </div>

            {/* کارت اصلی */}
            <div className={`relative z-10 w-full max-w-md p-8 space-y-8 rounded-2xl shadow-xl backdrop-blur-sm
                ${isDark 
                    ? 'bg-custom-dark-blue-light/80 border border-white/10' 
                    : 'bg-white/90 border border-gray-200 shadow-purple-100/50'
                }`}
            >
                <div className="text-center">
                    <div className="flex items-center justify-center mb-6">
                        <SuitcaseIcon className={`w-12 h-12 ${isDark ? 'text-custom-purple' : 'text-indigo-600'}`} />
                        <span className={`text-4xl font-bold mr-3 ${isDark ? 'text-white' : 'text-gray-800'}`}>
                            اینوببر
                        </span>
                    </div>
                    <h2 className={`text-2xl font-bold ${isDark ? 'text-white' : 'text-gray-800'}`}>
                        کد تایید را وارد کنید
                    </h2>
                    <p className={`mt-2 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
                        کد تایید برای شما ارسال گردید.
                    </p>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="flex justify-center gap-2 mb-6" dir="ltr" onPaste={handlePaste}>
                        {otp.map((data, index) => (
                            <input
                                key={index}
                                type="text"
                                name="otp"
                                inputMode="numeric"
                                pattern="[0-9]*"
                                maxLength={1}
                                className={`w-12 h-14 sm:w-14 sm:h-14 text-center text-2xl font-semibold rounded-lg focus:outline-none focus:ring-2 transition-colors
                                    ${isDark 
                                        ? 'bg-custom-dark-blue border border-gray-700 text-white focus:ring-custom-purple' 
                                        : 'bg-gray-50 border border-gray-300 text-gray-800 focus:ring-indigo-500 focus:border-indigo-500'
                                    }`}
                                value={data}
                                onChange={(e) => handleChange(e, index)}
                                onKeyDown={(e) => handleKeyDown(e, index)}
                                ref={(el) => { inputsRef.current[index] = el; }}
                                autoFocus={index === 0}
                            />
                        ))}
                    </div>
                    <button
                        type="submit"
                        className={`w-full py-3 px-4 rounded-lg font-semibold transition-colors duration-300 text-white
                            ${isDark 
                                ? 'bg-custom-purple hover:bg-custom-light-purple' 
                                : 'bg-indigo-600 hover:bg-indigo-700 shadow-lg shadow-indigo-200'
                            }`}
                    >
                        ادامه
                    </button>
                </form>

                <div className="text-center">
                    <button 
                        onClick={onResend} 
                        className={`text-sm hover:underline transition-colors
                            ${isDark 
                                ? 'text-custom-light-purple' 
                                : 'text-indigo-600 hover:text-indigo-700'
                            }`}
                    >
                        دریافت مجدد کد
                    </button>
                </div>
            </div>
        </div>
    );
};

export default VerificationPage;
