import Link from "next/link";
import { Rocket } from "lucide-react";
import { prisma } from "@/lib/db";
import { Shell } from "@/components/layout/shell";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { CopyText } from "@/components/ui/copy-text";
import { EmptyState } from "@/components/ui/empty-state";
import { LiveRefresh } from "@/components/live-refresh";
import { ago, deployToneFor, deployLabelFor } from "@/lib/format";

export const dynamic = "force-dynamic";

export default async function DeploymentsPage() {
  const [rows, stats, targets] = await Promise.all([
    prisma.deployHistory.findMany({
      orderBy: { startedAt: "desc" },
      take: 50,
      include: {
        project: { select: { id: true, name: true } },
      },
    }),
    prisma.deployHistory.groupBy({
      by: ["status"],
      _count: { _all: true },
    }),
    prisma.deployTarget.findMany({ select: { id: true, name: true } }),
  ]);

  const targetMap = new Map(targets.map((t) => [t.id, t.name]));
  const statMap = Object.fromEntries(stats.map((s) => [s.status, s._count._all]));

  return (
    <Shell>
      <LiveRefresh />
      <div className="space-y-6">
        <div className="flex items-end justify-between gap-4">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight">Lượt deploy</h1>
            <p className="mt-1 text-sm text-muted-foreground">
              Lịch sử build và deploy gần nhất từ tất cả các dự án.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <StatusChip label="Thành công" tone="success" count={statMap.success ?? 0} />
            <StatusChip label="Đang chạy" tone="info" count={(statMap.building ?? 0) + (statMap.deploying ?? 0)} />
            <StatusChip label="Thất bại" tone="danger" count={statMap.failed ?? 0} />
            <StatusChip label="Trong hàng đợi" tone="muted" count={statMap.queued ?? 0} />
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Lịch sử ({rows.length})</CardTitle>
            <CardDescription>50 lượt deploy mới nhất</CardDescription>
          </CardHeader>
          <CardContent className="p-0">
            {rows.length === 0 ? (
              <div className="px-5 py-10">
                <EmptyState
                  icon={<Rocket className="h-5 w-5" />}
                  title="Chưa có lượt deploy"
                  description="Cấu hình máy chủ deploy và bấm Deploy ở dự án bất kỳ để kích hoạt pipeline build → push → compose up."
                />
              </div>
            ) : (
              <ul className="divide-y divide-border/60">
                {rows.map((d) => {
                  const tag = d.imageTag.split("/").pop() ?? d.imageTag;
                  const targetName = d.targetId ? targetMap.get(d.targetId) : null;
                  return (
                    <li key={d.id}>
                      <div className="flex flex-wrap items-center gap-3 px-5 py-3 transition-colors hover:bg-accent/30">
                        <Badge tone={deployToneFor(d.status)} dot>
                          {deployLabelFor(d.status)}
                        </Badge>
                        <Link
                          href={`/projects/${d.project.id}`}
                          className="min-w-0 shrink-0 text-sm font-medium text-foreground hover:text-primary"
                        >
                          {d.project.name}
                        </Link>
                        <CopyText
                          value={d.imageTag}
                          display={tag}
                          truncate
                          className="min-w-0 flex-1"
                        />
                        {targetName && (
                          <span className="shrink-0 rounded-md border border-border bg-surface px-2 py-0.5 text-2xs uppercase tracking-wider text-muted-foreground">
                            {targetName}
                          </span>
                        )}
                        <span className="shrink-0 text-2xs uppercase tracking-wider text-muted-foreground">
                          {ago(d.startedAt)}
                        </span>
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </CardContent>
        </Card>
      </div>
    </Shell>
  );
}

function StatusChip({
  label,
  tone,
  count,
}: {
  label: string;
  tone: "success" | "info" | "danger" | "muted";
  count: number;
}) {
  const toneClass = {
    success: "border-success/30 text-success",
    info: "border-info/30 text-info",
    danger: "border-destructive/30 text-destructive",
    muted: "border-border text-muted-foreground",
  }[tone];

  return (
    <span
      className={`flex items-center gap-2 rounded-md border bg-surface px-2.5 py-1 text-xs font-medium ${toneClass}`}
    >
      {label}
      <span className="rounded-sm bg-background/60 px-1.5 text-mono">{count}</span>
    </span>
  );
}
