"use client";

import { type SecurityCheck, type SecurityAuditResult } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription } from "@/components/ui/alert";

interface SecurityTabProps {
  securityAudit: SecurityAuditResult | null;
  securityLoading: boolean;
  securityError: string;
  fixLoading: string | null;
  fixMessage: string;
  onRunAudit: () => void;
  onRunFix: (action: string) => void;
}

export function SecurityTab({
  securityAudit,
  securityLoading,
  securityError,
  fixLoading,
  fixMessage,
  onRunAudit,
  onRunFix,
}: SecurityTabProps) {
  return (
    <div className="mt-4 space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">Security Audit</h2>
          {securityAudit && (
            <p className="text-xs text-muted-foreground mt-0.5">
              Zuletzt geprüft: {new Date(securityAudit.run_at).toLocaleString("de-DE")}
            </p>
          )}
        </div>
        <Button onClick={onRunAudit} disabled={securityLoading || fixLoading !== null} size="sm">
          {securityLoading ? "Prüfe..." : "Jetzt prüfen"}
        </Button>
      </div>

      {securityError && (
        <Alert variant="destructive">
          <AlertDescription>{securityError}</AlertDescription>
        </Alert>
      )}

      {fixMessage && (
        <Alert>
          <AlertDescription className="text-green-700">{fixMessage}</AlertDescription>
        </Alert>
      )}

      {!securityAudit && !securityLoading && !securityError && (
        <div className="rounded-lg border border-dashed p-10 text-center text-sm text-muted-foreground">
          Klicke auf &ldquo;Jetzt prüfen&rdquo; um den Security-Audit zu starten.
        </div>
      )}

      {securityLoading && (
        <div className="space-y-3">
          {Array.from({ length: 7 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full rounded-lg" />
          ))}
        </div>
      )}

      {securityAudit && !securityLoading && (() => {
        // Map check names to fix actions
        const fixActions: Record<string, { action: string; label: string }> = {
          "Fail2ban":          { action: "install_fail2ban",      label: "Installieren & aktivieren" },
          "Firewall (nftables)": { action: "enable_firewall",     label: "Firewall aktivieren" },
          "SSH Passwort-Auth": { action: "fix_ssh_password_auth", label: "Deaktivieren" },
          "SSH Root-Login":    { action: "fix_ssh_root_login",    label: "Auf prohibit-password setzen" },
        };

        return (
          <div className="space-y-2">
            {securityAudit.checks.map((check: SecurityCheck, i: number) => {
              const fix = check.status !== "ok" ? fixActions[check.name] : undefined;
              return (
                <Card key={i}>
                  <CardContent className="p-4 flex items-start gap-3">
                    <span className={`mt-1 h-2.5 w-2.5 flex-shrink-0 rounded-full ${
                      check.status === "ok" ? "bg-green-500" :
                      check.status === "warning" ? "bg-yellow-400" : "bg-red-500"
                    }`} />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-sm font-medium">{check.name}</span>
                        <Badge
                          variant={check.status === "ok" ? "default" : check.status === "warning" ? "secondary" : "destructive"}
                          className={`text-xs ${check.status === "ok" ? "bg-green-100 text-green-800 hover:bg-green-100" : check.status === "warning" ? "bg-yellow-100 text-yellow-800 hover:bg-yellow-100" : ""}`}
                        >
                          {check.status === "ok" ? "OK" : check.status === "warning" ? "Warnung" : "Fehler"}
                        </Badge>
                      </div>
                      <p className="text-xs text-muted-foreground mt-0.5 font-mono">{check.message}</p>
                    </div>
                    {fix && (
                      <Button
                        size="sm"
                        variant="outline"
                        className="flex-shrink-0 text-xs"
                        disabled={fixLoading !== null}
                        onClick={() => onRunFix(fix.action)}
                      >
                        {fixLoading === fix.action ? "Wird behoben..." : fix.label}
                      </Button>
                    )}
                    {check.name === "HTTPS (TLS)" && check.status !== "ok" && (
                      <a
                        href="https://certbot.eff.org/instructions?os=debianbuster&tab=standard"
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Button size="sm" variant="outline" className="flex-shrink-0 text-xs">
                          Anleitung
                        </Button>
                      </a>
                    )}
                  </CardContent>
                </Card>
              );
            })}

            {/* Summary */}
            <div className="mt-4 grid grid-cols-3 gap-3 text-center text-sm">
              {[
                { label: "OK", color: "bg-green-50 text-green-700", count: securityAudit.checks.filter((c: SecurityCheck) => c.status === "ok").length },
                { label: "Warnungen", color: "bg-yellow-50 text-yellow-700", count: securityAudit.checks.filter((c: SecurityCheck) => c.status === "warning").length },
                { label: "Fehler", color: "bg-red-50 text-red-700", count: securityAudit.checks.filter((c: SecurityCheck) => c.status === "error").length },
              ].map((s) => (
                <div key={s.label} className={`rounded p-3 ${s.color}`}>
                  <p className="text-2xl font-bold">{s.count}</p>
                  <p className="text-xs">{s.label}</p>
                </div>
              ))}
            </div>
          </div>
        );
      })()}
    </div>
  );
}
