import Link from "next/link";
import { headers } from "next/headers";
import { Eye, Users, ShoppingCart, Wallet, Activity, AlertTriangle, Layers, LayoutGrid } from "lucide-react";
import { requireUser } from "@/lib/auth";
import { all } from "@/lib/db";
import { parseRange, todayISO } from "@/lib/range";
import { projectStats } from "@/lib/projects";
import { AreaChart, BarList, Gauge, Spark } from "@/components/charts";
import { PageHead } from "@/components/dash/Shell";
import { DateFilter } from "@/components/dash/DateFilter";
import { AddProject } from "@/components/dash/ProjectBits";
import { money, short, ago } from "@/lib/format";

export const metadata = { title: "Projects hub" };
type SP = { d?: string; date?: string; from?: string; to?: string; view?: string };
export default async function Projects({ searchParams }: { searchParams: Promise<SP> }) {
  await requireUser(["admin"]);
  const sp = await searchParams, r = parseRange(sp), view = sp.view === "individual" ? "individual" : "merged";
  const h = await headers(), origin = (process.env.APP_URL || `${h.get("x-forwarded-proto") || "http"}://${h.get("x-forwarded-host") || h.get("host")}`).replace(/\/$/, "");
  const projects = all<any>("SELECT * FROM projects ORDER BY id");
  const ids = projects.map((p) => p.id), m = projectStats(ids, r);
  const keep = { view, ...(sp.d ? {} : {}) } as Record<string, string>;
  const down = projects.filter((p) => p.status === "active" && p.last_check_at && !p.last_ok);
  const Dot = ({ p }: { p: any }) => <span className={`inline-block h-2.5 w-2.5 rounded-full ${p.status === "paused" ? "bg-slate-300" : p.maintenance ? "bg-amber-400" : !p.last_check_at ? "bg-slate-300" : p.last_ok ? "bg-emerald-500" : "bg-rose-500"}`} title={p.status === "paused" ? "Paused" : p.maintenance ? "Maintenance" : p.last_ok ? "Online" : "Down"} />;
  return (
    <>
      <PageHead title="Projects hub" sub={`Super-admin center for every site you run — ${r.label}`}>
        <DateFilter base="/dashboard/projects" sp={sp} keep={keep} max={todayISO()} /><AddProject origin={origin} /></PageHead>
      <div className="mb-5 flex flex-wrap items-center gap-2">
        <div className="flex gap-1 rounded-full bg-white p-1 ring-1 ring-slate-200">{[["merged", "Merged", Layers], ["individual", "Individual", LayoutGrid]].map(([v, l, I]: any) => <Link key={v} href={`/dashboard/projects?${new URLSearchParams({ ...(sp.d ? { d: sp.d } : {}), ...(sp.date ? { date: sp.date } : {}), ...(sp.from ? { from: sp.from, to: sp.to || "" } : {}), view: v })}`} className={`flex items-center gap-1.5 rounded-full px-4 py-1.5 text-xs font-semibold ${view === v ? "bg-brand text-white" : "text-slate-500"}`}><I size={13} />{l}</Link>)}</div>
        <span className="text-sm text-slate-500">{projects.length} project{projects.length === 1 ? "" : "s"} · {projects.filter((p) => p.status === "active").length} active</span>
        {down.length > 0 && <span className="flex items-center gap-1.5 rounded-full border border-rose-200 bg-rose-50 px-3 py-1 text-xs font-semibold text-rose-700"><AlertTriangle size={13} />{down.length} down: {down.map((d) => d.name).join(", ")}</span>}</div>

      {projects.length === 0 ? <div className="card p-14 text-center"><Layers className="mx-auto text-brand" size={36} /><h2 className="mt-3 text-xl font-bold">Connect your first project</h2><p className="mx-auto mt-1 max-w-md text-sm text-slate-500">Add any domain, subdomain or URL. You’ll get live uptime monitoring immediately and a one-line snippet for traffic, orders and error analytics.</p><div className="mt-5 flex justify-center"><AddProject origin={origin} /></div></div> : view === "merged" ? (<>
        <div className="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-5">
          {[[Wallet, "Revenue", money(m.revenue), m.revenueDelta, "#2563eb"], [Eye, "Pageviews", short(m.views), m.viewsDelta, "#06b6d4"], [Users, "Visitors", short(m.visitors), null, "#7c3aed"], [ShoppingCart, "Orders", String(m.orders), null, "#f59e0b"], [Activity, "Uptime", `${m.uptime}%`, null, "#10b981"]].map(([I, k, v, dl, c]: any) => (
            <div key={k} className="card stat"><div className="flex items-center justify-between"><span className="k">{k}</span><span className="grid h-8 w-8 place-items-center rounded-xl text-white" style={{ background: c }}><I size={15} /></span></div><div className="v">{v}</div><div className="mt-0.5 h-4 text-xs font-semibold">{dl !== null ? <span className={dl >= 0 ? "text-emerald-600" : "text-rose-600"}>{dl >= 0 ? "▲" : "▼"} {Math.abs(dl)}% vs previous</span> : <span className="text-slate-400">all projects</span>}</div></div>))}</div>
        <div className="mt-4 grid gap-4 xl:grid-cols-2">
          <div className="card p-5"><h2 className="font-bold">Traffic — merged</h2><p className="mb-1 text-xs text-slate-400">{r.single ? "Hourly" : "Pageviews"} across all projects</p><AreaChart data={m.viewsSeries} fmt="views" color="#06b6d4" /></div>
          <div className="card p-5"><h2 className="font-bold">Revenue — merged</h2><p className="mb-1 text-xs text-slate-400">Orders reported by connected sites</p><AreaChart data={m.revenueSeries} fmt="money" /></div></div>
        <div className="card mt-4 p-5"><h2 className="mb-4 font-bold">Fleet health</h2><div className="grid grid-cols-2 gap-x-4 gap-y-6 lg:grid-cols-4">
          <Gauge value={m.uptime} label="Average uptime" sub={`${m.checks} checks`} />
          <Gauge value={Math.min(m.latency, 2000)} max={2000} unit="ms" invert label="Avg response time" />
          <Gauge value={Math.min(m.conv * 10, 100)} unit="%" text={String(m.conv)} label="Visitor → order" sub="conversion ×10 scale" />
          <Gauge value={m.views ? Math.max(0, 100 - Math.round((m.errors / m.views) * 1000)) : 100} label="Error-free health" sub={`${m.errors} errors`} /></div></div>
        <div className="mt-4 grid gap-4 xl:grid-cols-3">
          <div className="card p-5"><h2 className="mb-4 font-bold">Revenue by project</h2><BarList items={m.rows.map((x: any) => ({ label: x.name, value: x.revenue }))} fmt="money" /></div>
          <div className="card p-5"><h2 className="mb-4 font-bold">Traffic by project</h2><BarList items={m.rows.map((x: any) => ({ label: x.name, value: x.views }))} fmt="short" /></div>
          <div className="card p-5"><h2 className="mb-4 font-bold">Top pages (all)</h2>{m.topPaths.length ? <BarList items={m.topPaths} fmt="short" /> : <p className="text-sm text-slate-400">No pageviews in this period</p>}</div></div>
        <div className="card mt-4 overflow-hidden"><div className="p-5 pb-2"><h2 className="font-bold">All projects</h2></div><div className="scroll-x"><table className="tbl min-w-[760px]"><thead><tr><th>Project</th><th>Status</th><th>Uptime</th><th>Latency</th><th>Views</th><th>Revenue</th><th>Errors</th><th /></tr></thead><tbody>
          {m.rows.map((x: any) => { const p = projects.find((q) => q.id === x.id); return <tr key={x.id}><td><div className="flex items-center gap-3"><span className="h-8 w-1.5 rounded-full" style={{ background: x.color }} /><div><Link href={`/dashboard/projects/${x.id}`} className="font-semibold hover:text-brand">{x.name}</Link><div className="text-xs text-slate-400">{x.host}</div></div></div></td>
            <td><span className="flex items-center gap-2 text-xs"><Dot p={p} />{p.status === "paused" ? "Paused" : p.maintenance ? "Maintenance" : !p.last_check_at ? "Pending" : p.last_ok ? "Online" : "Down"}</span></td><td>{x.uptime ?? "—"}{x.uptime != null && "%"}</td><td>{x.last_ms ? `${x.last_ms} ms` : "—"}</td><td>{short(x.views)}</td><td className="font-semibold">{money(x.revenue)}</td><td>{x.errors}</td><td className="text-right"><Link className="btn btn-ghost btn-sm" href={`/dashboard/projects/${x.id}`}>Open</Link></td></tr>; })}</tbody></table></div></div></>) : (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{projects.map((p) => { const s = projectStats([p.id], r); return (
          <Link key={p.id} href={`/dashboard/projects/${p.id}`} className="card card-hover block p-5">
            <div className="flex items-start justify-between gap-2"><div className="flex items-center gap-3"><span className="h-10 w-1.5 rounded-full" style={{ background: p.color }} /><div className="min-w-0"><div className="truncate font-bold">{p.name}</div><div className="truncate text-xs text-slate-400">{p.host} · {p.kind}</div></div></div><span className="flex items-center gap-1.5 text-xs font-medium text-slate-500"><Dot p={p} />{p.last_check_at ? ago(p.last_check_at) : "—"}</span></div>
            <div className="mt-4 grid grid-cols-3 gap-2 text-center">{[["Views", short(s.views)], ["Orders", String(s.orders)], ["Revenue", short(s.revenue)]].map(([k, v]) => <div key={k} className="rounded-xl bg-slate-50 py-2"><div className="text-[10px] font-semibold uppercase tracking-wider text-slate-400">{k}</div><div className="font-bold">{v}</div></div>)}</div>
            <div className="mt-4 flex items-center justify-between"><Spark values={s.viewsSeries.map((x) => x.value)} color={p.color} w={150} h={36} /><div className="text-right text-xs"><div className="font-bold">{s.uptime}%</div><div className="text-slate-400">uptime</div></div></div>
          </Link>); })}</div>)}
    </>
  );
}
