"use client";

import { Card, CardContent, 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 {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import type { useTotpSettings } from "@/hooks/useTotpSettings";

type TotpSectionProps = ReturnType<typeof useTotpSettings>;

export function TotpSection({
  totpEnabled,
  showSetup,
  qrCode,
  secret,
  totpCode,
  setTotpCode,
  totpError,
  totpSuccess,
  totpLoading,
  disableDialogOpen,
  setDisableDialogOpen,
  disableCode,
  setDisableCode,
  disableError,
  disableLoading,
  handleSetupTOTP,
  handleConfirmTOTP,
  handleDisableTOTP,
  cancelSetup,
  openDisableDialog,
}: TotpSectionProps) {
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-3">
          Zwei-Faktor-Authentifizierung (2FA)
          {totpEnabled ? (
            <Badge variant="default" className="bg-green-600">
              Aktiv
            </Badge>
          ) : (
            <Badge variant="secondary">Inaktiv</Badge>
          )}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {totpError && (
          <Alert variant="destructive">
            <AlertDescription>{totpError}</AlertDescription>
          </Alert>
        )}
        {totpSuccess && (
          <Alert>
            <AlertDescription>{totpSuccess}</AlertDescription>
          </Alert>
        )}

        {!totpEnabled && !showSetup && (
          <div>
            <p className="text-sm text-muted-foreground mb-4">
              Schuetzen Sie Ihr Konto mit einem Einmalpasswort (TOTP).
              Kompatibel mit Google Authenticator, Authy und anderen
              TOTP-Apps.
            </p>
            <Button onClick={handleSetupTOTP} disabled={totpLoading}>
              {totpLoading ? "Laden..." : "2FA einrichten"}
            </Button>
          </div>
        )}

        {showSetup && (
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Scannen Sie den QR-Code mit Ihrer Authenticator-App und geben
              Sie den angezeigten Code ein.
            </p>
            {qrCode && (
              <div className="flex justify-center p-4 bg-white rounded-lg border w-fit mx-auto">
                <img
                  src={`data:image/png;base64,${qrCode}`}
                  alt="TOTP QR-Code"
                  width={200}
                  height={200}
                />
              </div>
            )}
            {secret && (
              <div className="space-y-1">
                <Label className="text-xs text-muted-foreground">
                  Manueller Schluessel
                </Label>
                <code className="block text-sm font-mono bg-muted px-3 py-2 rounded break-all select-all">
                  {secret}
                </code>
              </div>
            )}
            <form onSubmit={handleConfirmTOTP} className="space-y-3">
              <div className="space-y-2">
                <Label htmlFor="totp-code">Bestaetigungscode</Label>
                <Input
                  id="totp-code"
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]{6}"
                  maxLength={6}
                  placeholder="000000"
                  value={totpCode}
                  onChange={(e) => setTotpCode(e.target.value)}
                  required
                  autoComplete="one-time-code"
                  aria-label="TOTP Bestaetigungscode"
                />
              </div>
              <div className="flex gap-2">
                <Button type="submit" disabled={totpLoading}>
                  {totpLoading ? "Pruefen..." : "Bestaetigen"}
                </Button>
                <Button type="button" variant="outline" onClick={cancelSetup}>
                  Abbrechen
                </Button>
              </div>
            </form>
          </div>
        )}

        {totpEnabled && (
          <div>
            <p className="text-sm text-muted-foreground mb-4">
              2FA ist aktiv. Zum Deaktivieren benoetigen Sie einen
              aktuellen Code aus Ihrer Authenticator-App.
            </p>
            <Button variant="destructive" onClick={openDisableDialog}>
              2FA deaktivieren
            </Button>
          </div>
        )}

        {/* Disable TOTP dialog */}
        <Dialog open={disableDialogOpen} onOpenChange={setDisableDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>2FA deaktivieren</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <p className="text-sm text-muted-foreground">
                Geben Sie einen aktuellen Code aus Ihrer Authenticator-App
                ein, um 2FA zu deaktivieren.
              </p>
              <div className="space-y-2">
                <Label htmlFor="disable-totp-code">TOTP-Code</Label>
                <Input
                  id="disable-totp-code"
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]{6}"
                  maxLength={6}
                  placeholder="000000"
                  value={disableCode}
                  onChange={(e) => setDisableCode(e.target.value)}
                  autoComplete="one-time-code"
                  aria-label="TOTP-Code zum Deaktivieren"
                />
              </div>
              {disableError && (
                <Alert variant="destructive">
                  <AlertDescription>{disableError}</AlertDescription>
                </Alert>
              )}
            </div>
            <DialogFooter>
              <Button
                variant="outline"
                onClick={() => setDisableDialogOpen(false)}
              >
                Abbrechen
              </Button>
              <Button
                variant="destructive"
                onClick={handleDisableTOTP}
                disabled={disableLoading || disableCode.length !== 6}
              >
                {disableLoading ? "Pruefen..." : "Deaktivieren"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </CardContent>
    </Card>
  );
}
