import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, Download, CheckCircle, AlertCircle, Shield } from 'lucide-react';
import { twoFactorService } from '@/services/2fa-service';
import { useToast } from '@/hooks/use-toast';

export function TwoFactorSetup() {
  const [isEnabled, setIsEnabled] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isSettingUp, setIsSettingUp] = useState(false);
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  const [secret, setSecret] = useState('');
  const [backupCodes, setBackupCodes] = useState<string[]>([]);
  const [verificationCode, setVerificationCode] = useState('');
  const [showBackupCodes, setShowBackupCodes] = useState(false);
  const [error, setError] = useState('');
  const { toast } = useToast();

  useEffect(() => {
    checkStatus();
  }, []);

  const checkStatus = async () => {
    try {
      const status = await twoFactorService.getStatus();
      setIsEnabled(status.enabled);
    } catch (error: any) {
      toast({
        title: 'Failed to check 2FA status',
        description: error.message,
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSetup = async () => {
    try {
      setIsSettingUp(true);
      const setup = await twoFactorService.setup();
      setQrCodeUrl(setup.qr_code_url);
      setSecret(setup.secret);
      setBackupCodes(setup.backup_codes);
    } catch (error: any) {
      setError(error.message);
      toast({
        title: 'Failed to setup 2FA',
        description: error.message,
        variant: 'destructive',
      });
    } finally {
      setIsSettingUp(false);
    }
  };

  const handleEnable = async () => {
    if (!verificationCode) {
      setError('Please enter the verification code');
      return;
    }

    try {
      await twoFactorService.enable(verificationCode);
      setIsEnabled(true);
      setShowBackupCodes(true);
      toast({
        title: '2FA enabled',
        description: 'Two-factor authentication has been enabled',
      });
    } catch (error: any) {
      setError(error.message);
      toast({
        title: 'Failed to enable 2FA',
        description: error.message,
        variant: 'destructive',
      });
    }
  };

  const handleDisable = async () => {
    if (!verificationCode) {
      setError('Please enter the verification code');
      return;
    }

    try {
      await twoFactorService.disable(verificationCode);
      setIsEnabled(false);
      setQrCodeUrl('');
      setSecret('');
      setBackupCodes([]);
      setVerificationCode('');
      toast({
        title: '2FA disabled',
        description: 'Two-factor authentication has been disabled',
      });
    } catch (error: any) {
      setError(error.message);
      toast({
        title: 'Failed to disable 2FA',
        description: error.message,
        variant: 'destructive',
      });
    }
  };

  const downloadBackupCodes = () => {
    const content = `Veza 2FA Backup Codes\n\n${backupCodes.join('\n')}\n\nSave these codes in a safe place.`;
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'veza-2fa-backup-codes.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Two-Factor Authentication</CardTitle>
          <CardDescription>Manage your 2FA settings</CardDescription>
        </CardHeader>
        <CardContent className="flex items-center justify-center py-8">
          <Loader2 className="h-6 w-6 animate-spin" />
        </CardContent>
      </Card>
    );
  }

  if (isEnabled) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5 text-green-500" />
            Two-Factor Authentication (Enabled)
          </CardTitle>
          <CardDescription>Your account is protected with 2FA</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center gap-2 text-green-600">
            <CheckCircle className="h-4 w-4" />
            <span>Two-factor authentication is active</span>
          </div>

          {showBackupCodes && backupCodes.length > 0 && (
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                <div className="space-y-2">
                  <p className="font-medium">Save these backup codes!</p>
                  <div className="bg-gray-100 p-3 rounded font-mono text-sm">
                    {backupCodes.join('\n')}
                  </div>
                  <Button onClick={downloadBackupCodes} variant="outline" size="sm">
                    <Download className="h-4 w-4 mr-2" />
                    Download Backup Codes
                  </Button>
                </div>
              </AlertDescription>
            </Alert>
          )}

          <div className="space-y-4">
            <Label>Disable 2FA</Label>
            <Input
              type="text"
              placeholder="Enter 2FA code"
              value={verificationCode}
              onChange={(e) => setVerificationCode(e.target.value)}
              maxLength={6}
            />
            {error && <p className="text-sm text-red-600">{error}</p>}
            <Button onClick={handleDisable} variant="destructive">
              Disable 2FA
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Two-Factor Authentication</CardTitle>
        <CardDescription>Add an extra layer of security to your account</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {!qrCodeUrl && (
          <div className="space-y-4">
            <p className="text-sm text-gray-600">
              Two-factor authentication adds an extra layer of security to your account.
              You'll need to enter a code from your authenticator app each time you sign in.
            </p>
            <Button onClick={handleSetup} disabled={isSettingUp}>
              {isSettingUp ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Setting up...
                </>
              ) : (
                'Enable 2FA'
              )}
            </Button>
          </div>
        )}

        {qrCodeUrl && (
          <>
            <Alert>
              <Shield className="h-4 w-4" />
              <AlertDescription>
                Scan this QR code with your authenticator app (Google Authenticator, Authy, etc.)
              </AlertDescription>
            </Alert>

            <div className="flex justify-center p-4 bg-white rounded">
              <img src={qrCodeUrl} alt="QR Code" className="w-64 h-64" />
            </div>

            <div className="space-y-2">
              <Label>Or enter this secret manually:</Label>
              <code className="block p-2 bg-gray-100 rounded text-sm break-all">{secret}</code>
            </div>

            <div className="space-y-4">
              <Label>Enter the verification code from your app</Label>
              <Input
                type="text"
                placeholder="000000"
                value={verificationCode}
                onChange={(e) => setVerificationCode(e.target.value)}
                maxLength={6}
              />
              {error && <p className="text-sm text-red-600">{error}</p>}
              <Button onClick={handleEnable} className="w-full">
                Enable 2FA
              </Button>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}

