'use client';

import { Shield, CheckCircle } from 'lucide-react';
import QRCode from 'qrcode';
import { useState } from 'react';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';

export default function TwoFactorAuthPage() {
  const [isEnabled, setIsEnabled] = useState(false);
  const [qrCode, setQrCode] = useState<string | null>(null);
  const [secret, setSecret] = useState<string | null>(null);
  const [verificationCode, setVerificationCode] = useState('');
  const [isVerifying, setIsVerifying] = useState(false);

  const enable2FA = async () => {
    try {
      // In production, this would call your backend API
      const response = await fetch('/api/auth/2fa/setup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });
      const data = await response.json();
      
      setSecret(data.secret);
      const qr = await QRCode.toDataURL(data.qrCodeUrl);
      setQrCode(qr);
    } catch {
      /* setup failed — surface UI toast when wired */
    }
  };

  const verifyAndEnable = async () => {
    setIsVerifying(true);
    try {
      const response = await fetch('/api/auth/2fa/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: verificationCode, secret }),
      });
      
      if (response.ok) {
        setIsEnabled(true);
        setQrCode(null);
        setSecret(null);
      }
    } catch {
      /* verification failed */
    } finally {
      setIsVerifying(false);
    }
  };

  const disable2FA = async () => {
    try {
      await fetch('/api/auth/2fa/disable', { method: 'POST' });
      setIsEnabled(false);
    } catch {
      /* disable failed */
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-white mb-2">Two-Factor Authentication</h1>
        <p className="text-gray-400">Add an extra layer of security to your account</p>
      </div>

      <Card className="bg-gray-800 border-gray-700 max-w-2xl">
        <CardHeader>
          <div className="flex items-center gap-3">
            <Shield className="h-6 w-6 text-orange-500" />
            <div>
              <CardTitle className="text-white">2FA Status</CardTitle>
              <p className="text-gray-400 text-sm mt-2">
                {isEnabled ? 'Two-factor authentication is enabled' : 'Two-factor authentication is disabled'}
              </p>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {!isEnabled && !qrCode && (
            <div>
              <p className="text-gray-300 mb-4">
                Enable two-factor authentication to protect your account with an additional security layer.
              </p>
              <button
                onClick={enable2FA}
                className="px-6 py-3 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors"
              >
                Enable 2FA
              </button>
            </div>
          )}

          {qrCode && secret && (
            <div className="space-y-4">
              <div>
                <p className="text-gray-300 mb-2">Scan this QR code with your authenticator app:</p>
                <div className="flex justify-center p-4 bg-white rounded">
                  {/* eslint-disable-next-line @next/next/no-img-element -- data: URL from qrcode package */}
                  <img src={qrCode} alt="2FA QR Code" className="w-48 h-48" />
                </div>
              </div>
              
              <div>
                <p className="text-gray-300 mb-2">Or enter this secret manually:</p>
                <code className="block p-3 bg-gray-900 rounded text-white font-mono text-sm break-all">
                  {secret}
                </code>
              </div>

              <div>
                <label htmlFor="settings-2fa-verify-code" className="block text-sm text-gray-300 mb-2">
                  Enter verification code from your app:
                </label>
                <input
                  id="settings-2fa-verify-code"
                  type="text"
                  value={verificationCode}
                  onChange={(e) => setVerificationCode(e.target.value)}
                  placeholder="000000"
                  maxLength={6}
                  className="w-full px-4 py-2 bg-gray-900 border border-gray-700 rounded text-white"
                />
              </div>

              <button
                onClick={verifyAndEnable}
                disabled={verificationCode.length !== 6 || isVerifying}
                className="px-6 py-3 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors disabled:opacity-50"
              >
                {isVerifying ? 'Verifying...' : 'Verify and Enable'}
              </button>
            </div>
          )}

          {isEnabled && (
            <div className="space-y-4">
              <div className="flex items-center gap-2 text-green-400">
                <CheckCircle className="h-5 w-5" />
                <span>Two-factor authentication is active</span>
              </div>
              <button
                onClick={disable2FA}
                className="px-6 py-3 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
              >
                Disable 2FA
              </button>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

