import React, { useState } from 'react';
import GuestLayout from '../../Layouts/GuestLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import { Card, Form, Spinner } from 'react-bootstrap';
import { ShieldCheck, Lock, KeyRound, ArrowLeft, Laptop } from 'lucide-react';
import styles from './Login.module.css';
import loginBg1 from '../../../images/login/login-bg-1.png';

interface Props {
    email?: string;
}

export default function TwoFactorChallenge({ email }: Props) {
    const [useRecoveryCode, setUseRecoveryCode] = useState<boolean>(false);

    const { data, setData, post, processing, errors } = useForm({
        code: '',
        trust_device: true,
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('two-factor.verify'));
    };

    return (
        <GuestLayout>
            <Head title="Verificación en Dos Pasos (2FA) — N)EON" />
            <div className={`auth-page-content ${styles.paginaLogin}`}>
                <div
                    className={`${styles.fondoCapa} ${styles.fondoVisible}`}
                    style={{ backgroundImage: `url(${loginBg1})` }}
                    aria-hidden="true"
                />
                <div className={styles.overlay} aria-hidden="true" />

                <div className={styles.contenedorFormulario}>
                    <Card
                        className={`card-border-effect-none ${styles.tarjetaLogin}`}
                        style={{
                            borderRadius: '22px',
                            background:
                                'linear-gradient(180deg, rgba(241, 245, 249, 0.96) 0%, rgba(255, 255, 255, 0.99) 100%)',
                            backdropFilter: 'blur(24px) saturate(180%)',
                            border: '1px solid rgba(148, 163, 184, 0.45)',
                            boxShadow:
                                '0 24px 48px -12px rgba(15, 23, 42, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.9)',
                        }}
                    >
                        <Card.Body className="p-4">
                            <div className="text-center mb-3">
                                <div
                                    className="mx-auto mb-3 d-inline-flex align-items-center justify-content-center"
                                    style={{
                                        width: '56px',
                                        height: '56px',
                                        borderRadius: '16px',
                                        background: 'linear-gradient(145deg, #dcfce7 0%, #bbf7d0 100%)',
                                        border: '1px solid #86efac',
                                        color: '#15803d',
                                        boxShadow: '0 8px 18px rgba(22, 163, 74, 0.18)',
                                    }}
                                >
                                    <ShieldCheck size={28} />
                                </div>
                                <h1
                                    style={{
                                        fontSize: '1.3rem',
                                        fontWeight: 700,
                                        color: '#0f172a',
                                        letterSpacing: '-0.02em',
                                        marginBottom: '0.25rem',
                                    }}
                                >
                                    Verificación de Seguridad (2FA)
                                </h1>
                                <p style={{ fontSize: '0.84rem', color: '#475569', marginBottom: 0 }}>
                                    {useRecoveryCode
                                        ? 'Ingresa uno de tus códigos de recuperación de respaldo de un solo uso.'
                                        : 'Ingresa el código de 6 dígitos generado por tu aplicación autenticadora.'}
                                </p>
                                {email && (
                                    <div
                                        className="mt-2 d-inline-flex align-items-center gap-1 px-3 py-1 rounded-pill"
                                        style={{
                                            background: '#eff6ff',
                                            border: '1px solid #bfdbfe',
                                            color: '#1d4ed8',
                                            fontSize: '0.75rem',
                                            fontWeight: 600,
                                        }}
                                    >
                                        <Lock size={12} />
                                        <span>{email}</span>
                                    </div>
                                )}
                            </div>

                            <Form onSubmit={handleSubmit} className="mt-3">
                                <Form.Group className="mb-3">
                                    <Form.Label
                                        htmlFor="two-factor-code"
                                        style={{
                                            fontSize: '0.78rem',
                                            fontWeight: 600,
                                            color: '#334155',
                                        }}
                                    >
                                        {useRecoveryCode
                                            ? 'Código de recuperación (XXXX-XXXX)'
                                            : 'Código de autenticación (6 dígitos)'}
                                    </Form.Label>
                                    <Form.Control
                                        id="two-factor-code"
                                        type="text"
                                        inputMode={useRecoveryCode ? 'text' : 'numeric'}
                                        maxLength={useRecoveryCode ? 12 : 6}
                                        autoFocus
                                        required
                                        value={data.code}
                                        onChange={(e) =>
                                            setData(
                                                'code',
                                                useRecoveryCode
                                                    ? e.target.value.toUpperCase()
                                                    : e.target.value.replace(/\D/g, '')
                                            )
                                        }
                                        placeholder={useRecoveryCode ? 'XXXX-XXXX' : '000000'}
                                        isInvalid={Boolean(errors.code)}
                                        style={{
                                            fontFamily:
                                                'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
                                            fontSize: '1.35rem',
                                            fontWeight: 700,
                                            letterSpacing: useRecoveryCode ? '0.15em' : '0.35em',
                                            textAlign: 'center',
                                            borderRadius: '12px',
                                            padding: '0.65rem 1rem',
                                        }}
                                    />
                                    {errors.code && (
                                        <Form.Control.Feedback type="invalid" className="d-block mt-2">
                                            {errors.code}
                                        </Form.Control.Feedback>
                                    )}
                                </Form.Group>

                                {/* Checkbox: Recordar y confiar en este equipo por 30 días */}
                                <div
                                    className="p-3 rounded-3 mb-3"
                                    style={{
                                        background:
                                            'linear-gradient(135deg, rgba(224, 242, 254, 0.75) 0%, rgba(236, 254, 255, 0.65) 100%)',
                                        border: '1px solid #bae6fd',
                                    }}
                                >
                                    <Form.Check
                                        type="checkbox"
                                        id="trust-device-checkbox"
                                        checked={data.trust_device}
                                        onChange={(e) => setData('trust_device', e.target.checked)}
                                        label={
                                            <span
                                                className="d-inline-flex align-items-center gap-2"
                                                style={{
                                                    fontSize: '0.82rem',
                                                    fontWeight: 600,
                                                    color: '#0f172a',
                                                }}
                                            >
                                                <Laptop size={15} style={{ color: '#0284c7' }} />
                                                <span>Recordar y confiar en este equipo por 30 días</span>
                                            </span>
                                        }
                                    />
                                </div>

                                <button
                                    id="btn-two-factor-submit"
                                    type="submit"
                                    className="btn btn-primary w-100 py-2 fw-semibold"
                                    style={{ borderRadius: '12px' }}
                                    disabled={processing}
                                >
                                    {processing ? (
                                        <Spinner animation="border" size="sm" />
                                    ) : (
                                        'Verificar y Continuar'
                                    )}
                                </button>

                                <div className="d-flex justify-content-between align-items-center mt-3 pt-2 border-top">
                                    <button
                                        type="button"
                                        className="btn btn-link p-0 text-decoration-none"
                                        style={{ fontSize: '0.78rem', fontWeight: 600, color: '#2563eb' }}
                                        onClick={() => {
                                            setUseRecoveryCode(!useRecoveryCode);
                                            setData('code', '');
                                        }}
                                    >
                                        <KeyRound size={13} className="me-1" />
                                        {useRecoveryCode
                                            ? 'Usar código de 6 dígitos'
                                            : 'Usar código de recuperación'}
                                    </button>

                                    <Link
                                        href={route('login')}
                                        className="text-decoration-none d-inline-flex align-items-center gap-1"
                                        style={{ fontSize: '0.78rem', fontWeight: 600, color: '#64748b' }}
                                    >
                                        <ArrowLeft size={13} />
                                        <span>Volver al Login</span>
                                    </Link>
                                </div>
                            </Form>
                        </Card.Body>
                    </Card>
                </div>
            </div>
        </GuestLayout>
    );
}
