import React, { useState } from 'react';
import { router } from '@inertiajs/react';
import { Col, Form, Row, Spinner } from 'react-bootstrap';
import {
    Shield,
    ShieldCheck,
    ShieldAlert,
    QrCode,
    KeyRound,
    Copy,
    Check,
    Download,
    Monitor,
    Smartphone,
    Trash2,
    Lock,
    Sparkles,
    X,
} from 'lucide-react';
import Swal from 'sweetalert2';

export interface TrustedDeviceItem {
    id: number;
    browser: string;
    platform: string;
    is_mobile: boolean;
    ip_address: string;
    last_used_at: string;
    expires_at: string;
    is_current: boolean;
}

interface SetupData {
    secret: string;
    otpauth_url: string;
    qr_svg: string | null;
    recovery_codes: string[];
}

interface Props {
    userId: number;
    userEmail: string;
    initialEnabled: boolean;
    initialTrustedDevices: TrustedDeviceItem[];
    isSelfProfile: boolean;
    onStatusChange?: (enabled: boolean) => void;
}

export const TwoFactorSecurityCard: React.FC<Props> = ({
    userId,
    userEmail,
    initialEnabled,
    initialTrustedDevices,
    isSelfProfile,
    onStatusChange,
}) => {
    const [enabled, setEnabled] = useState<boolean>(initialEnabled);
    const [trustedDevices, setTrustedDevices] = useState<TrustedDeviceItem[]>(initialTrustedDevices);
    const [setupData, setSetupData] = useState<SetupData | null>(null);
    const [verificationCode, setVerificationCode] = useState<string>('');
    const [disableCredential, setDisableCredential] = useState<string>('');
    const [disableMode, setDisableMode] = useState<'password' | 'totp'>('password');
    const [showDisablePanel, setShowDisablePanel] = useState<boolean>(false);
    const [loadingAction, setLoadingAction] = useState<boolean>(false);
    const [copiedSecret, setCopiedSecret] = useState<boolean>(false);
    const [copiedRecovery, setCopiedRecovery] = useState<boolean>(false);

    const refreshSharedState = (nextEnabled: boolean) => {
        setEnabled(nextEnabled);
        onStatusChange?.(nextEnabled);
        router.reload({ only: ['auth', 'usuario', 'trustedDevices'] });
    };

    const handleInitiateSetup = async () => {
        setLoadingAction(true);
        try {
            const response = await window.axios.post(route('users.two-factor.setup', userId));
            if (response.data?.success) {
                setSetupData({
                    secret: response.data.secret,
                    otpauth_url: response.data.otpauth_url,
                    qr_svg: response.data.qr_svg ?? null,
                    recovery_codes: response.data.recovery_codes ?? [],
                });
                setVerificationCode('');
            }
        } catch (error: any) {
            Swal.fire({
                title: 'Error',
                text: error?.response?.data?.message ?? 'No se pudo iniciar la configuración 2FA.',
                icon: 'error',
            });
        } finally {
            setLoadingAction(false);
        }
    };

    const handleConfirmSetup = async () => {
        const cleanCode = verificationCode.replace(/\D/g, '');
        if (cleanCode.length !== 6) {
            Swal.fire({
                title: 'Código incompleto',
                text: 'Ingresa el código de 6 dígitos generado por Google Authenticator.',
                icon: 'warning',
            });
            return;
        }

        setLoadingAction(true);
        try {
            const response = await window.axios.post(route('users.two-factor.confirm', userId), {
                code: cleanCode,
            });

            if (response.data?.success) {
                setSetupData(null);
                setVerificationCode('');
                refreshSharedState(true);
                Swal.fire({
                    title: '2FA Activado',
                    text: response.data.message,
                    icon: 'success',
                    timer: 1800,
                    showConfirmButton: false,
                });
            }
        } catch (error: any) {
            Swal.fire({
                title: 'Código inválido',
                text:
                    error?.response?.data?.message ??
                    'El código de 6 dígitos no coincide. Verifica tu aplicación autenticadora.',
                icon: 'error',
            });
        } finally {
            setLoadingAction(false);
        }
    };

    const handleDisableTwoFactor = async () => {
        if (isSelfProfile && !disableCredential.trim()) {
            Swal.fire({
                title: 'Verificación requerida',
                text:
                    disableMode === 'password'
                        ? 'Ingresa tu contraseña actual para desactivar el 2FA.'
                        : 'Ingresa un código TOTP vigente de 6 dígitos para desactivar el 2FA.',
                icon: 'warning',
            });
            return;
        }

        setLoadingAction(true);
        try {
            const payload =
                disableMode === 'password'
                    ? { current_password: disableCredential }
                    : { code: disableCredential.replace(/\D/g, '') };

            const response = await window.axios.delete(route('users.two-factor.disable', userId), {
                data: payload,
            });

            if (response.data?.success) {
                setShowDisablePanel(false);
                setDisableCredential('');
                setTrustedDevices([]);
                refreshSharedState(false);
                Swal.fire({
                    title: '2FA Desactivado',
                    text: response.data.message,
                    icon: 'success',
                    timer: 1800,
                    showConfirmButton: false,
                });
            }
        } catch (error: any) {
            Swal.fire({
                title: 'No se pudo desactivar',
                text:
                    error?.response?.data?.message ??
                    'Credencial inválida para desactivar el Doble Factor.',
                icon: 'error',
            });
        } finally {
            setLoadingAction(false);
        }
    };

    const handleRevokeAllDevices = async () => {
        const confirm = await Swal.fire({
            title: '¿Revocar todos los dispositivos?',
            text: 'Se solicitará el código de 6 dígitos la próxima vez que inicies sesión en cualquier equipo.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, revocar todos',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#dc2626',
        });

        if (!confirm.isConfirmed) return;

        setLoadingAction(true);
        try {
            const response = await window.axios.delete(
                route('users.trusted-devices.revoke', userId)
            );
            if (response.data?.success) {
                setTrustedDevices([]);
                Swal.fire({
                    title: 'Dispositivos revocados',
                    text: response.data.message,
                    icon: 'success',
                    timer: 1600,
                    showConfirmButton: false,
                });
            }
        } catch (error: any) {
            Swal.fire({
                title: 'Error',
                text: 'No se pudieron revocar los dispositivos de confianza.',
                icon: 'error',
            });
        } finally {
            setLoadingAction(false);
        }
    };

    const copySecret = () => {
        if (!setupData?.secret) return;
        navigator.clipboard.writeText(setupData.secret);
        setCopiedSecret(true);
        setTimeout(() => setCopiedSecret(false), 2000);
    };

    const copyRecoveryCodes = () => {
        if (!setupData?.recovery_codes?.length) return;
        navigator.clipboard.writeText(setupData.recovery_codes.join('\n'));
        setCopiedRecovery(true);
        setTimeout(() => setCopiedRecovery(false), 2000);
    };

    const downloadRecoveryCodes = () => {
        if (!setupData?.recovery_codes?.length) return;
        const content = [
            'ENEON CRM — CÓDIGOS DE RECUPERACIÓN 2FA (UN SOLO USO)',
            `Cuenta: ${userEmail}`,
            `Fecha: ${new Date().toLocaleString('es-ES')}`,
            '-----------------------------------------------------',
            ...setupData.recovery_codes,
        ].join('\n');

        const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `eneon-2fa-backup-codes-${userId}.txt`;
        link.click();
        URL.revokeObjectURL(url);
    };

    return (
        <div
            id="two-factor-security"
            className={`apple-2fa-card ${enabled ? '' : 'is-inactive'}`}
        >
            {/* Cabecera estilo Apple / Dashboard */}
            <div className="saas-card-header flex-wrap gap-2">
                <div className="d-flex align-items-center gap-2">
                    <div className={`saas-icon-badge ${enabled ? 'emerald' : 'primary'}`}>
                        <Shield size={15} />
                    </div>
                    <div>
                        <h3 className="saas-title m-0" style={{ fontSize: '0.96rem' }}>
                            Autenticación de Doble Factor (2FA — Google Authenticator)
                        </h3>
                        <span style={{ fontSize: '0.75rem', color: '#64748b' }}>
                            Protege tu cuenta con códigos temporales TOTP y reconocimiento de dispositivos de confianza por 30 días.
                        </span>
                    </div>
                </div>

                {enabled ? (
                    <span className="saas-badge-status active" style={{ fontSize: '0.75rem', padding: '0.25rem 0.75rem' }}>
                        <ShieldCheck size={13} />
                        <span>2FA • Verificado</span>
                    </span>
                ) : (
                    <span className="saas-badge-status suspended" style={{ fontSize: '0.75rem', padding: '0.25rem 0.75rem' }}>
                        <ShieldAlert size={13} />
                        <span>2FA • Sin activar</span>
                    </span>
                )}
            </div>

            <div className="saas-card-body">
                {/* Banner Principal Llamativo */}
                <div className={`apple-2fa-banner ${enabled ? '' : 'inactive'}`}>
                    <div className="d-flex align-items-center gap-3">
                        <div className={`apple-2fa-icon-orb ${enabled ? '' : 'inactive'}`}>
                            {enabled ? <ShieldCheck size={24} /> : <QrCode size={24} />}
                        </div>
                        <div>
                            <div className="d-flex flex-wrap align-items-center gap-2">
                                <h4
                                    style={{
                                        fontSize: '0.98rem',
                                        fontWeight: 700,
                                        color: '#0f172a',
                                        margin: 0,
                                    }}
                                >
                                    {enabled
                                        ? 'Doble Factor de Autenticación Activo'
                                        : 'Refuerza la seguridad de tu cuenta con 2FA'}
                                </h4>
                                <span
                                    className={`apple-legend-pill ${
                                        enabled ? 'additional' : 'inherited'
                                    }`}
                                >
                                    {enabled ? 'TOTP Sincronizado' : 'Opcional • Recomendado'}
                                </span>
                            </div>
                            <p
                                style={{
                                    fontSize: '0.8rem',
                                    color: '#475569',
                                    margin: '0.22rem 0 0',
                                    maxWidth: '640px',
                                }}
                            >
                                {enabled
                                    ? 'Solo te pediremos el código de 6 dígitos la primera vez que inicies sesión desde un navegador o equipo nuevo.'
                                    : 'Vincula Google Authenticator o Apple Passwords escaneando un código QR. Podrás recordar tus equipos habituales por 30 días.'}
                            </p>
                        </div>
                    </div>

                    <div className="d-flex align-items-center gap-2 flex-shrink-0">
                        {!enabled && !setupData && isSelfProfile && (
                            <button
                                id="btn-2fa-start-setup"
                                type="button"
                                className="saas-btn-primary"
                                onClick={handleInitiateSetup}
                                disabled={loadingAction}
                            >
                                {loadingAction ? (
                                    <Spinner animation="border" size="sm" />
                                ) : (
                                    <>
                                        <Sparkles size={14} />
                                        <span>Activar Doble Factor (2FA)</span>
                                    </>
                                )}
                            </button>
                        )}

                        {enabled && !showDisablePanel && (
                            <button
                                id="btn-2fa-open-disable"
                                type="button"
                                className="saas-btn-outline"
                                style={{ color: '#dc2626', borderColor: '#fecaca', background: '#fff1f2' }}
                                onClick={() => setShowDisablePanel(true)}
                            >
                                <Lock size={13} />
                                <span>Desactivar 2FA</span>
                            </button>
                        )}
                    </div>
                </div>

                {/* Asistente Guiado de Activación 2FA (Estado Pendiente) */}
                {!enabled && setupData && (
                    <div
                        className="mt-3 p-3 rounded-4 border"
                        style={{ background: '#ffffff', borderColor: '#cbd5e1' }}
                    >
                        <div className="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                            <div className="d-flex align-items-center gap-2">
                                <QrCode size={17} className="text-primary" />
                                <span style={{ fontSize: '0.9rem', fontWeight: 700, color: '#0f172a' }}>
                                    Configuración Guiada de Google Authenticator (Pendiente de confirmar)
                                </span>
                            </div>
                            <button
                                type="button"
                                className="saas-btn-ghost"
                                onClick={() => setSetupData(null)}
                                title="Cancelar configuración"
                            >
                                <X size={16} />
                            </button>
                        </div>

                        <Row className="g-4 align-items-start">
                            {/* Paso 1: Escaneo QR + Clave Manual */}
                            <Col lg={5} className="text-center">
                                <div className="apple-qr-frame mb-3">
                                    {setupData.qr_svg ? (
                                        <div
                                            dangerouslySetInnerHTML={{ __html: setupData.qr_svg }}
                                            aria-label="Código QR de configuración 2FA"
                                        />
                                    ) : (
                                        <div className="text-center p-2">
                                            <QrCode size={72} className="text-primary mb-2" />
                                            <div style={{ fontSize: '0.74rem', color: '#475569' }}>
                                                Usa la clave manual inferior en tu app autenticadora
                                            </div>
                                        </div>
                                    )}
                                </div>

                                <div className="text-start">
                                    <span className="apple-field-label">
                                        <KeyRound size={13} className="text-primary" />
                                        <span>Clave secreta manual (Base32)</span>
                                    </span>
                                    <div className="apple-secret-pill">
                                        <span className="text-truncate">{setupData.secret}</span>
                                        <button
                                            type="button"
                                            className="saas-btn-outline py-1 px-2"
                                            onClick={copySecret}
                                        >
                                            {copiedSecret ? <Check size={13} /> : <Copy size={13} />}
                                            <span>{copiedSecret ? 'Copiada' : 'Copiar'}</span>
                                        </button>
                                    </div>
                                </div>
                            </Col>

                            {/* Paso 2: Códigos de Respaldo y Confirmación de 6 dígitos */}
                            <Col lg={7}>
                                <div className="mb-3">
                                    <div className="d-flex justify-content-between align-items-center mb-2">
                                        <span className="apple-field-label mb-0">
                                            <Shield size={13} className="text-primary" />
                                            <span>Códigos de Recuperación (Guárdalos en un lugar seguro)</span>
                                        </span>
                                        <div className="d-flex gap-2">
                                            <button
                                                type="button"
                                                className="saas-btn-outline py-1 px-2"
                                                onClick={copyRecoveryCodes}
                                            >
                                                {copiedRecovery ? <Check size={12} /> : <Copy size={12} />}
                                                <span>{copiedRecovery ? 'Copiados' : 'Copiar'}</span>
                                            </button>
                                            <button
                                                type="button"
                                                className="saas-btn-outline py-1 px-2"
                                                onClick={downloadRecoveryCodes}
                                            >
                                                <Download size={12} />
                                                <span>Descargar .txt</span>
                                            </button>
                                        </div>
                                    </div>

                                    <div className="apple-recovery-grid">
                                        {setupData.recovery_codes.map((code) => (
                                            <div key={code} className="apple-recovery-code">
                                                {code}
                                            </div>
                                        ))}
                                    </div>
                                </div>

                                {/* Paso 3: Confirmar código de 6 dígitos */}
                                <div
                                    className="p-3 rounded-3"
                                    style={{ background: '#f8fafc', border: '1px solid #cbd5e1' }}
                                >
                                    <label
                                        htmlFor="two-factor-confirm-code"
                                        className="apple-field-label"
                                    >
                                        <ShieldCheck size={14} style={{ color: '#059669' }} />
                                        <span>
                                            Ingresa el código de 6 dígitos de Google Authenticator para confirmar
                                        </span>
                                    </label>
                                    <div className="d-flex flex-column flex-sm-row gap-2 align-items-stretch">
                                        <Form.Control
                                            id="two-factor-confirm-code"
                                            type="text"
                                            inputMode="numeric"
                                            maxLength={6}
                                            className="apple-form-control apple-totp-input"
                                            placeholder="000000"
                                            value={verificationCode}
                                            onChange={(e) =>
                                                setVerificationCode(e.target.value.replace(/\D/g, ''))
                                            }
                                            onKeyDown={(e) => {
                                                if (e.key === 'Enter') {
                                                    e.preventDefault();
                                                    handleConfirmSetup();
                                                }
                                            }}
                                        />
                                        <button
                                            id="btn-2fa-confirm-activation"
                                            type="button"
                                            className="saas-btn-primary justify-content-center px-4"
                                            onClick={handleConfirmSetup}
                                            disabled={loadingAction}
                                            style={{ whiteSpace: 'nowrap' }}
                                        >
                                            {loadingAction ? (
                                                <Spinner animation="border" size="sm" />
                                            ) : (
                                                <>
                                                    <ShieldCheck size={15} />
                                                    <span>Confirmar y Activar</span>
                                                </>
                                            )}
                                        </button>
                                    </div>
                                </div>
                            </Col>
                        </Row>
                    </div>
                )}

                {/* Panel de Desactivación Protegida */}
                {enabled && showDisablePanel && (
                    <div
                        className="mt-3 p-3 rounded-3"
                        style={{ background: '#fff1f2', border: '1px solid #fecdd3' }}
                    >
                        <div className="d-flex justify-content-between align-items-center mb-2">
                            <span style={{ fontSize: '0.86rem', fontWeight: 700, color: '#9f1239' }}>
                                Confirmar desactivación del Doble Factor (2FA)
                            </span>
                            <button
                                type="button"
                                className="saas-btn-ghost"
                                onClick={() => setShowDisablePanel(false)}
                            >
                                <X size={15} />
                            </button>
                        </div>
                        <p style={{ fontSize: '0.78rem', color: '#be123c', marginBottom: '0.75rem' }}>
                            Al desactivar el 2FA se eliminará el secreto TOTP y se revocará la confianza de todos los equipos registrados.
                        </p>

                        {isSelfProfile && (
                            <div className="d-flex gap-2 mb-2">
                                <button
                                    type="button"
                                    className={`saas-btn-outline ${
                                        disableMode === 'password' ? 'border-primary text-primary' : ''
                                    }`}
                                    onClick={() => {
                                        setDisableMode('password');
                                        setDisableCredential('');
                                    }}
                                >
                                    <span>Usar contraseña actual</span>
                                </button>
                                <button
                                    type="button"
                                    className={`saas-btn-outline ${
                                        disableMode === 'totp' ? 'border-primary text-primary' : ''
                                    }`}
                                    onClick={() => {
                                        setDisableMode('totp');
                                        setDisableCredential('');
                                    }}
                                >
                                    <span>Usar código TOTP de 6 dígitos</span>
                                </button>
                            </div>
                        )}

                        <div className="d-flex flex-column flex-sm-row gap-2">
                            {isSelfProfile && (
                                <Form.Control
                                    id="two-factor-disable-input"
                                    type={disableMode === 'password' ? 'password' : 'text'}
                                    maxLength={disableMode === 'totp' ? 6 : 120}
                                    className="apple-form-control"
                                    placeholder={
                                        disableMode === 'password'
                                            ? 'Ingresa tu contraseña actual...'
                                            : 'Código TOTP de 6 dígitos...'
                                    }
                                    value={disableCredential}
                                    onChange={(e) => setDisableCredential(e.target.value)}
                                />
                            )}
                            <button
                                id="btn-2fa-confirm-disable"
                                type="button"
                                className="saas-btn-primary"
                                style={{ backgroundColor: '#dc2626', borderColor: '#dc2626', whiteSpace: 'nowrap' }}
                                onClick={handleDisableTwoFactor}
                                disabled={loadingAction}
                            >
                                {loadingAction ? (
                                    <Spinner animation="border" size="sm" />
                                ) : (
                                    <span>Confirmar Desactivación</span>
                                )}
                            </button>
                        </div>
                    </div>
                )}

                {/* Listado de Dispositivos de Confianza Autorizados */}
                {enabled && (
                    <div className="mt-3 pt-3 border-top">
                        <div className="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
                            <div className="d-flex align-items-center gap-2">
                                <Monitor size={15} className="text-primary" />
                                <span style={{ fontSize: '0.88rem', fontWeight: 700, color: '#0f172a' }}>
                                    Dispositivos de Confianza Autorizados (30 días)
                                </span>
                                <span className="apple-legend-pill inherited">
                                    {trustedDevices.length}
                                </span>
                            </div>

                            {trustedDevices.length > 0 && (
                                <button
                                    id="btn-revoke-all-trusted-devices"
                                    type="button"
                                    className="saas-btn-outline"
                                    style={{ color: '#dc2626', borderColor: '#fecaca' }}
                                    onClick={handleRevokeAllDevices}
                                    disabled={loadingAction}
                                >
                                    <Trash2 size={13} />
                                    <span>Revocar confianza de todos los dispositivos</span>
                                </button>
                            )}
                        </div>

                        {trustedDevices.length === 0 ? (
                            <div
                                className="p-3 rounded-3 text-center"
                                style={{ background: '#f8fafc', border: '1px dashed #cbd5e1', fontSize: '0.78rem', color: '#64748b' }}
                            >
                                No hay dispositivos de confianza registrados actualmente. Al iniciar sesión podrás marcar <em>"Recordar y confiar en este equipo por 30 días"</em>.
                            </div>
                        ) : (
                            <div>
                                {trustedDevices.map((device) => (
                                    <div key={device.id} className="apple-device-row">
                                        <div className="d-flex align-items-center gap-3">
                                            <div className="saas-icon-badge primary">
                                                {device.is_mobile ? (
                                                    <Smartphone size={15} />
                                                ) : (
                                                    <Monitor size={15} />
                                                )}
                                            </div>
                                            <div>
                                                <div className="d-flex align-items-center gap-2">
                                                    <span
                                                        style={{
                                                            fontSize: '0.84rem',
                                                            fontWeight: 700,
                                                            color: '#0f172a',
                                                        }}
                                                    >
                                                        {device.platform} • {device.browser}
                                                    </span>
                                                    {device.is_current && (
                                                        <span className="saas-badge-status active">
                                                            <span>Este equipo</span>
                                                        </span>
                                                    )}
                                                </div>
                                                <div
                                                    style={{
                                                        fontSize: '0.74rem',
                                                        color: '#64748b',
                                                        marginTop: '2px',
                                                    }}
                                                >
                                                    IP: {device.ip_address} • Último uso: {device.last_used_at} • Expira: {device.expires_at}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};
