"use client";

import {
  type SMTPStatus,
  type StorageStats,
  type SystemStats,
  type SystemStatsActivity,
  type SystemStatsEstimate,
  type TimeseriesPoint,
} from "@/lib/api";
import { type User } 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 { Separator } from "@/components/ui/separator";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ReconciliationCard } from "@/components/admin/tabs/ReconciliationCard";

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

function formatUptime(seconds: number): string {
  const d = Math.floor(seconds / 86400);
  const h = Math.floor((seconds % 86400) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (d > 0) return `${d}d ${h}h ${m}m`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

function formatDaysUntilFull(days: number): string {
  if (days < 0) return "∞";
  if (days < 30) return `${days} Tage`;
  if (days < 365) return `${Math.round(days / 30)} Monate`;
  return `${(days / 365).toFixed(1)} Jahre`;
}

function MailTimeseriesChart({ points }: { points: TimeseriesPoint[] }) {
  if (!points || points.length === 0) return null;
  const maxCount = Math.max(...points.map((p) => p.count), 1);
  const BAR_H = 80; // px height of chart area

  return (
    <Card>
      <CardContent className="pt-6 space-y-3">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-muted-foreground">Mail-Eingang (letzte 30 Tage)</span>
          <span className="text-xs text-muted-foreground font-mono">max {maxCount.toLocaleString("de-DE")}/Tag</span>
        </div>
        <Separator />
        <div className="flex items-end gap-px overflow-hidden" style={{ height: BAR_H }}>
          {points.map((p) => {
            const heightPct = maxCount > 0 ? (p.count / maxCount) * 100 : 0;
            const date = new Date(p.day);
            const label = date.toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit" });
            return (
              <div
                key={p.day}
                className="flex-1 group relative flex flex-col justify-end"
                style={{ height: BAR_H }}
                title={`${label}: ${p.count.toLocaleString("de-DE")} Mails`}
              >
                <div
                  className="w-full rounded-t bg-primary/70 group-hover:bg-primary transition-colors"
                  style={{ height: `${Math.max(heightPct, p.count > 0 ? 2 : 0)}%` }}
                />
                {/* tooltip */}
                <div className="absolute bottom-full mb-1 left-1/2 -translate-x-1/2 hidden group-hover:block z-10 pointer-events-none">
                  <div className="bg-popover text-popover-foreground border rounded px-2 py-1 text-xs whitespace-nowrap shadow">
                    {label}: {p.count.toLocaleString("de-DE")}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div className="flex justify-between text-xs text-muted-foreground font-mono">
          <span>{points[0]?.day.slice(5)}</span>
          <span>{points[Math.floor(points.length / 2)]?.day.slice(5)}</span>
          <span>{points[points.length - 1]?.day.slice(5)}</span>
        </div>
      </CardContent>
    </Card>
  );
}

function ActivityCard({ activity }: { activity: SystemStatsActivity }) {
  return (
    <Card>
      <CardContent className="pt-6 space-y-3">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-muted-foreground">Mail-Eingang</span>
        </div>
        <Separator />
        <div className="grid grid-cols-2 gap-1 text-sm">
          <span className="text-muted-foreground">Letzte 60 min</span>
          <span className="font-semibold">{activity.last_60_min.toLocaleString("de-DE")}</span>
          <span className="text-muted-foreground">Letzte 24 h</span>
          <span className="font-semibold">{activity.last_24h.toLocaleString("de-DE")}</span>
          <span className="text-muted-foreground">Letzte 7 Tage</span>
          <span className="font-semibold">{activity.last_7d.toLocaleString("de-DE")}</span>
          <span className="text-muted-foreground">Letzte 30 Tage</span>
          <span className="font-semibold">{activity.last_30d.toLocaleString("de-DE")}</span>
        </div>
      </CardContent>
    </Card>
  );
}

function EstimateCard({ estimate }: { estimate: SystemStatsEstimate }) {
  return (
    <Card>
      <CardContent className="pt-6 space-y-3">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-muted-foreground">Speicherprognose</span>
          {estimate.days_until_full >= 0 && estimate.days_until_full < 90 && (
            <Badge variant="destructive">Knapp!</Badge>
          )}
        </div>
        <Separator />
        <div className="grid grid-cols-2 gap-1 text-sm">
          <span className="text-muted-foreground">Ø Mails/Tag</span>
          <span className="font-semibold">{estimate.avg_mails_per_day.toFixed(1)}</span>
          <span className="text-muted-foreground">Ø Mail-Größe</span>
          <span>{formatBytes(estimate.avg_mail_bytes)}</span>
          <span className="text-muted-foreground">Archiv-Alter</span>
          <span>{estimate.archive_age_days} Tage</span>
          <span className="text-muted-foreground">Partition voll in</span>
          <span className={estimate.days_until_full >= 0 && estimate.days_until_full < 90 ? "font-semibold text-destructive" : "font-semibold"}>
            {formatDaysUntilFull(estimate.days_until_full)}
          </span>
        </div>
      </CardContent>
    </Card>
  );
}

interface DashboardTabProps {
  isSuperAdmin: boolean;
  smtpStatus: SMTPStatus | null;
  storageStats: StorageStats | null;
  systemStats: SystemStats | null;
  timeseries: TimeseriesPoint[];
  apiOnline: boolean | null;
  dashLoading: boolean;
  dashRefreshed: Date | null;
  countdown: number;
  users: User[];
  usersLoading: boolean;
  onRefresh: () => void;
}

export function DashboardTab({
  isSuperAdmin,
  smtpStatus,
  storageStats,
  systemStats,
  timeseries,
  apiOnline,
  dashLoading,
  dashRefreshed,
  countdown,
  users,
  usersLoading,
  onRefresh,
}: DashboardTabProps) {
  return (
    <>
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Systemstatus</h2>
        <div className="flex items-center gap-3">
          {dashRefreshed && (
            <span className="text-xs text-muted-foreground">
              {dashRefreshed.toLocaleTimeString("de-DE")} · nächste Aktualisierung in {countdown}s
            </span>
          )}
          <Button variant="outline" size="sm" onClick={onRefresh} disabled={dashLoading}>
            {dashLoading ? "..." : "Jetzt aktualisieren"}
          </Button>
        </div>
      </div>

      {dashLoading ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <Skeleton key={i} className="h-36 w-full rounded-lg" />
          ))}
        </div>
      ) : (
        <>
          {/* Status-Kacheln */}
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">

            {/* API + Uptime */}
            <Card>
              <CardContent className="pt-6 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">REST API</span>
                  <Badge variant={apiOnline ? "default" : "destructive"}>
                    {apiOnline ? "Online" : "Offline"}
                  </Badge>
                </div>
                <Separator />
                <div className="grid grid-cols-2 gap-1 text-sm">
                  <span className="text-muted-foreground">Adresse</span>
                  <span className="font-mono">:8080</span>
                  <span className="text-muted-foreground">Protokoll</span>
                  <span>HTTP</span>
                  {systemStats?.uptime && (
                    <>
                      <span className="text-muted-foreground">System-Uptime</span>
                      <span>{formatUptime(systemStats.uptime.seconds)}</span>
                    </>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* SMTP — superadmin: globaler Daemon; domain_admin: nur eigene Domain-Statistik */}
            {isSuperAdmin ? (
              <>
                <Card>
                  <CardContent className="pt-6 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-muted-foreground">SMTP-Daemon</span>
                      <Badge variant={smtpStatus?.running ? "default" : "destructive"}>
                        {smtpStatus?.running ? "Aktiv" : smtpStatus?.enabled === false ? "Deaktiviert" : "Gestoppt"}
                      </Badge>
                    </div>
                    <Separator />
                    {smtpStatus ? (
                      <div className="grid grid-cols-2 gap-1 text-sm">
                        <span className="text-muted-foreground">Adresse</span>
                        <span className="font-mono">{smtpStatus.bind}</span>
                        <span className="text-muted-foreground">Domain</span>
                        <span className="font-mono">{smtpStatus.domain || "–"}</span>
                        <span className="text-muted-foreground">TLS</span>
                        <span>{smtpStatus.tls ? "Ja" : "Nein"}</span>
                        <span className="text-muted-foreground">Max. Größe</span>
                        <span>{(smtpStatus.max_size_mb ?? 0) > 0 ? `${smtpStatus.max_size_mb} MB` : "50 MB"}</span>
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground">Nicht erreichbar</p>
                    )}
                  </CardContent>
                </Card>
                <Card>
                  <CardContent className="pt-6 space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-muted-foreground">SMTP Statistik</span>
                      <span className="text-xs text-muted-foreground">seit letztem Start</span>
                    </div>
                    <Separator />
                    {smtpStatus ? (
                      <div className="grid grid-cols-2 gap-1 text-sm">
                        <span className="text-muted-foreground">Empfangen</span>
                        <span className="font-semibold text-green-600">{smtpStatus.received ?? 0}</span>
                        <span className="text-muted-foreground">Abgelehnt</span>
                        <span className="font-semibold text-red-500">{smtpStatus.rejected ?? 0}</span>
                        <span className="text-muted-foreground">Letzte Mail</span>
                        <span className="text-xs">
                          {smtpStatus.last_mail_at
                            ? new Date(smtpStatus.last_mail_at).toLocaleString("de-DE")
                            : "–"}
                        </span>
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground">Keine Daten</p>
                    )}
                  </CardContent>
                </Card>
              </>
            ) : (
              <Card>
                <CardContent className="pt-6 space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-muted-foreground">SMTP – meine Domain(s)</span>
                    <Badge variant="secondary">Tenant</Badge>
                  </div>
                  <Separator />
                  {smtpStatus ? (
                    <div className="grid grid-cols-2 gap-1 text-sm">
                      <span className="text-muted-foreground">Domain(s)</span>
                      <span className="font-mono text-xs">
                        {(smtpStatus.domains?.length ?? 0) > 0 ? smtpStatus.domains!.join(", ") : "–"}
                      </span>
                      <span className="text-muted-foreground">Archivierte Mails</span>
                      <span className="font-semibold">{smtpStatus.total_mails?.toLocaleString("de-DE") ?? "–"}</span>
                      <span className="text-muted-foreground">Speicher</span>
                      <span>{smtpStatus.total_bytes ? formatBytes(smtpStatus.total_bytes) : "–"}</span>
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground">Keine Daten</p>
                  )}
                </CardContent>
              </Card>
            )}

            {/* Archiv-Speicher */}
            <Card>
              <CardContent className="pt-6 space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium text-muted-foreground">Archiv gesamt</span>
                  {storageStats && (
                    <Badge variant="secondary" className="font-mono text-xs">
                      {storageStats.total_mails} Mails
                    </Badge>
                  )}
                </div>
                <Separator />
                {storageStats ? (
                  <div className="grid grid-cols-2 gap-1 text-sm">
                    <span className="text-muted-foreground">E-Mails</span>
                    <span className="font-semibold">{storageStats.total_mails.toLocaleString("de-DE")}</span>
                    <span className="text-muted-foreground">Speicher</span>
                    <span>{formatBytes(storageStats.total_bytes)}</span>
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground">Keine Daten</p>
                )}
              </CardContent>
            </Card>
          </div>

          {/* System Stats: nur für superadmin */}
          {isSuperAdmin && <div className="space-y-4">
            <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Systemauslastung</h3>
            {!systemStats ? (
              <Alert variant="destructive">
                <AlertDescription>
                  Systemdaten konnten nicht abgerufen werden. Prüfe ob der Backend-Dienst läuft und der Endpunkt <code className="font-mono">/api/admin/system/stats</code> erreichbar ist.
                </AlertDescription>
              </Alert>
            ) : (
              <>
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">

                  {/* CPU */}
                  <Card>
                    <CardContent className="pt-6 space-y-3">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-muted-foreground">CPU Load Average</span>
                        <Badge variant="secondary">{systemStats.cpu.num_cpu} CPU(s)</Badge>
                      </div>
                      <Separator />
                      <div className="grid grid-cols-2 gap-1 text-sm">
                        <span className="text-muted-foreground">1 min</span>
                        <span className="font-semibold">{systemStats.cpu.load1.toFixed(2)}</span>
                        <span className="text-muted-foreground">5 min</span>
                        <span className="font-semibold">{systemStats.cpu.load5.toFixed(2)}</span>
                        <span className="text-muted-foreground">15 min</span>
                        <span className="font-semibold">{systemStats.cpu.load15.toFixed(2)}</span>
                      </div>
                    </CardContent>
                  </Card>

                  {/* RAM */}
                  <Card>
                    <CardContent className="pt-6 space-y-3">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-muted-foreground">Arbeitsspeicher</span>
                        <Badge variant={systemStats.ram.used_pct > 90 ? "destructive" : systemStats.ram.used_pct > 70 ? "secondary" : "default"}>
                          {systemStats.ram.used_pct.toFixed(1)}%
                        </Badge>
                      </div>
                      <Separator />
                      <div className="space-y-2">
                        <div className="h-2 w-full rounded-full bg-secondary">
                          <div
                            className={`h-2 rounded-full ${systemStats.ram.used_pct > 90 ? "bg-destructive" : systemStats.ram.used_pct > 70 ? "bg-yellow-500" : "bg-primary"}`}
                            style={{ width: `${Math.min(systemStats.ram.used_pct, 100)}%` }}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-1 text-sm">
                          <span className="text-muted-foreground">Belegt</span>
                          <span>{formatBytes(systemStats.ram.used_bytes)}</span>
                          <span className="text-muted-foreground">Gesamt</span>
                          <span>{formatBytes(systemStats.ram.total_bytes)}</span>
                          <span className="text-muted-foreground">Frei</span>
                          <span>{formatBytes(systemStats.ram.free_bytes)}</span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Archivzeitraum */}
                  <Card>
                    <CardContent className="pt-6 space-y-3">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-muted-foreground">Archivzeitraum</span>
                      </div>
                      <Separator />
                      {systemStats.archive.first_mail || systemStats.archive.last_mail ? (
                        <div className="space-y-2 text-sm">
                          {systemStats.archive.first_mail && (
                            <div>
                              <span className="text-xs text-muted-foreground block">Älteste Mail</span>
                              <span className="font-semibold">{new Date(systemStats.archive.first_mail.date).toLocaleDateString("de-DE")}</span>
                              <span className="block text-muted-foreground truncate">{systemStats.archive.first_mail.from || "–"}</span>
                              <span className="block text-xs truncate">{systemStats.archive.first_mail.subject || "(kein Betreff)"}</span>
                            </div>
                          )}
                          {systemStats.archive.last_mail && (
                            <div className="pt-1 border-t">
                              <span className="text-xs text-muted-foreground block">Neueste Mail</span>
                              <span className="font-semibold">{new Date(systemStats.archive.last_mail.date).toLocaleDateString("de-DE")}</span>
                              <span className="block text-muted-foreground truncate">{systemStats.archive.last_mail.from || "–"}</span>
                              <span className="block text-xs truncate">{systemStats.archive.last_mail.subject || "(kein Betreff)"}</span>
                            </div>
                          )}
                        </div>
                      ) : (
                        <p className="text-sm text-muted-foreground">Archiv leer</p>
                      )}
                    </CardContent>
                  </Card>
                </div>

                {/* Mail-Aktivität + Speicherprognose + Zeitreihe */}
                {(systemStats.activity || systemStats.estimate || timeseries.length > 0) && (
                  <div className="space-y-2">
                    <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Archiv-Statistik</h3>
                    {timeseries.length > 0 && (
                      <MailTimeseriesChart points={timeseries} />
                    )}
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                      {systemStats.activity && <ActivityCard activity={systemStats.activity} />}
                      {systemStats.estimate && <EstimateCard estimate={systemStats.estimate} />}
                    </div>
                  </div>
                )}

                {/* Festplatten */}
                {systemStats.disks.length > 0 && (
                  <div className="space-y-2">
                    <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Festplatten</h3>
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                      {systemStats.disks.map((disk) => (
                        <Card key={disk.mount}>
                          <CardContent className="pt-6 space-y-3">
                            <div className="flex items-center justify-between">
                              <span className="text-sm font-medium font-mono">{disk.mount}</span>
                              <Badge variant={disk.used_pct > 90 ? "destructive" : disk.used_pct > 75 ? "secondary" : "outline"}>
                                {disk.used_pct.toFixed(1)}%
                              </Badge>
                            </div>
                            <div className="h-2 w-full rounded-full bg-secondary">
                              <div
                                className={`h-2 rounded-full ${disk.used_pct > 90 ? "bg-destructive" : disk.used_pct > 75 ? "bg-yellow-500" : "bg-primary"}`}
                                style={{ width: `${Math.min(disk.used_pct, 100)}%` }}
                              />
                            </div>
                            <div className="grid grid-cols-2 gap-1 text-sm">
                              <span className="text-muted-foreground">Belegt</span>
                              <span>{formatBytes(disk.used_bytes)}</span>
                              <span className="text-muted-foreground">Gesamt</span>
                              <span>{formatBytes(disk.total_bytes)}</span>
                              <span className="text-muted-foreground">Frei</span>
                              <span>{formatBytes(disk.free_bytes)}</span>
                              <span className="text-muted-foreground">Dateisystem</span>
                              <span className="font-mono text-xs">{disk.fstype}</span>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  </div>
                )}
              </>
            )}
          </div>}

          {/* IP-Allowlist — nur superadmin */}
          {isSuperAdmin && smtpStatus && (smtpStatus.allowed_ips?.length ?? 0) > 0 && (
            <Card>
              <CardContent className="pt-6 space-y-2">
                <span className="text-sm font-medium text-muted-foreground">SMTP IP-Allowlist</span>
                <Separator />
                <div className="flex flex-wrap gap-2 pt-1">
                  {smtpStatus.allowed_ips!.map((ip) => (
                    <Badge key={ip} variant="outline" className="font-mono">
                      {ip}
                    </Badge>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Vollständigkeits-Check (PROJ-52) — tenant-gescoped, domain_admin+ */}
          <ReconciliationCard />

          {/* Benutzerübersicht */}
          <Card>
            <CardContent className="pt-6 space-y-2">
              <span className="text-sm font-medium text-muted-foreground">Benutzer</span>
              <Separator />
              {usersLoading ? (
                <Skeleton className="h-8 w-full" />
              ) : (
                <div className="flex flex-wrap gap-4 pt-1 text-sm">
                  <span>
                    <span className="font-semibold">{users.filter(u => u.active).length}</span>
                    <span className="text-muted-foreground ml-1">aktiv</span>
                  </span>
                  <span>
                    <span className="font-semibold">{users.filter(u => u.role === "admin").length}</span>
                    <span className="text-muted-foreground ml-1">Admin</span>
                  </span>
                  <span>
                    <span className="font-semibold">{users.filter(u => u.role === "auditor").length}</span>
                    <span className="text-muted-foreground ml-1">Auditor</span>
                  </span>
                  <span>
                    <span className="font-semibold">{users.filter(u => u.role === "user").length}</span>
                    <span className="text-muted-foreground ml-1">User</span>
                  </span>
                </div>
              )}
            </CardContent>
          </Card>

          {!smtpStatus && (
            <Alert variant="destructive">
              <AlertDescription>
                SMTP-Status konnte nicht abgerufen werden. Prüfe ob der Backend-Dienst läuft.
              </AlertDescription>
            </Alert>
          )}
        </>
      )}
    </>
  );
}
