import React, { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import {
  Smartphone,
  QrCode,
  ArrowLeft,
  Copy,
  Download,
  AlertTriangle,
  CheckCircle,
  Loader2,
} from 'lucide-react';
import { useToast } from '../../../components/feedback/ToastProvider';
import { twoFactorService } from '../../../services/2fa-service';

interface TwoFactorSetupProps {
  onBack: () => void;
  onComplete: () => void;
}

export const TwoFactorSetup: React.FC<TwoFactorSetupProps> = ({
  onBack,
  onComplete,
}) => {
  const { addToast } = useToast();
  const [step, setStep] = useState(1);
  const [method, setMethod] = useState<'totp' | 'sms'>('totp');
  const [verificationCode, setVerificationCode] = useState('');
  const [loading, setLoading] = useState(false);

  // Real 2FA data from backend
  const [setupData, setSetupData] = useState<{
    secret: string;
    qr_code_url: string;
    recovery_codes: string[];
  } | null>(null);

  const fetchSetupData = async () => {
    setLoading(true);
    try {
      const data = await twoFactorService.setup();
      setSetupData(data);
    } catch (e) {
      addToast('Failed to initialize 2FA setup', 'error');
      onBack();
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async () => {
    if (verificationCode.length < 6 || !setupData) {
      addToast('Invalid code', 'error');
      return;
    }
    setLoading(true);
    try {
      await twoFactorService.verify(setupData.secret, verificationCode);
      setStep(3);
      addToast('2FA Verified Successfully', 'success');
    } catch (e) {
      addToast('Verification failed. Please check the code.', 'error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (step === 2 && method === 'totp' && !setupData) {
      fetchSetupData();
    }
  }, [step, method]);

  const copyCodes = () => {
    if (!setupData?.recovery_codes) return;
    navigator.clipboard.writeText(setupData.recovery_codes.join('\n'));
    addToast('Backup codes copied to clipboard');
  };

  const downloadCodes = () => {
    if (!setupData?.recovery_codes) return;
    const element = document.createElement('a');
    const file = new Blob([setupData.recovery_codes.join('\n')], { type: 'text/plain' });
    element.href = URL.createObjectURL(file);
    element.download = 'veza-backup-codes.txt';
    document.body.appendChild(element);
    element.click();
    addToast('Backup codes downloaded');
  };

  return (
    <div className="animate-fadeIn max-w-2xl mx-auto">
      <div className="mb-6 flex items-center gap-4">
        <button
          onClick={onBack}
          className="p-2 hover:bg-white/5 rounded-full text-kodo-content-dim hover:text-white transition-colors"
        >
          <ArrowLeft className="w-5 h-5" />
        </button>
        <div>
          <h2 className="text-2xl font-bold text-white">
            Enable Two-Factor Authentication
          </h2>
          <p className="text-kodo-content-dim text-sm">
            Protect your account with an extra layer of security.
          </p>
        </div>
      </div>

      {/* STEP 1: CHOOSE METHOD */}
      {step === 1 && (
        <div className="grid gap-4">
          <div
            onClick={() => {
              setMethod('totp');
              setStep(2);
            }}
            className="p-6 border border-kodo-steel rounded-xl bg-kodo-ink hover:bg-white/5 cursor-pointer transition-all hover:border-kodo-steel/50 group"
          >
            <div className="flex items-center gap-4 mb-2">
              <div className="w-12 h-12 rounded-full bg-kodo-steel/10 flex items-center justify-center group-hover:bg-white/5">
                <QrCode className="w-6 h-6 text-kodo-steel" />
              </div>
              <div>
                <h3 className="text-lg font-bold text-white group-hover:text-white">
                  Authenticator App
                </h3>
                <p className="text-sm text-kodo-content-dim">
                  Use Google Authenticator, Authy, or 1Password. (Recommended)
                </p>
              </div>
            </div>
          </div>

          <div
            onClick={() => {
              addToast('SMS method not yet available in this region', 'info');
              // setMethod('sms');
              // setStep(2);
            }}
            className="p-6 border border-kodo-steel rounded-xl bg-kodo-ink opacity-50 cursor-not-allowed transition-all grayscale group"
          >
            <div className="flex items-center gap-4 mb-2">
              <div className="w-12 h-12 rounded-full bg-kodo-gold/10 flex items-center justify-center">
                <Smartphone className="w-6 h-6 text-kodo-gold" />
              </div>
              <div>
                <h3 className="text-lg font-bold text-white">
                  SMS / Text Message
                </h3>
                <p className="text-sm text-kodo-content-dim">
                  Receive a code via text message to your phone.
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* STEP 2: CONFIGURE & VERIFY */}
      {step === 2 && method === 'totp' && (
        <div className="space-y-8 bg-kodo-ink p-8 rounded-xl border border-kodo-steel">
          <div className="text-center">
            {loading && !setupData ? (
              <div className="w-48 h-48 mx-auto flex items-center justify-center">
                <Loader2 className="w-10 h-10 text-primary animate-spin" />
              </div>
            ) : (
              <>
                <div className="bg-white p-4 inline-block rounded-xl mb-4 shadow-glow-cyan/20">
                  <img
                    src={setupData?.qr_code_url}
                    alt="QR Code"
                    className="w-48 h-48"
                  />
                </div>
                <p className="text-sm text-kodo-text-main mb-2">
                  Scan this QR code with your authenticator app.
                </p>
                <p
                  className="text-[10px] text-kodo-content-dim font-mono bg-black/30 py-1 px-3 rounded-full border border-white/5 inline-block cursor-pointer hover:text-white transition-colors"
                  onClick={() => {
                    if (setupData) {
                      navigator.clipboard.writeText(setupData.secret);
                      addToast('Secret Key copied');
                    }
                  }}
                >
                  KEY: {setupData?.secret}
                </p>
              </>
            )}
          </div>

          <div className="border-t border-kodo-steel pt-6">
            <h4 className="font-bold text-white mb-4 flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-primary" /> Verify Configuration
            </h4>
            <div className="flex gap-4">
              <Input
                placeholder="Enter 6-digit code"
                value={verificationCode}
                onChange={(e) =>
                  setVerificationCode(
                    e.target.value.replace(/\D/g, '').slice(0, 6),
                  )
                }
                className="font-mono text-center tracking-[0.5em] text-lg border-primary/20 focus:border-primary"
              />
              <Button
                variant="primary"
                onClick={handleVerify}
                disabled={verificationCode.length !== 6 || loading}
                className="shadow-glow-cyan"
              >
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : 'VERIFY'}
              </Button>
            </div>
          </div>
        </div>
      )}

      {step === 2 && method === 'sms' && (
        <div className="bg-kodo-ink p-8 rounded-xl border border-kodo-steel text-center">
          <Smartphone className="w-16 h-16 text-kodo-gold mx-auto mb-4" />
          <h3 className="text-xl font-bold text-white mb-2">SMS Setup</h3>
          <p className="text-kodo-content-dim mb-6">
            Enter your phone number to receive a verification code.
          </p>
          <div className="flex gap-2 max-w-sm mx-auto">
            <Input placeholder="+1 (555) 000-0000" />
            <Button
              variant="primary"
              onClick={() => addToast('Code sent to your phone', 'info')}
            >
              SEND
            </Button>
          </div>

          <div className="mt-8 border-t border-kodo-steel pt-6 text-left">
            <h4 className="font-bold text-white mb-4">
              Enter Verification Code
            </h4>
            <div className="flex gap-4">
              <Input
                placeholder="000000"
                value={verificationCode}
                onChange={(e) =>
                  setVerificationCode(
                    e.target.value.replace(/\D/g, '').slice(0, 6),
                  )
                }
                className="font-mono text-center tracking-widest text-lg"
              />
              <Button
                variant="primary"
                onClick={handleVerify}
                disabled={verificationCode.length !== 6}
              >
                VERIFY
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* STEP 3: BACKUP CODES */}
      {step === 3 && (
        <div className="space-y-6 bg-kodo-ink p-8 rounded-xl border border-kodo-steel shadow-2xl">
          <div className="flex items-center gap-4 text-lime-500 mb-2">
            <CheckCircle className="w-8 h-8" />
            <h3 className="text-xl font-bold">2FA Enabled Successfully</h3>
          </div>

          <div className="bg-orange-500/10 border border-orange-500/30 p-4 rounded-lg flex gap-4">
            <AlertTriangle className="w-6 h-6 text-orange-500 flex-shrink-0" />
            <div>
              <h4 className="font-bold text-orange-500 text-sm mb-1">
                Save these backup codes
              </h4>
              <p className="text-xs text-kodo-text-main leading-relaxed">
                If you lose your device, these codes are the only way to access
                your account. Store them in a password manager.
              </p>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3 bg-black/40 p-6 rounded-lg font-mono text-sm text-kodo-text-main text-center border border-white/5 group">
            {setupData?.recovery_codes.map((code) => (
              <div key={code} className="py-2 tracking-widest border border-transparent hover:border-white/10 rounded transition-colors bg-white/2">
                {code}
              </div>
            ))}
          </div>

          <div className="flex gap-4 pt-2">
            <Button
              variant="secondary"
              className="flex-1"
              icon={<Copy className="w-4 h-4" />}
              onClick={copyCodes}
            >
              Copy
            </Button>
            <Button
              variant="secondary"
              className="flex-1"
              icon={<Download className="w-4 h-4" />}
              onClick={downloadCodes}
            >
              Download
            </Button>
            <Button variant="primary" className="flex-1 shadow-glow-cyan" onClick={onComplete}>
              Complete
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};
