"use client";

import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Loader2, Shield, ShieldCheck, ShieldX, Smartphone, QrCode, AlertTriangle, Copy, Eye, EyeOff, Type } from "lucide-react";
import { toast } from "sonner";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";

interface MfaFactor {
  id: string;
  friendlyName?: string;
  createdAt: string;
}

interface MfaStatus {
  hasMfa: boolean;
  factors: MfaFactor[];
}

interface MfaSetupComponentProps {
  onStatusChange?: () => void;
}

export function MfaSetupComponent({ onStatusChange }: MfaSetupComponentProps) {
  const [mfaStatus, setMfaStatus] = useState<MfaStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [enrollStep, setEnrollStep] = useState<'idle' | 'enroll' | 'verify'>('idle');
  const [qrCode, setQrCode] = useState<string>('');
  const [factorId, setFactorId] = useState<string>('');
  const [secret, setSecret] = useState<string>('');
  const [totpUri, setTotpUri] = useState<string>('');
  const [verificationCode, setVerificationCode] = useState<string>('');
  const [enrollLoading, setEnrollLoading] = useState(false);
  const [verifyLoading, setVerifyLoading] = useState(false);
  const [unenrollLoading, setUnenrollLoading] = useState(false);
  const [showManualEntry, setShowManualEntry] = useState(false);
  const [showUnenrollModal, setShowUnenrollModal] = useState(false);

  const fetchMfaStatus = async () => {
    try {
      const response = await fetch('/api/auth/mfa/status', {
        credentials: 'include',
        cache: 'no-store'
      });
      
      if (response.ok) {
        const data = await response.json();
        setMfaStatus(data);
      } else {
        console.error('Erreur lors de la récupération du statut MFA');
        toast.error('Erreur lors de la récupération du statut 2FA');
      }
    } catch (error) {
      console.error('Erreur fetch MFA status:', error);
      toast.error('Erreur de connexion');
    } finally {
      setLoading(false);
    }
  };

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

  const handleEnrollStart = async () => {
    setEnrollLoading(true);
    try {
      const response = await fetch('/api/auth/mfa/enroll', {
        method: 'POST',
        credentials: 'include',
      });

      const data = await response.json();
      
      if (response.ok) {
        setQrCode(data.qrCode);
        setFactorId(data.factorId);
        setSecret(data.secret);
        setTotpUri(data.uri);
        setEnrollStep('verify');
        setShowManualEntry(false); // Reset manual entry mode
        toast.success('Configuration 2FA prête - scannez le QR code ou utilisez la saisie manuelle');
      } else {
        if (data.error?.includes('facteur') || data.error?.includes('factor')) {
          toast.error('Configuration 2FA en cours de nettoyage. Veuillez réessayer dans quelques secondes.');
        } else {
          toast.error(data.error || 'Erreur lors de l\'activation du 2FA');
        }
      }
    } catch (error) {
      console.error('Erreur enroll MFA:', error);
      toast.error('Erreur de connexion');
    } finally {
      setEnrollLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    if (!verificationCode || verificationCode.length !== 6) {
      toast.error('Veuillez saisir un code à 6 chiffres');
      return;
    }

    setVerifyLoading(true);
    try {
      const response = await fetch('/api/auth/mfa/verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({
          factorId: factorId,
          code: verificationCode,
        }),
      });

      const data = await response.json();
      
      if (response.ok) {
        toast.success('2FA activé avec succès !');
        setEnrollStep('idle');
        setVerificationCode('');
        setQrCode('');
        setFactorId('');
        setSecret('');
        setTotpUri('');
        setShowManualEntry(false);
        fetchMfaStatus();
        onStatusChange?.();
      } else {
        toast.error(data.error || 'Code invalide');
      }
    } catch (error) {
      console.error('Erreur verify MFA:', error);
      toast.error('Erreur de connexion');
    } finally {
      setVerifyLoading(false);
    }
  };

  const handleUnenrollOpen = () => setShowUnenrollModal(true);
  const handleUnenrollConfirm = async () => {
    setUnenrollLoading(true);
    try {
      const response = await fetch('/api/auth/mfa/unenroll', {
        method: 'DELETE',
        credentials: 'include',
      });

      const data = await response.json();
      
      if (response.ok) {
        toast.success('2FA désactivé avec succès');
        setShowUnenrollModal(false);
        fetchMfaStatus();
        onStatusChange?.();
      } else {
        toast.error(data.error || 'Erreur lors de la désactivation du 2FA');
      }
    } catch (error) {
      console.error('Erreur unenroll MFA:', error);
      toast.error('Erreur de connexion');
    } finally {
      setUnenrollLoading(false);
    }
  };

  const handleCancelEnroll = () => {
    setEnrollStep('idle');
    setVerificationCode('');
    setQrCode('');
    setFactorId('');
    setSecret('');
    setTotpUri('');
    setShowManualEntry(false);
  };

  const copyToClipboard = async (text: string, label: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast.success(`${label} copié dans le presse-papiers`);
    } catch (error) {
      console.error('Erreur copie clipboard:', error);
      toast.error('Impossible de copier dans le presse-papiers');
    }
  };

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Double authentification (2FA)
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-6 w-6 animate-spin" />
            <span className="ml-2">Chargement...</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          {mfaStatus?.hasMfa ? (
            <ShieldCheck className="h-5 w-5 text-green-600" />
          ) : (
            <Shield className="h-5 w-5" />
          )}
          Double authentification (2FA)
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {mfaStatus?.hasMfa ? (
          <div className="space-y-4">
            <div className="flex items-center gap-2 text-green-600">
              <ShieldCheck className="h-4 w-4" />
              <span className="text-sm font-medium">2FA actif</span>
            </div>
            
            <p className="text-sm text-slate-600">
              Votre compte est protégé par la double authentification. 
              Un code de votre application d'authentification sera requis lors de la connexion.
            </p>

            {mfaStatus.factors.map((factor) => (
              <div key={factor.id} className="p-3 border rounded-lg">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Smartphone className="h-4 w-4" />
                    <span className="text-sm font-medium">
                      {factor.friendlyName || 'Application d\'authentification'}
                    </span>
                  </div>
                  <span className="text-xs text-slate-500">
                    Ajouté le {new Date(factor.createdAt).toLocaleDateString()}
                  </span>
                </div>
              </div>
            ))}

            <Button 
              variant="outline" 
              onClick={handleUnenrollOpen}
              disabled={unenrollLoading}
              className="w-full bg-red-50 border-red-200 text-red-700 hover:bg-red-100"
            >
              {unenrollLoading ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Désactivation...
                </>
              ) : (
                <>
                  <ShieldX className="h-4 w-4 mr-2" />
                  Désactiver le 2FA
                </>
              )}
            </Button>
            <Dialog open={showUnenrollModal} onOpenChange={setShowUnenrollModal}>
              <DialogContent className="max-w-md">
                <DialogHeader>
                  <DialogTitle className="flex items-center gap-2">
                    <AlertTriangle className="text-red-500" size={18} />
                    Désactiver la double authentification
                  </DialogTitle>
                </DialogHeader>
                <div className="space-y-3 text-sm text-slate-700">
                  <p>
                    La 2FA protège votre compte contre les accès non autorisés. 
                    En la désactivant, votre sécurité sera réduite.
                  </p>
                  <p className="text-slate-600">
                    Vous pourrez la réactiver plus tard depuis cette page. En cas de doute, contactez le support.
                  </p>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setShowUnenrollModal(false)}>
                    Annuler
                  </Button>
                  <Button 
                    onClick={handleUnenrollConfirm}
                    disabled={unenrollLoading}
                    className="bg-red-600 hover:bg-red-700"
                  >
                    {unenrollLoading ? 'Désactivation…' : 'Désactiver le 2FA'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        ) : (
          <div className="space-y-4">
            {enrollStep === 'idle' && (
              <>
                <p className="text-sm text-slate-600">
                  Renforcez la sécurité de votre compte avec la double authentification. 
                  Vous aurez besoin d'une application comme Google Authenticator, Authy ou Microsoft Authenticator.
                </p>
                
                <div className="flex items-start gap-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <AlertTriangle className="h-4 w-4 text-blue-600 mt-0.5 flex-shrink-0" />
                  <div className="text-sm text-blue-700">
                    <strong>Important :</strong> Gardez votre téléphone à portée de main et assurez-vous 
                    d'avoir une application d'authentification installée avant de continuer.
                  </div>
                </div>

                <Button 
                  onClick={handleEnrollStart}
                  disabled={enrollLoading}
                  className="w-full"
                >
                  {enrollLoading ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Activation...
                    </>
                  ) : (
                    <>
                      <ShieldCheck className="h-4 w-4 mr-2" />
                      Activer le 2FA
                    </>
                  )}
                </Button>
              </>
            )}

            {enrollStep === 'verify' && (
              <div className="space-y-4">
                <div className="text-center space-y-4">
                  <h3 className="text-lg font-medium flex items-center justify-center gap-2">
                    <QrCode className="h-5 w-5" />
                    Configuration de l'authentification
                  </h3>
                  
                  {!showManualEntry ? (
                    <>
                      {qrCode && (
                        <div className="flex justify-center p-4 bg-white rounded-lg border">
                          <img src={qrCode} alt="QR Code pour 2FA" className="max-w-48 max-h-48" />
                        </div>
                      )}
                      
                      <p className="text-sm text-slate-600">
                        Scannez ce QR code avec votre application d'authentification 
                        (Google Authenticator, Authy, etc.)
                      </p>

                      <div className="flex flex-col sm:flex-row gap-2 justify-center">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setShowManualEntry(true)}
                          className="text-xs"
                        >
                          <Type className="h-3 w-3 mr-2" />
                          Saisie manuelle
                        </Button>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="text-left space-y-4 p-4 bg-slate-50 rounded-lg">
                        <p className="text-sm text-slate-700 font-medium">
                          Copiez ces informations dans votre application d'authentification :
                        </p>
                        
                        <div className="space-y-3">
                          <div>
                            <Label className="text-xs text-slate-600">Code secret :</Label>
                            <div className="flex items-center gap-2 mt-1">
                              <Input
                                value={secret}
                                readOnly
                                className="font-mono text-sm bg-white border-slate-200"
                              />
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => copyToClipboard(secret, 'Code secret')}
                                className="flex-shrink-0"
                              >
                                <Copy className="h-3 w-3" />
                              </Button>
                            </div>
                          </div>

                          <div>
                            <Label className="text-xs text-slate-600">URI TOTP (optionnel) :</Label>
                            <div className="flex items-center gap-2 mt-1">
                              <Input
                                value={totpUri}
                                readOnly
                                className="font-mono text-xs bg-white border-slate-200"
                              />
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => copyToClipboard(totpUri, 'URI TOTP')}
                                className="flex-shrink-0"
                              >
                                <Copy className="h-3 w-3" />
                              </Button>
                            </div>
                          </div>
                        </div>

                        <p className="text-xs text-slate-600">
                          Dans votre application : Ajouter un compte → Saisie manuelle → 
                          Collez le code secret ci-dessus
                        </p>
                      </div>

                      <div className="flex justify-center">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setShowManualEntry(false)}
                          className="text-xs"
                        >
                          <QrCode className="h-3 w-3 mr-2" />
                          Retour au QR code
                        </Button>
                      </div>
                    </>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="verification-code">Code de vérification</Label>
                  <Input
                    id="verification-code"
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={6}
                    placeholder="123456"
                    value={verificationCode}
                    onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, ''))}
                    className="text-center text-lg tracking-widest"
                  />
                  <p className="text-xs text-slate-600 text-center">
                    Saisissez le code à 6 chiffres généré par votre application
                  </p>
                </div>

                <div className="flex gap-2">
                  <Button 
                    variant="outline" 
                    onClick={handleCancelEnroll}
                    className="flex-1"
                  >
                    Annuler
                  </Button>
                  <Button 
                    onClick={handleVerifyCode}
                    disabled={verifyLoading || verificationCode.length !== 6}
                    className="flex-1"
                  >
                    {verifyLoading ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        Vérification...
                      </>
                    ) : (
                      'Vérifier'
                    )}
                  </Button>
                </div>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}