import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import {
  AlertTriangle,
  ArrowLeft,
  Baby,
  CheckCircle2,
  Clock,
  Lock,
  MailCheck,
  MailWarning,
  ShieldAlert,
  Users,
} from "lucide-react";
import { UserRole } from "@prisma/client";

import { requireRole } from "@/lib/auth-utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  getKitaDiagnostics,
  recordKitaDiagnosticView,
  roleOrder,
} from "../../_lib/data";
import { KitaDeleteDialog } from "../../_components/kita-delete-dialog";
import { UserSupportActions } from "../../_components/user-support-actions";

type PageProps = {
  params: Promise<{ kitaId: string }>;
};

export const metadata: Metadata = {
  title: "Kita-Diagnose · Kita-Planer",
};

function formatDate(date: Date | null) {
  if (!date) return "Nie";
  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(date);
}

function isLocked(lockedUntil: Date | null) {
  return !!lockedUntil && lockedUntil > new Date();
}

export default async function KitaDiagnosticsPage({ params }: PageProps) {
  const [{ kitaId }, session] = await Promise.all([
    params,
    requireRole([UserRole.SUPERADMIN]),
  ]);

  const diagnostics = await getKitaDiagnostics(kitaId);
  if (!diagnostics) {
    notFound();
  }

  await recordKitaDiagnosticView({
    actorUserId: session.user.id,
    actorEmail: session.user.email ?? session.user.name ?? "Unbekannter Superadmin",
    kitaId: diagnostics.kita.id,
    kitaName: diagnostics.kita.name,
    kitaSlug: diagnostics.kita.slug,
  });

  const issueCards = [
    {
      label: "Gesperrte Konten",
      value: diagnostics.diagnostics.lockedUsers,
      icon: Lock,
    },
    {
      label: "Fehlender Consent",
      value: diagnostics.diagnostics.missingConsent,
      icon: ShieldAlert,
    },
    {
      label: "Unverifizierte E-Mails",
      value: diagnostics.diagnostics.unverifiedUsers,
      icon: MailWarning,
    },
    {
      label: "Familien ohne Benutzer",
      value: diagnostics.diagnostics.familiesWithoutUsers,
      icon: Users,
    },
  ];

  return (
    <div className="px-8 py-8">
      <div className="mb-7 flex flex-wrap items-start justify-between gap-4">
        <div>
          <Button asChild variant="ghost" className="-ml-3 mb-3">
            <Link href="/admin">
              <ArrowLeft className="h-4 w-4" />
              Zur Kita-Übersicht
            </Link>
          </Button>
          <h1 className="text-2xl font-semibold tracking-tight">
            {diagnostics.kita.name}
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            {diagnostics.kita.slug} · angelegt am{" "}
            {formatDate(diagnostics.kita.createdAt)}
          </p>
        </div>
        <KitaDeleteDialog
          kitaId={diagnostics.kita.id}
          kitaName={diagnostics.kita.name}
          counts={diagnostics.counts}
        />
      </div>

      <div className="mb-6 grid gap-4 md:grid-cols-4">
        <MetricCard
          icon={Users}
          label="Benutzer"
          value={diagnostics.counts.users}
          description={`${diagnostics.counts.families} Familien`}
        />
        <MetricCard
          icon={Baby}
          label="Aktive Kinder"
          value={diagnostics.counts.activeChildren}
          description={`${diagnostics.counts.inactiveChildren} inaktiv`}
        />
        <MetricCard
          icon={Clock}
          label="Termine"
          value={diagnostics.counts.termine}
          description={`${diagnostics.counts.absences} Abwesenheiten`}
        />
        <MetricCard
          icon={MailCheck}
          label="Offene Einladungen"
          value={diagnostics.counts.openInvitations}
          description={`${diagnostics.counts.expiredPendingInvitations} abgelaufen`}
          attention={diagnostics.counts.openInvitations > 0}
        />
      </div>

      <div className="mb-6 grid gap-4 md:grid-cols-4">
        {issueCards.map(({ label, value, icon: Icon }) => (
          <Card
            key={label}
            className={value > 0 ? "border-amber-200 bg-amber-50/70" : ""}
          >
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardDescription>{label}</CardDescription>
                <Icon className="h-4 w-4 text-muted-foreground" />
              </div>
              <CardTitle className="text-3xl">{value}</CardTitle>
            </CardHeader>
          </Card>
        ))}
      </div>

      <div className="mb-6 grid gap-4 lg:grid-cols-[1fr_1.4fr]">
        <Card>
          <CardHeader>
            <CardTitle as="h2" className="text-xl">
              Rollenverteilung
            </CardTitle>
            <CardDescription>
              Nur tenant-gebundene Benutzer dieser Kita.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              {roleOrder.map((role) => (
                <Badge key={role} variant="secondary">
                  {role}: {diagnostics.roleCounts[role]}
                </Badge>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle as="h2" className="text-xl">
              Modulstatus
            </CardTitle>
            <CardDescription>
              V1 zeigt Module nur read-only, keine Konfigurationsänderungen.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              <ModuleBadge label="Notdienst" enabled={diagnostics.kita.modules.notdienst} />
              <ModuleBadge label="Termine" enabled={diagnostics.kita.modules.termine} />
              <ModuleBadge
                label="Adressbuch"
                enabled={diagnostics.kita.modules.adressbuch}
              />
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle as="h2" className="text-xl">
            Benutzer
          </CardTitle>
          <CardDescription>
            Support-Aktionen sind auf Löschen, Sperren, Entsperren und
            Fehlversuche zurücksetzen begrenzt.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Benutzer</TableHead>
                <TableHead>Rolle / Familie</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Login</TableHead>
                <TableHead className="text-right">Aktionen</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {diagnostics.users.map((user) => {
                const userIsLocked = isLocked(user.lockedUntil);
                const userName = `${user.firstName} ${user.lastName}`.trim();
                return (
                  <TableRow key={user.id}>
                    <TableCell>
                      <div className="font-medium">{userName}</div>
                      <div className="text-xs text-muted-foreground">
                        {user.email}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1">
                        <Badge variant="secondary">{user.role}</Badge>
                        <span className="text-xs text-muted-foreground">
                          {user.familyName ?? "Keine Familie"}
                        </span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1.5">
                        {userIsLocked ? (
                          <Badge variant="destructive">
                            <Lock className="mr-1 h-3 w-3" />
                            Gesperrt
                          </Badge>
                        ) : (
                          <Badge variant="success">
                            <CheckCircle2 className="mr-1 h-3 w-3" />
                            Aktiv
                          </Badge>
                        )}
                        {!user.emailVerifiedAt && (
                          <Badge variant="warning">E-Mail offen</Badge>
                        )}
                        {!user.privacyPolicyAcceptedAt && (
                          <Badge variant="warning">Consent fehlt</Badge>
                        )}
                        {user.failedLoginAttempts > 0 && (
                          <Badge variant="outline">
                            {user.failedLoginAttempts} Fehlversuche
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1 text-sm">
                        <div>{formatDate(user.lastLoginAt)}</div>
                        {userIsLocked && (
                          <div className="text-xs text-muted-foreground">
                            bis {formatDate(user.lockedUntil)}
                          </div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      <UserSupportActions
                        user={{
                          id: user.id,
                          email: user.email,
                          name: userName,
                          isLocked: userIsLocked,
                          failedLoginAttempts: user.failedLoginAttempts,
                        }}
                      />
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}

function MetricCard({
  icon: Icon,
  label,
  value,
  description,
  attention = false,
}: {
  icon: typeof Users;
  label: string;
  value: number;
  description: string;
  attention?: boolean;
}) {
  return (
    <Card className={attention ? "border-amber-200 bg-amber-50/70" : ""}>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardDescription>{label}</CardDescription>
          <Icon className="h-4 w-4 text-muted-foreground" />
        </div>
        <CardTitle className="text-3xl">{value}</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="text-xs text-muted-foreground">{description}</p>
      </CardContent>
    </Card>
  );
}

function ModuleBadge({ label, enabled }: { label: string; enabled: boolean }) {
  return (
    <Badge variant={enabled ? "success" : "outline"}>
      {enabled ? (
        <CheckCircle2 className="mr-1 h-3 w-3" />
      ) : (
        <AlertTriangle className="mr-1 h-3 w-3" />
      )}
      {label}: {enabled ? "aktiv" : "inaktiv"}
    </Badge>
  );
}

