import { prisma } from "@/lib/db";
import Link from "next/link";
import {
  FolderGit2,
  Rocket,
  CheckCircle2,
  AlertTriangle,
  GitCommit,
  Activity,
} from "lucide-react";
import { Shell } from "@/components/layout/shell";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "@/components/ui/card";
import { Kpi } from "@/components/ui/kpi";
import { Badge } from "@/components/ui/badge";
import { EmptyState } from "@/components/ui/empty-state";
import { ProjectCard } from "@/components/project-card";
import { LiveRefresh } from "@/components/live-refresh";
import { getDashboardStats } from "@/lib/dashboard";
import { ago, deployToneFor, deployLabelFor } from "@/lib/format";

export const dynamic = "force-dynamic";

export default async function Dashboard() {
  const stats = await getDashboardStats();
  const [projects, recentDeploys, recentCommits] = await Promise.all([
    prisma.project.findMany({
      orderBy: [{ updatedAt: "desc" }],
      take: 12,
      include: { _count: { select: { deploys: true, commits: true } } },
    }),
    prisma.deployHistory.findMany({
      orderBy: { startedAt: "desc" },
      take: 5,
      include: { project: { select: { name: true, id: true } } },
    }),
    prisma.commitLog.findMany({
      orderBy: { timestamp: "desc" },
      take: 8,
      include: { project: { select: { name: true, id: true } } },
    }),
  ]);

  return (
    <Shell>
      <LiveRefresh />

      <div className="space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Tổng quan</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Theo dõi và deploy các dự án self-host trên hạ tầng của bạn.
          </p>
        </div>

        {/* KPIs */}
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          <Kpi
            label="Dự án"
            value={stats.projectCount}
            hint={`${stats.commitCount} commit đã ghi nhận`}
            icon={<FolderGit2 className="h-4 w-4" />}
          />
          <Kpi
            label="Deploy hôm nay"
            value={stats.deploysToday}
            hint={`${stats.deploysTotal} tổng`}
            icon={<Rocket className="h-4 w-4" />}
            tone="info"
          />
          <Kpi
            label="Đang lỗi"
            value={stats.deployFailures}
            hint={
              stats.deployFailures > 0
                ? "Cần xem lại log"
                : "Pipeline đang ổn"
            }
            icon={<AlertTriangle className="h-4 w-4" />}
            tone={stats.deployFailures > 0 ? "danger" : "success"}
          />
          <Kpi
            label="Deploy thành công gần nhất"
            value={stats.lastSuccessAt ? ago(stats.lastSuccessAt) : "—"}
            hint={stats.lastSuccessProject ?? "Chưa có"}
            icon={<CheckCircle2 className="h-4 w-4" />}
            tone="success"
          />
        </div>

        {/* Activity panels */}
        <div className="grid gap-6 lg:grid-cols-2">
          <Card>
            <CardHeader>
              <CardTitle>Deploy gần đây</CardTitle>
              <CardDescription>5 lần build/deploy mới nhất</CardDescription>
            </CardHeader>
            <CardContent className="p-0">
              {recentDeploys.length === 0 ? (
                <div className="px-5 py-8">
                  <EmptyState
                    icon={<Rocket className="h-5 w-5" />}
                    title="Chưa có lần deploy nào"
                    description="Cấu hình máy chủ deploy và bấm Deploy ở dự án bất kỳ để kích hoạt pipeline."
                  />
                </div>
              ) : (
                <ul className="divide-y divide-border/60">
                  {recentDeploys.map((d) => {
                    const tag = d.imageTag.split("/").pop() ?? d.imageTag;
                    return (
                      <li key={d.id}>
                        <Link
                          href={`/projects/${d.project.id}`}
                          className="flex items-center gap-3 px-5 py-3 transition-colors hover:bg-accent/30"
                        >
                          <Badge tone={deployToneFor(d.status)} dot>
                            {deployLabelFor(d.status)}
                          </Badge>
                          <div className="min-w-0 flex-1">
                            <div className="truncate text-sm font-medium text-foreground">
                              {d.project.name}
                            </div>
                            <div className="truncate text-mono text-xs text-muted-foreground">
                              {tag}
                            </div>
                          </div>
                          <span className="hidden shrink-0 text-2xs uppercase tracking-wider text-muted-foreground sm:inline">
                            {ago(d.startedAt)}
                          </span>
                        </Link>
                      </li>
                    );
                  })}
                </ul>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Hoạt động commit</CardTitle>
              <CardDescription>8 commit mới nhất từ webhook</CardDescription>
            </CardHeader>
            <CardContent className="p-0">
              {recentCommits.length === 0 ? (
                <div className="px-5 py-8">
                  <EmptyState
                    icon={<GitCommit className="h-5 w-5" />}
                    title="Chưa có commit"
                    description="Cài git hook ở repo bằng scripts/install-hook.sh để bắt đầu nhận webhook."
                  />
                </div>
              ) : (
                <ul className="divide-y divide-border/60">
                  {recentCommits.map((c) => (
                    <li key={c.id}>
                      <Link
                        href={`/projects/${c.project.id}`}
                        className="flex items-start gap-3 px-5 py-3 transition-colors hover:bg-accent/30"
                      >
                        <GitCommit className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <code className="text-mono text-2xs text-primary">
                              {c.hash.slice(0, 7)}
                            </code>
                            <span className="truncate text-xs font-medium text-foreground/85">
                              {c.project.name}
                            </span>
                          </div>
                          <p className="mt-0.5 truncate text-xs text-muted-foreground">
                            {c.message}
                          </p>
                        </div>
                        <span className="shrink-0 text-2xs uppercase tracking-wider text-muted-foreground">
                          {ago(c.timestamp)}
                        </span>
                      </Link>
                    </li>
                  ))}
                </ul>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Projects grid */}
        <div>
          <div className="mb-4 flex items-end justify-between">
            <div>
              <h2 className="text-lg font-semibold tracking-tight">Dự án</h2>
              <p className="mt-0.5 text-xs text-muted-foreground">
                {projects.length} repo đang theo dõi
              </p>
            </div>
            <span className="flex items-center gap-1.5 text-2xs uppercase tracking-wider text-muted-foreground">
              <Activity className="h-3 w-3 text-success animate-pulse-soft" />
              cập nhật trực tiếp
            </span>
          </div>

          {projects.length === 0 ? (
            <EmptyState
              icon={<FolderGit2 className="h-5 w-5" />}
              title="Chưa có dự án nào"
              description={
                <>
                  Bấm <strong className="text-foreground">Quét lại</strong> ở thanh trên cùng, hoặc
                  thêm thủ công bằng nút <strong className="text-foreground">Thêm dự án</strong>.
                </>
              }
            />
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {projects.map((p) => (
                <ProjectCard
                  key={p.id}
                  id={p.id}
                  name={p.name}
                  branch={p.branch}
                  version={p.version}
                  source={p.source}
                  lastCommitTime={p.lastCommitTime}
                  lastCommitMessage={p.lastCommitMessage}
                  deployedVersion={p.deployedVersion}
                  deployedAt={p.deployedAt}
                  deployCount={p._count.deploys}
                  commitCount={p._count.commits}
                />
              ))}
            </div>
          )}
        </div>
      </div>
    </Shell>
  );
}
