import { useState, useCallback } from 'react';
import { Lock, ShieldCheck, ShieldOff, KeyRound, Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
import { useAuthStore } from '@/stores/auth';
import client from '@/api/client';
import { useI18n } from '@/i18n';

interface MfaSetupResponse {
  secret: string;
  uri: string;
}

export default function MfaPage() {
  const { user, checkAuth } = useAuthStore();
  const { t } = useI18n();

  const [secret, setSecret] = useState<string | null>(null);
  const [totpUri, setTotpUri] = useState<string | null>(null);
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState<{ text: string; type: 's' | 'e' | 'i' } | null>(null);

  const mfaEnabled = !!user?.mfa_enabled;

  const handleSetup = useCallback(async () => {
    setLoading(true);
    setMsg(null);
    try {
      const data = await client.post('/mfa/setup') as unknown as MfaSetupResponse;
      setSecret(data.secret);
      setTotpUri(data.uri);
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Erro ao gerar secret', type: 'e' });
    } finally {
      setLoading(false);
    }
  }, []);

  const handleVerify = useCallback(async () => {
    if (!code || code.length !== 6) {
      setMsg({ text: t('mfa.invalidCode'), type: 'e' });
      return;
    }
    setLoading(true);
    setMsg(null);
    try {
      await client.post('/mfa/verify', { totp_code: code });
      setMsg({ text: t('mfa.activated'), type: 's' });
      setSecret(null);
      setTotpUri(null);
      setCode('');
      await checkAuth();
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Codigo invalido', type: 'e' });
    } finally {
      setLoading(false);
    }
  }, [code, checkAuth, t]);

  const handleDisable = useCallback(async () => {
    if (!user) return;
    if (!window.confirm(t('mfa.confirmDisable'))) return;
    setLoading(true);
    setMsg(null);
    try {
      await client.post(`/mfa/disable/${user.id}`);
      setMsg({ text: t('mfa.deactivated'), type: 'i' });
      await checkAuth();
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Erro ao desativar MFA', type: 'e' });
    } finally {
      setLoading(false);
    }
  }, [user, checkAuth, t]);

  const alertStyles: Record<string, { bg: string; color: string; icon: typeof CheckCircle2 }> = {
    s: { bg: 'var(--gnl)', color: 'var(--gn)', icon: CheckCircle2 },
    e: { bg: 'var(--rdl)', color: 'var(--rd)', icon: AlertCircle },
    i: { bg: 'color-mix(in srgb, var(--bl) 12%, transparent)', color: 'var(--bl)', icon: AlertCircle },
  };

  return (
    <div className="page" style={{ maxWidth: 580 }}>
      {/* Header */}
      <div className="page-header">
        <div className="card-header icon" style={{ background: 'color-mix(in srgb, var(--ac) 10%, transparent)' }}>
          <Lock size={20} style={{ color: 'var(--ac)' }} />
        </div>
        <div>
          <h1>{t('mfa.title')}</h1>
          <div className="subtitle">
            {t('mfa.subtitle')}
          </div>
        </div>
      </div>

      {/* Card */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        {/* Status banner */}
        <div
          className="flex items-center gap-3 px-5 py-4"
          style={{
            borderBottom: '1px solid var(--bd)',
            background: mfaEnabled
              ? 'color-mix(in srgb, var(--gn) 6%, transparent)'
              : 'color-mix(in srgb, var(--yl) 6%, transparent)',
          }}
        >
          {mfaEnabled ? (
            <ShieldCheck size={22} style={{ color: 'var(--gn)' }} />
          ) : (
            <ShieldOff size={22} style={{ color: 'var(--yl)' }} />
          )}
          <div>
            <span className="text-sm font-semibold" style={{ color: 'var(--t1)' }}>
              {mfaEnabled ? t('mfa.enabled') : t('mfa.disabled')}
            </span>
            <p className="text-xs mt-0.5" style={{ color: 'var(--t3)' }}>
              {mfaEnabled
                ? t('mfa.enabledDesc')
                : t('mfa.disabledDesc')}
            </p>
          </div>
        </div>

        {/* Content */}
        <div className="p-5">
          {/* Message */}
          {msg && (() => {
            const st = alertStyles[msg.type];
            const Icon = st.icon;
            return (
              <div
                className="flex items-center gap-2 px-3.5 py-2.5 rounded-lg mb-4 text-xs font-medium"
                style={{ background: st.bg, color: st.color }}
              >
                <Icon size={15} />
                {msg.text}
              </div>
            );
          })()}

          {mfaEnabled ? (
            /* Enabled state: show disable button */
            <div className="flex flex-col items-center gap-4 py-4">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center"
                style={{ background: 'color-mix(in srgb, var(--gn) 10%, transparent)' }}
              >
                <ShieldCheck size={32} style={{ color: 'var(--gn)' }} />
              </div>
              <p className="text-xs text-center" style={{ color: 'var(--t3)' }}>
                {t('mfa.disableHint')}
              </p>
              <button
                onClick={handleDisable}
                disabled={loading}
                className="btn btn-danger btn-sm"
              >
                {loading ? <Loader2 size={14} className="animate-spin" /> : <ShieldOff size={14} />}
                {t('mfa.disableBtn')}
              </button>
            </div>
          ) : secret && totpUri ? (
            /* Setup step 2: show secret + QR + verify */
            <div className="flex flex-col gap-4">
              {/* Instructions */}
              <div className="flex items-start gap-3">
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 text-[.65rem] font-bold"
                  style={{ background: 'var(--ac)', color: '#fff' }}
                >
                  1
                </div>
                <div>
                  <p className="text-xs font-semibold" style={{ color: 'var(--t1)' }}>
                    {t('mfa.scanQr')}
                  </p>
                  <p className="text-[.68rem] mt-0.5" style={{ color: 'var(--t4)' }}>
                    {t('mfa.openApp')}
                  </p>
                </div>
              </div>

              {/* QR code */}
              <div className="flex justify-center">
                <div className="p-3 rounded-xl" style={{ background: '#fff' }}>
                  <img
                    src={`https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${encodeURIComponent(totpUri)}`}
                    alt="QR Code TOTP"
                    width={180}
                    height={180}
                    className="rounded"
                  />
                </div>
              </div>

              {/* Secret */}
              <div
                className="px-3.5 py-2.5 rounded-lg text-center"
                style={{ background: 'var(--bg2)', border: '1px solid var(--bd)' }}
              >
                <span className="text-[.62rem] block mb-1" style={{ color: 'var(--t4)' }}>SECRET</span>
                <code
                  className="text-xs font-bold tracking-wider select-all cursor-pointer"
                  style={{ color: 'var(--ac)', fontFamily: 'var(--fm)' }}
                  title="Clique para selecionar"
                >
                  {secret}
                </code>
              </div>

              {/* Verify */}
              <div className="flex items-start gap-3">
                <div
                  className="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 text-[.65rem] font-bold"
                  style={{ background: 'var(--ac)', color: '#fff' }}
                >
                  2
                </div>
                <div className="flex-1">
                  <p className="text-xs font-semibold mb-2" style={{ color: 'var(--t1)' }}>
                    {t('mfa.enterCode')}
                  </p>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={code}
                      onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                      placeholder="000000"
                      maxLength={6}
                      className="flex-1 px-3 py-2 rounded-lg text-sm text-center tracking-[.3em] font-semibold outline-none transition-colors"
                      style={{
                        background: 'var(--bg2)',
                        border: '1px solid var(--bd)',
                        color: 'var(--t1)',
                        fontFamily: 'var(--fm)',
                      }}
                      onFocus={(e) => { e.target.style.borderColor = 'var(--ac)'; }}
                      onBlur={(e) => { e.target.style.borderColor = 'var(--bd)'; }}
                      onKeyDown={(e) => { if (e.key === 'Enter') handleVerify(); }}
                      autoFocus
                    />
                    <button
                      onClick={handleVerify}
                      disabled={loading || code.length !== 6}
                      className="btn btn-success btn-sm"
                    >
                      {loading ? <Loader2 size={14} className="animate-spin" /> : <KeyRound size={14} />}
                      {t('mfa.activateMfa')}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            /* Setup step 1: generate secret */
            <div className="flex flex-col items-center gap-4 py-4">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center"
                style={{ background: 'color-mix(in srgb, var(--yl) 10%, transparent)' }}
              >
                <KeyRound size={32} style={{ color: 'var(--yl)' }} />
              </div>
              <p className="text-xs text-center max-w-xs" style={{ color: 'var(--t3)' }}>
                {t('mfa.generateHint')}
              </p>
              <button
                onClick={handleSetup}
                disabled={loading}
                className="btn btn-primary"
              >
                {loading ? <Loader2 size={16} className="animate-spin" /> : <KeyRound size={16} />}
                {t('mfa.generateSecret')}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
