import { Badge } from "@/components/ui/badge";
import { Card, CardBody, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Sparkline } from "@/components/ui/sparkline";
import { DonutChart } from "@/components/ui/charts/donut-chart";
import { BarChart } from "@/components/ui/charts/bar-chart";
import { listActivities } from "@/lib/db/queries/activities";
import {
  activitiesPerDay30j,
  activityTypesTop10,
  activitiesSuperadminVsTenant24h,
} from "@/lib/db/queries/charts";
import { logActivity } from "@/lib/db/audit";
import { getSession } from "@/lib/auth/session";

export const dynamic = "force-dynamic";

const dateTimeFmt = new Intl.DateTimeFormat("fr-FR", {
  day: "2-digit",
  month: "short",
  year: "numeric",
  hour: "2-digit",
  minute: "2-digit",
});

function typeTone(type: string | null): "accent" | "warning" | "success" | "neutral" {
  if (!type) return "neutral";
  if (type.startsWith("superadmin.")) return "accent";
  if (type.includes("error") || type.includes("alert")) return "warning";
  if (type.includes("success") || type.includes("apply")) return "success";
  return "neutral";
}

export default async function ActivitesPage() {
  const session = await getSession();
  let rows: Awaited<ReturnType<typeof listActivities>> = [];
  let daily: Awaited<ReturnType<typeof activitiesPerDay30j>> = [];
  let topTypes: Awaited<ReturnType<typeof activityTypesTop10>> = [];
  let split: Awaited<ReturnType<typeof activitiesSuperadminVsTenant24h>> = [];
  let loadError: string | null = null;
  try {
    [rows, daily, topTypes, split] = await Promise.all([
      listActivities(100),
      activitiesPerDay30j(),
      activityTypesTop10(),
      activitiesSuperadminVsTenant24h(),
    ]);
    void logActivity({
      type: "superadmin.activities_view",
      title: "Vue journal d'activité",
      description: `${rows.length} entrées affichées`,
      user_id: session?.user.id,
    });
  } catch (err) {
    loadError = err instanceof Error ? err.message : "Erreur inconnue";
  }

  const superadminCount =
    split.find((s) => s.scope === "superadmin")?.count ?? 0;
  const tenantCount = split.find((s) => s.scope === "tenant")?.count ?? 0;

  return (
    <div className="px-6 py-6 lg:px-10">
      <header className="mb-6 flex flex-wrap items-baseline justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold">Journal d&apos;activité</h1>
          <p className="text-sm text-muted-foreground">
            Audit cross-tenant des actions administrateurs et système (100 plus
            récentes).
          </p>
        </div>
        {!loadError && (
          <span className="text-xs text-muted-foreground tabular-nums">
            {rows.length} entrée{rows.length > 1 ? "s" : ""}
          </span>
        )}
      </header>

      {loadError && (
        <div className="rounded-md border border-red-200 bg-danger-subtle px-4 py-3 text-sm text-danger">
          Impossible de charger le journal : {loadError}
        </div>
      )}

      {!loadError && (
        <section className="mb-6 grid gap-4 lg:grid-cols-3">
          <Card className="lg:col-span-1">
            <CardHeader>
              <CardTitle>Activité quotidienne — 30 j</CardTitle>
              <CardDescription>
                Volume total d&apos;événements journaliers.
              </CardDescription>
            </CardHeader>
            <CardBody>
              <div className="text-accent">
                <Sparkline
                  data={daily.map((d) => d.count)}
                  width={300}
                  height={64}
                  strokeWidth={1.8}
                />
              </div>
              <p className="mt-2 text-xs text-muted-foreground tabular-nums">
                {daily.reduce((sum, d) => sum + d.count, 0)} événements sur 30 jours
              </p>
            </CardBody>
          </Card>

          <Card className="lg:col-span-1">
            <CardHeader>
              <CardTitle>Top types d&apos;activité (30 j)</CardTitle>
            </CardHeader>
            <CardBody>
              {topTypes.length === 0 ? (
                <p className="text-sm text-muted-foreground">
                  Aucune activité sur les 30 derniers jours.
                </p>
              ) : (
                <BarChart
                  orientation="horizontal"
                  data={topTypes.map((t) => ({
                    label: t.type,
                    values: [t.count],
                  }))}
                  series={[{ name: "Occurrences" }]}
                  showValues
                  legend={false}
                />
              )}
            </CardBody>
          </Card>

          <Card className="lg:col-span-1">
            <CardHeader>
              <CardTitle>Scope d&apos;activité — 24 h</CardTitle>
              <CardDescription>
                Super-admin (cross-tenant) vs scope tenant.
              </CardDescription>
            </CardHeader>
            <CardBody>
              <DonutChart
                segments={[
                  {
                    label: "Super-admin",
                    value: superadminCount,
                    color: "var(--accent)",
                  },
                  {
                    label: "Tenant",
                    value: tenantCount,
                    color: "var(--success)",
                  },
                ]}
                centerValue={String(superadminCount + tenantCount)}
                centerLabel="Total"
              />
            </CardBody>
          </Card>
        </section>
      )}

      {!loadError && rows.length === 0 && (
        <div className="rounded-md border border-border bg-surface px-4 py-8 text-center text-sm text-muted-foreground">
          Aucune activité enregistrée.
        </div>
      )}

      {!loadError && rows.length > 0 && (
        <div className="overflow-hidden rounded-lg border border-border bg-surface">
          <table className="w-full text-sm">
            <thead className="bg-surface-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-4 py-2.5">Quand</th>
                <th className="px-4 py-2.5">Type</th>
                <th className="px-4 py-2.5">Tenant</th>
                <th className="px-4 py-2.5">Auteur</th>
                <th className="px-4 py-2.5">Détails</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {rows.map((a) => (
                <tr key={a.id} className="hover:bg-surface-2/60">
                  <td className="px-4 py-2 align-top text-xs text-muted-foreground tabular-nums whitespace-nowrap">
                    {dateTimeFmt.format(new Date(a.created_at))}
                  </td>
                  <td className="px-4 py-2 align-top">
                    <Badge tone={typeTone(a.type)}>
                      <span className="font-mono text-[10px]">
                        {a.type ?? "?"}
                      </span>
                    </Badge>
                  </td>
                  <td className="px-4 py-2 align-top text-xs">
                    {a.tenant_name ? (
                      <>
                        <div>{a.tenant_name}</div>
                        <div className="font-mono text-[10px] text-muted-foreground">
                          {a.tenant_slug}
                        </div>
                      </>
                    ) : (
                      <span className="text-muted-foreground italic">
                        cross-tenant
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-2 align-top text-xs">
                    {a.user_name?.trim() || (
                      <span className="text-muted-foreground italic">
                        système
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-2 align-top">
                    {a.title && (
                      <div className="text-sm font-medium">{a.title}</div>
                    )}
                    {a.description && (
                      <div className="mt-0.5 text-xs text-muted-foreground break-words">
                        {a.description}
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
