/**
 * AuthFormCard Component
 * @description Unified authentication form with animated transitions between Sign In and Register.
 * Uses framer-motion for smooth expand/collapse animations.
 * Follows AgenticIQ Enterprise Coding Guidelines v1.0
 */

import { useState, type FormEvent } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
    AuthCard,
    AuthCardHeader,
    AuthCardContent,
    AuthInput,
    AuthButton,
    SocialButton,
    TextButton,
    GoogleIcon,
    AzureIcon,
} from './index';

/**
 * Auth form mode type
 */
type AuthMode = 'signin' | 'register';

/**
 * Props for AuthFormCard component
 */
interface AuthFormCardProps {
    /** Initial mode (signin or register) */
    initialMode?: AuthMode;
    /** Callback when sign in is submitted */
    onSignIn?: (email: string, password: string) => void;
    /** Callback when register is submitted */
    onRegister?: (data: RegisterData) => void;
    /** Callback for Google sign in */
    onGoogleAuth?: () => void;
    /** Callback for Azure sign in */
    onAzureAuth?: () => void;
    /** Callback for forgot password */
    onForgotPassword?: () => void;
}

/**
 * Register form data interface
 */
interface RegisterData {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
}

/**
 * Spring transition for smooth physics-based animations
 * Using 'as const' to ensure literal types for framer-motion
 */
const springTransition = {
    type: 'spring' as const,
    stiffness: 500,
    damping: 30,
    mass: 1,
};

/**
 * Animation variants for the collapsible name fields row
 */
const nameFieldsVariants = {
    hidden: {
        height: 0,
        opacity: 0,
        marginBottom: 0,
        transition: {
            height: { ...springTransition, duration: 0.2 },
            opacity: { duration: 0.1 },
            marginBottom: { ...springTransition, duration: 0.2 },
        },
    },
    visible: {
        height: 'auto',
        opacity: 1,
        marginBottom: 16,
        transition: {
            height: { ...springTransition, duration: 0.2 },
            opacity: { duration: 0.15, delay: 0.05 },
            marginBottom: { ...springTransition, duration: 0.2 },
        },
    },
};

/**
 * Animation variants for forgot password link
 */
const forgotPasswordVariants = {
    hidden: {
        height: 0,
        opacity: 0,
        marginTop: 0,
        transition: {
            height: { ...springTransition, duration: 0.15 },
            opacity: { duration: 0.1 },
            marginTop: { ...springTransition, duration: 0.15 },
        },
    },
    visible: {
        height: 'auto',
        opacity: 1,
        marginTop: 8,
        transition: {
            height: { ...springTransition, duration: 0.15 },
            opacity: { duration: 0.15, delay: 0.05 },
            marginTop: { ...springTransition, duration: 0.15 },
        },
    },
};

/**
 * AuthFormCard component
 * @description Unified authentication card with animated transitions between Sign In and Register modes.
 * @param {AuthFormCardProps} props - Component props
 * @returns {JSX.Element} AuthFormCard element
 */
export function AuthFormCard({
    initialMode = 'signin',
    onSignIn,
    onRegister,
    onGoogleAuth,
    onAzureAuth,
    onForgotPassword,
}: AuthFormCardProps): JSX.Element {
    const [mode, setMode] = useState<AuthMode>(initialMode);
    const isRegister = mode === 'register';

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    /**
     * Handle form submission based on current mode
     * @param {FormEvent<HTMLFormElement>} e - Form event
     */
    const handleSubmit = (e: FormEvent<HTMLFormElement>): void => {
        e.preventDefault();
        setIsLoading(true);

        if (isRegister) {
            onRegister?.({ firstName, lastName, email, password });
        } else {
            onSignIn?.(email, password);
        }

        setTimeout(() => setIsLoading(false), 1000);
    };

    /**
     * Toggle between Sign In and Register modes
     */
    const toggleMode = (): void => {
        setMode((prev) => (prev === 'signin' ? 'register' : 'signin'));
        setFirstName('');
        setLastName('');
        setEmail('');
        setPassword('');
    };

    return (
        <motion.div
            layout
            transition={{ layout: { ...springTransition, duration: 0.3 } }}
            className="w-[520px] max-w-full"
            style={{ willChange: 'transform' }}
        >
            <AuthCard variant={isRegister ? 'register' : 'signin'}>
                {/* Header Section */}
                <AuthCardHeader
                    title={isRegister ? 'Create Your Account' : 'Sign In to Your Account'}
                    subtitle={
                        isRegister
                            ? 'Welcome! Please enter your information.'
                            : 'Welcome back. Please enter your credentials.'
                    }
                />

                {/* Form Content */}
                <AuthCardContent>
                    <form onSubmit={handleSubmit} className="flex flex-col gap-4 w-full">
                        {/* Collapsible Name Fields Row */}
                        <AnimatePresence initial={false}>
                            {isRegister && (
                                <motion.div
                                    key="name-fields"
                                    variants={nameFieldsVariants}
                                    initial="hidden"
                                    animate="visible"
                                    exit="hidden"
                                    className="overflow-hidden"
                                    style={{ willChange: 'height, opacity' }}
                                >
                                    <div className="flex gap-3 w-full">
                                        <div className="flex-1 min-w-0">
                                            <AuthInput
                                                label="First Name"
                                                type="text"
                                                placeholder="First name"
                                                value={firstName}
                                                onChange={(e) => setFirstName(e.target.value)}
                                                isRequired
                                                autoComplete="given-name"
                                            />
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <AuthInput
                                                label="Last Name"
                                                type="text"
                                                placeholder="Last name"
                                                value={lastName}
                                                onChange={(e) => setLastName(e.target.value)}
                                                autoComplete="family-name"
                                            />
                                        </div>
                                    </div>
                                </motion.div>
                            )}
                        </AnimatePresence>

                        {/* Email Input */}
                        <motion.div layout transition={springTransition}>
                            <AuthInput
                                label="Email"
                                type="email"
                                placeholder="Enter your email address"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                isRequired
                                autoComplete={isRegister ? 'email' : 'username'}
                            />
                        </motion.div>

                        {/* Password Input */}
                        <motion.div layout transition={springTransition}>
                            <AuthInput
                                label="Password"
                                type="password"
                                placeholder={isRegister ? 'Create a password' : 'Enter your password'}
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                isRequired
                                autoComplete={isRegister ? 'new-password' : 'current-password'}
                            />
                        </motion.div>

                        {/* Forgot Password Link - Collapses in Register mode */}
                        <AnimatePresence initial={false}>
                            {!isRegister && (
                                <motion.div
                                    key="forgot-password"
                                    variants={forgotPasswordVariants}
                                    initial="hidden"
                                    animate="visible"
                                    exit="hidden"
                                    className="overflow-hidden flex justify-end w-full"
                                    style={{ willChange: 'height, opacity' }}
                                >
                                    <TextButton onClick={onForgotPassword}>
                                        Forgot your password?
                                    </TextButton>
                                </motion.div>
                            )}
                        </AnimatePresence>

                        {/* Submit Button */}
                        <AuthButton isLoading={isLoading}>
                            {isRegister ? 'Create Account' : 'Sign In'}
                        </AuthButton>
                    </form>

                    {/* Social Login Buttons */}
                    <div className="flex gap-3 w-full">
                        <SocialButton
                            icon={<GoogleIcon />}
                            onClick={onGoogleAuth}
                            className="flex-1"
                        >
                            {isRegister ? 'Sign Up with Google' : 'Sign In with Google'}
                        </SocialButton>
                        <SocialButton
                            icon={<AzureIcon />}
                            onClick={onAzureAuth}
                            className="flex-1"
                        >
                            {isRegister ? 'Sign Up with Azure' : 'Sign In with Azure'}
                        </SocialButton>
                    </div>
                </AuthCardContent>

                {/* Footer Section */}
                <div className="flex items-baseline justify-center gap-1 w-full">
                    <span className="text-sm font-normal leading-5 text-[rgba(255,255,255,0.5)]">
                        {isRegister ? 'Already have an account?' : "Don't have an account?"}
                    </span>
                    <TextButton onClick={toggleMode}>
                        {isRegister ? 'Sign In' : 'Register here'}
                    </TextButton>
                </div>
            </AuthCard>
        </motion.div>
    );
}
