"use client";

import { type ImapAccount } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";

function statusBadge(status: string) {
  switch (status) {
    case "running":
      return <Badge className="bg-blue-600 text-white">Importiert...</Badge>;
    case "error":
      return <Badge variant="destructive">Fehler</Badge>;
    default:
      return <Badge variant="secondary">Bereit</Badge>;
  }
}

function syncBadge(acc: ImapAccount) {
  if (acc.sync_running) {
    return <Badge className="bg-blue-500 text-white">Sync laeuft...</Badge>;
  }
  if (!acc.sync_status) return null;
  if (acc.sync_status === "ok") {
    return <Badge className="bg-green-600 text-white">Sync OK</Badge>;
  }
  if (acc.sync_status === "error") {
    return <Badge variant="destructive">Sync Fehler</Badge>;
  }
  return null;
}

interface ImapAccountCardProps {
  acc: ImapAccount;
  onStartImport: (id: number) => void;
  onSyncNow: (id: number) => void;
  onEdit: (acc: ImapAccount) => void;
  onDelete: (id: number) => void;
  onIntervalChange: (id: number, value: string) => void;
}

export function ImapAccountCard({
  acc,
  onStartImport,
  onSyncNow,
  onEdit,
  onDelete,
  onIntervalChange,
}: ImapAccountCardProps) {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <div>
          <h3 className="font-semibold">{acc.name}</h3>
          <p className="text-sm text-muted-foreground">
            {acc.host}:{acc.port} ({acc.tls.toUpperCase()}) &middot; {acc.username}
          </p>
        </div>
        {statusBadge(acc.status)}
      </CardHeader>
      <CardContent>
        {acc.status === "running" && acc.progress_total === 0 && (
          <div className="mb-3 space-y-1">
            <Progress value={undefined} className="animate-pulse" />
            <p className="text-xs text-muted-foreground">
              Zaehle E-Mails auf dem Server...
            </p>
          </div>
        )}
        {acc.status === "running" && acc.progress_total > 0 && (
          <div className="mb-3 space-y-1">
            <Progress
              value={(acc.progress_current / acc.progress_total) * 100}
            />
            <p className="text-xs text-muted-foreground">
              {acc.progress_current} von {acc.progress_total} E-Mails
            </p>
          </div>
        )}

        {acc.status === "error" && acc.error_msg && (
          <p className="mb-3 text-sm text-destructive">{acc.error_msg}</p>
        )}

        {acc.last_import_at && (
          <p className="text-sm text-muted-foreground mb-3">
            Letzter Import:{" "}
            {new Date(acc.last_import_at).toLocaleString("de-DE")} (
            {acc.last_import_count} E-Mails)
          </p>
        )}

        {/* PROJ-8: Sync status */}
        {acc.last_sync_at && (
          <div className="flex items-center gap-2 mb-3">
            <p className="text-sm text-muted-foreground">
              Letzter Sync:{" "}
              {new Date(acc.last_sync_at).toLocaleString("de-DE")} (
              {acc.last_sync_count} neu)
            </p>
            {syncBadge(acc)}
          </div>
        )}

        {acc.sync_running && !acc.last_sync_at && syncBadge(acc)}

        {acc.sync_error_msg && acc.sync_status === "error" && (
          <p className="mb-3 text-sm text-destructive">
            Sync-Fehler: {acc.sync_error_msg}
          </p>
        )}

        {acc.excluded_folders && acc.excluded_folders.length > 0 && (
          <p className="text-xs text-muted-foreground mb-3">
            Ausgeschlossene Ordner: {acc.excluded_folders.join(", ")}
          </p>
        )}

        {/* PROJ-8: Sync interval selector */}
        <div className="mb-3 flex items-center gap-3">
          <span className="text-sm text-muted-foreground whitespace-nowrap">
            Auto-Sync:
          </span>
          <Select
            value={String(acc.sync_interval_min ?? 0)}
            onValueChange={(v) => onIntervalChange(acc.id, v)}
          >
            <SelectTrigger className="w-40 h-8 text-sm">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="0">Deaktiviert</SelectItem>
              <SelectItem value="5">5 min</SelectItem>
              <SelectItem value="15">15 min</SelectItem>
              <SelectItem value="30">30 min</SelectItem>
              <SelectItem value="60">1 Stunde</SelectItem>
              <SelectItem value="360">6 Stunden</SelectItem>
              <SelectItem value="1440">24 Stunden</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="flex gap-2 flex-wrap">
          <Button
            size="sm"
            disabled={acc.status === "running"}
            onClick={() => onStartImport(acc.id)}
          >
            Import starten
          </Button>
          <Button
            size="sm"
            variant="outline"
            disabled={acc.status === "running" || acc.sync_running}
            onClick={() => onSyncNow(acc.id)}
          >
            Sync jetzt
          </Button>
          <Button size="sm" variant="outline" onClick={() => onEdit(acc)}>
            Bearbeiten
          </Button>
          <Button
            size="sm"
            variant="destructive"
            disabled={acc.status === "running"}
            onClick={() => onDelete(acc.id)}
          >
            Loeschen
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
