import Link from "next/link";
import { prisma } from "@/lib/db";
import { getUser } from "@/lib/auth";
import { timeAgo, STATUS_META } from "@/lib/constants";
import { TrendChart, ProjectBars, Donut } from "@/components/admin/Charts";
import { StatusBadge, PriorityBadge, ProjectChip } from "@/components/Badges";

export const dynamic = "force-dynamic";

export default async function AdminDashboard() {
  const user = await getUser();

  const [total, open, inProgress, waiting, resolved, closed] = await Promise.all([
    prisma.ticket.count(),
    prisma.ticket.count({ where: { status: "OPEN" } }),
    prisma.ticket.count({ where: { status: "IN_PROGRESS" } }),
    prisma.ticket.count({ where: { status: "WAITING" } }),
    prisma.ticket.count({ where: { status: "RESOLVED" } }),
    prisma.ticket.count({ where: { status: "CLOSED" } }),
  ]);

  const urgentOpen = await prisma.ticket.findMany({
    where: { OR: [{ priority: "URGENT" }, { escalated: true }], status: { notIn: ["RESOLVED", "CLOSED"] } },
    include: { project: true, assignee: { select: { name: true } } },
    orderBy: { createdAt: "asc" },
    take: 6,
  });

  const unassigned = await prisma.ticket.count({
    where: { assigneeId: null, status: { notIn: ["RESOLVED", "CLOSED"] } },
  });

  const projects = await prisma.project.findMany({
    include: { tickets: { select: { status: true } } },
    orderBy: { id: "asc" },
  });

  const since = new Date(Date.now() - 13 * 86400000);
  since.setHours(0, 0, 0, 0);
  const recentCreated = await prisma.ticket.findMany({
    where: { createdAt: { gte: since } },
    select: { createdAt: true },
  });
  const trend = [];
  for (let i = 0; i < 14; i++) {
    const day = new Date(since.getTime() + i * 86400000);
    const next = new Date(day.getTime() + 86400000);
    trend.push({
      day: day.toLocaleDateString("en-US", { month: "short", day: "numeric" }),
      count: recentCreated.filter((t) => t.createdAt >= day && t.createdAt < next).length,
    });
  }

  const responded = await prisma.ticket.findMany({
    where: { firstResponseAt: { not: null } },
    select: { createdAt: true, firstResponseAt: true },
    take: 200,
    orderBy: { id: "desc" },
  });
  const avgFirst =
    responded.length > 0
      ? responded.reduce((s, t) => s + (t.firstResponseAt - t.createdAt) / 3600000, 0) / responded.length
      : null;

  const rated = await prisma.ticket.aggregate({
    _avg: { rating: true },
    _count: { rating: true },
    where: { rating: { not: null } },
  });

  const recent = await prisma.ticket.findMany({
    include: { project: true, assignee: { select: { name: true } } },
    orderBy: { updatedAt: "desc" },
    take: 8,
  });

  const cards = [
    { label: "Open", value: open, icon: "📥", color: "#3b82f6" },
    { label: "In progress", value: inProgress, icon: "🔧", color: "#f59e0b" },
    { label: "Waiting on customer", value: waiting, icon: "⏳", color: "#8b5cf6" },
    { label: "Unassigned", value: unassigned, icon: "🙋", color: "#ef4444" },
    { label: "Avg first response", value: avgFirst != null ? `${avgFirst.toFixed(1)}h` : "—", icon: "⚡", color: "#10b981" },
    { label: "Satisfaction", value: rated._avg.rating ? `${rated._avg.rating.toFixed(1)}★` : "—", icon: "😊", color: "#f97316" },
  ];

  return (
    <main className="max-w-6xl mx-auto space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-extrabold tracking-tight">Good {new Date().getHours() < 12 ? "morning" : new Date().getHours() < 18 ? "afternoon" : "evening"}, {user.name.split(" ")[0]} 👋</h1>
          <p className="text-sm text-muted mt-0.5">Here&apos;s what&apos;s happening across all products.</p>
        </div>
        <Link href="/admin/tickets" className="btn-primary">View all tickets</Link>
      </div>

      {/* stat cards */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4">
        {cards.map((c, i) => (
          <div key={c.label} className="card p-4 animate-rise" style={{ animationDelay: `${i * 50}ms` }}>
            <div className="flex items-center justify-between mb-2">
              <span className="text-xl">{c.icon}</span>
              <span className="w-2 h-2 rounded-full" style={{ background: c.color }} />
            </div>
            <p className="text-2xl font-extrabold">{c.value}</p>
            <p className="text-xs text-muted font-medium mt-0.5">{c.label}</p>
          </div>
        ))}
      </div>

      <div className="grid lg:grid-cols-3 gap-5">
        {/* trend */}
        <div className="card p-5 lg:col-span-2">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-bold">New tickets — last 14 days</h2>
            <span className="text-xs text-muted">{recentCreated.length} total</span>
          </div>
          <TrendChart data={trend} color="#6366f1" height={150} />
        </div>

        {/* status donut */}
        <div className="card p-5">
          <h2 className="font-bold mb-4">By status</h2>
          <Donut
            label={total}
            sub="tickets"
            segments={[
              { label: "Open", value: open, color: STATUS_META.OPEN.color },
              { label: "In progress", value: inProgress, color: STATUS_META.IN_PROGRESS.color },
              { label: "Waiting", value: waiting, color: STATUS_META.WAITING.color },
              { label: "Resolved", value: resolved + closed, color: STATUS_META.RESOLVED.color },
            ]}
          />
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-5">
        {/* per project */}
        <div className="card p-5">
          <h2 className="font-bold mb-4">Tickets by product</h2>
          <ProjectBars
            projects={projects.map((p) => ({
              slug: p.slug,
              name: p.name,
              icon: p.icon,
              color: p.color,
              total: p.tickets.length,
              openCount: p.tickets.filter((t) => !["RESOLVED", "CLOSED"].includes(t.status)).length,
            }))}
          />
        </div>

        {/* escalated / urgent */}
        <div className="card p-5">
          <h2 className="font-bold mb-4">🔥 Needs attention</h2>
          {urgentOpen.length === 0 ? (
            <p className="text-sm text-muted py-6 text-center">Nothing urgent — nice work! 🎉</p>
          ) : (
            <div className="space-y-2.5">
              {urgentOpen.map((t) => (
                <Link key={t.id} href={`/admin/tickets/${t.id}`} className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-surface transition-colors">
                  <span className="text-lg">{t.project.icon}</span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold truncate">{t.subject}</p>
                    <p className="text-xs text-muted">
                      {t.number} · {t.assignee?.name || "Unassigned"} · {timeAgo(t.createdAt)}
                    </p>
                  </div>
                  <PriorityBadge priority={t.priority} />
                </Link>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* recent activity */}
      <div className="card overflow-hidden">
        <div className="px-5 py-4 border-b border-line flex items-center justify-between">
          <h2 className="font-bold">Recent activity</h2>
          <Link href="/admin/tickets" className="text-sm font-semibold" style={{ color: "rgb(var(--accent))" }}>
            See all →
          </Link>
        </div>
        <div className="overflow-x-auto">
          <table className="table-base">
            <thead>
              <tr>
                <th>Ticket</th>
                <th>Product</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Assignee</th>
                <th>Updated</th>
              </tr>
            </thead>
            <tbody>
              {recent.map((t) => (
                <tr key={t.id}>
                  <td>
                    <Link href={`/admin/tickets/${t.id}`} className="block">
                      <span className="font-mono text-xs text-muted">{t.number}</span>
                      <p className="font-semibold">{t.subject}</p>
                    </Link>
                  </td>
                  <td><ProjectChip project={t.project} /></td>
                  <td><StatusBadge status={t.status} /></td>
                  <td><PriorityBadge priority={t.priority} /></td>
                  <td className="text-sm">{t.assignee?.name || <span className="text-muted">—</span>}</td>
                  <td className="text-sm text-muted whitespace-nowrap">{timeAgo(t.updatedAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </main>
  );
}
