/**
 * ForgotPasswordModal Component
 * @description Modal dialog for password recovery with two steps:
 * 1. Email input (forgot password)
 * 2. OTP verification (verify your email)
 * Features smooth animated transitions between steps.
 * Follows AgenticIQ Enterprise Coding Guidelines v1.0
 */

import { useState, useRef, useEffect, type FormEvent, type KeyboardEvent, type ClipboardEvent } from 'react';
import { motion, AnimatePresence, type Easing } from 'framer-motion';
import { AuthInput, AuthButton } from './index';

/**
 * Modal step type - determines which view to show
 */
type ModalStep = 'email' | 'verify';

/**
 * Props for ForgotPasswordModal component
 */
interface ForgotPasswordModalProps {
    /** Whether the modal is visible */
    isOpen: boolean;
    /** Callback when modal should close */
    onClose: () => void;
    /** Callback when email is submitted */
    onSubmit?: (email: string) => void;
    /** Callback when OTP is verified */
    onVerify?: (otp: string) => void;
}

/**
 * Close icon component
 */
function CloseIcon(): JSX.Element {
    return (
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M18 6L6 18M6 6L18 18" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
    );
}

/**
 * Left arrow icon component
 */
function ArrowLeftIcon(): JSX.Element {
    return (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 12H5M5 12L12 19M5 12L12 5" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
    );
}

/**
 * Smooth easing curve for animations (cubic-bezier)
 */
const smoothEasing: Easing = [0.4, 0, 0.2, 1];

/**
 * OTP Input component for 6-digit verification code
 */
function OTPInput({
    otp,
    setOtp,
}: {
    otp: string[];
    setOtp: React.Dispatch<React.SetStateAction<string[]>>;
}): JSX.Element {
    const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

    // Auto-focus first input when component mounts
    useEffect(() => {
        const timer = setTimeout(() => {
            inputRefs.current[0]?.focus();
        }, 300);
        return () => clearTimeout(timer);
    }, []);

    const handleChange = (index: number, value: string): void => {
        if (value.length > 1) value = value.slice(-1);
        if (value && !/^\d$/.test(value)) return;

        const newOtp = [...otp];
        newOtp[index] = value;
        setOtp(newOtp);

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

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

    const handlePaste = (e: ClipboardEvent<HTMLInputElement>): void => {
        e.preventDefault();
        const pastedData = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);
        const newOtp = [...otp];
        for (let i = 0; i < pastedData.length; i++) {
            newOtp[i] = pastedData[i];
        }
        setOtp(newOtp);
        const nextIndex = Math.min(pastedData.length, 5);
        inputRefs.current[nextIndex]?.focus();
    };

    return (
        <div className="flex gap-3 items-center justify-center">
            {otp.map((digit, index) => (
                <motion.input
                    key={index}
                    initial={{ opacity: 0, y: 8 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{
                        duration: 0.25,
                        delay: index * 0.04,
                        ease: smoothEasing,
                    }}
                    ref={(el) => { inputRefs.current[index] = el; }}
                    type="text"
                    inputMode="numeric"
                    maxLength={1}
                    value={digit}
                    onChange={(e) => handleChange(index, e.target.value)}
                    onKeyDown={(e) => handleKeyDown(e, index)}
                    onPaste={handlePaste}
                    className="
                        w-[44px] h-[44px]
                        bg-[rgba(255,255,255,0.15)]
                        border border-[rgba(255,255,255,0.1)]
                        rounded-[8px]
                        text-center text-white text-[18px] font-medium
                        outline-none
                        focus:border-[rgba(255,255,255,0.4)]
                        focus:bg-[rgba(255,255,255,0.2)]
                        transition-all duration-200
                    "
                    placeholder="•"
                    aria-label={`Digit ${index + 1}`}
                />
            ))}
        </div>
    );
}

/**
 * ForgotPasswordModal component
 * @description Modal with smooth transitions between email input and OTP verification.
 * @param {ForgotPasswordModalProps} props - Component props
 * @returns {JSX.Element} ForgotPasswordModal element
 */
export function ForgotPasswordModal({
    isOpen,
    onClose,
    onSubmit,
    onVerify,
}: ForgotPasswordModalProps): JSX.Element {
    const [step, setStep] = useState<ModalStep>('email');
    const [email, setEmail] = useState('');
    const [otp, setOtp] = useState<string[]>(['', '', '', '', '', '']);
    const [isLoading, setIsLoading] = useState(false);

    const handleClose = (): void => {
        onClose();
        setTimeout(() => {
            setStep('email');
            setEmail('');
            setOtp(['', '', '', '', '', '']);
            setIsLoading(false);
        }, 250);
    };

    const handleEmailSubmit = (e: FormEvent<HTMLFormElement>): void => {
        e.preventDefault();
        setIsLoading(true);
        onSubmit?.(email);
        setTimeout(() => {
            setIsLoading(false);
            setStep('verify');
        }, 600);
    };

    const handleVerifySubmit = (e: FormEvent<HTMLFormElement>): void => {
        e.preventDefault();
        const otpString = otp.join('');
        if (otpString.length !== 6) return;

        setIsLoading(true);
        onVerify?.(otpString);
        setTimeout(() => {
            setIsLoading(false);
            handleClose();
        }, 800);
    };

    const handleResendCode = (): void => {
        console.log('Resend code to:', email);
    };

    const handleBackdropClick = (): void => handleClose();
    const handleModalClick = (e: React.MouseEvent): void => e.stopPropagation();

    const isEmailStep = step === 'email';

    return (
        <AnimatePresence>
            {isOpen && (
                <>
                    {/* Backdrop */}
                    <motion.div
                        key="backdrop"
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        transition={{ duration: 0.25, ease: smoothEasing }}
                        onClick={handleBackdropClick}
                        className="fixed inset-0 z-50 bg-black/40 backdrop-blur-sm"
                    />

                    {/* Modal Container */}
                    <motion.div
                        key="modal-container"
                        initial={{ opacity: 0, scale: 0.96, y: 10 }}
                        animate={{ opacity: 1, scale: 1, y: 0 }}
                        exit={{ opacity: 0, scale: 0.96, y: 10 }}
                        transition={{ duration: 0.25, ease: smoothEasing }}
                        onClick={handleBackdropClick}
                        className="fixed inset-0 z-50 flex items-center justify-center p-4"
                    >
                        {/* Modal Card */}
                        <motion.div
                            layout
                            transition={{ duration: 0.3, ease: smoothEasing }}
                            onClick={handleModalClick}
                            className="
                                flex flex-col items-center gap-8
                                w-[520px] max-w-full
                                p-[42px]
                                rounded-[32px]
                                shadow-[0px_1px_2px_0px_rgba(16,24,40,0.05)]
                            "
                            style={{
                                background: 'linear-gradient(180deg, #00B8B7 0%, #001C8E 100%)',
                            }}
                        >
                            {/* Header with Close Button */}
                            <div className="flex items-start justify-between w-full gap-4">
                                {/* Title Section */}
                                <div className="flex-1 flex flex-col gap-[6px] items-center text-center">
                                    <AnimatePresence mode="wait">
                                        <motion.div
                                            key={isEmailStep ? 'email-header' : 'verify-header'}
                                            initial={{ opacity: 0, y: -5 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            exit={{ opacity: 0, y: 5 }}
                                            transition={{ duration: 0.2, ease: smoothEasing }}
                                        >
                                            <h2 className="text-[24px] font-semibold leading-[38px] text-white">
                                                {isEmailStep ? 'Forgot your password' : 'Verify Your Email'}
                                            </h2>
                                            <p className={isEmailStep 
                                                ? "text-[24px] font-semibold leading-[38px] text-white"
                                                : "text-[18px] font-medium leading-6 text-[rgba(255,255,255,0.75)] mt-1"
                                            }>
                                                {isEmailStep ? 'and continue' : 'Enter the 6-Digit Verification Code'}
                                            </p>
                                        </motion.div>
                                    </AnimatePresence>
                                </div>

                                {/* Close Button */}
                                <button
                                    type="button"
                                    onClick={handleClose}
                                    className="
                                        flex items-center justify-center
                                        w-8 h-8 rounded-full
                                        bg-[rgba(255,255,255,0.1)]
                                        hover:bg-[rgba(255,255,255,0.2)]
                                        transition-colors duration-200
                                        cursor-pointer shrink-0
                                    "
                                    aria-label="Close modal"
                                >
                                    <CloseIcon />
                                </button>
                            </div>

                            {/* Form Content */}
                            <div className="flex flex-col gap-6 items-center w-full">
                                <AnimatePresence mode="wait">
                                    {isEmailStep ? (
                                        <motion.form
                                            key="email-form"
                                            initial={{ opacity: 0, x: -20 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            exit={{ opacity: 0, x: 20 }}
                                            transition={{ duration: 0.25, ease: smoothEasing }}
                                            onSubmit={handleEmailSubmit}
                                            className="flex flex-col gap-6 w-full"
                                        >
                                            <AuthInput
                                                label="Email"
                                                type="email"
                                                placeholder="Enter your email address"
                                                value={email}
                                                onChange={(e) => setEmail(e.target.value)}
                                                isRequired
                                                autoComplete="email"
                                            />
                                            <AuthButton isLoading={isLoading}>
                                                Submit
                                            </AuthButton>
                                        </motion.form>
                                    ) : (
                                        <motion.form
                                            key="otp-form"
                                            initial={{ opacity: 0, x: 20 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            exit={{ opacity: 0, x: -20 }}
                                            transition={{ duration: 0.25, ease: smoothEasing }}
                                            onSubmit={handleVerifySubmit}
                                            className="flex flex-col gap-6 w-full items-center"
                                        >
                                            <OTPInput otp={otp} setOtp={setOtp} />
                                            <AuthButton
                                                isLoading={isLoading}
                                                disabled={otp.join('').length !== 6}
                                                fullWidth
                                            >
                                                Continue
                                            </AuthButton>
                                        </motion.form>
                                    )}
                                </AnimatePresence>
                            </div>

                            {/* Footer */}
                            <AnimatePresence mode="wait">
                                {isEmailStep ? (
                                    <motion.button
                                        key="back-btn"
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        exit={{ opacity: 0 }}
                                        transition={{ duration: 0.2, ease: smoothEasing }}
                                        type="button"
                                        onClick={handleClose}
                                        className="
                                            flex items-center justify-center gap-1.5
                                            text-sm font-semibold text-white
                                            cursor-pointer hover:opacity-80
                                            transition-opacity duration-200
                                        "
                                    >
                                        <ArrowLeftIcon />
                                        <span>Back to Sign In</span>
                                    </motion.button>
                                ) : (
                                    <motion.div
                                        key="resend-code"
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        exit={{ opacity: 0 }}
                                        transition={{ duration: 0.2, ease: smoothEasing }}
                                        className="flex items-center justify-center gap-1"
                                    >
                                        <span className="text-sm font-normal text-[rgba(255,255,255,0.5)]">
                                            Didn't you receive any code?
                                        </span>
                                        <button
                                            type="button"
                                            onClick={handleResendCode}
                                            className="text-sm font-semibold text-white cursor-pointer hover:underline"
                                        >
                                            Resend Code
                                        </button>
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </motion.div>
                    </motion.div>
                </>
            )}
        </AnimatePresence>
    );
}
