import { notFound } from "next/navigation";
import { BarChart } from "@/components/charts/bar-chart";
import { UptimeControls } from "@/components/features/reports/uptime-controls";
import { Card, EmptyState, PageHeader, StatCard } from "@/components/ui";
import { AuthError } from "@/lib/authz/errors";
import { UserError } from "@/lib/actions/result";
import { getUptimeReport } from "@/lib/services/uptime";
import { reportsBase, reportsStart, type ReportsKind } from "./reports-shared";

const first = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v);

/** "Uptime": availability and response time of the website's primary domain, from recorded checks only. */
export async function ReportsUptimeScreen({ kind, searchParams }: { kind: ReportsKind; searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const s = await reportsStart(kind, "Uptime");
  if (s.siteId === null) return s.empty;
  const sp = await searchParams;
  let r, problem = "";
  try { r = await getUptimeReport(s.siteId, { from: first(sp.from), to: first(sp.to) }); } catch (e) { if (e instanceof AuthError) notFound(); if (e instanceof UserError) problem = e.message; else throw e; }
  if (!r) return (<><PageHeader title="Uptime" /><Card><EmptyState title="Choose a valid date range" description={problem} /></Card></>);
  const base = `${reportsBase(kind)}/uptime`;
  return (
    <>
      <PageHeader title="Uptime" description={r.host ? `Checks of https://${r.host}/ · figures come from recorded checks` : "This website has no domain yet"} />
      <UptimeControls siteId={s.siteId} base={base} from={r.from} to={r.to} canCheck={Boolean(r.host) && r.probeable} />
      {!r.host ? <Card className="mb-4"><EmptyState title="No domain" description="Add a domain to this website to start checking it." /></Card> : null}
      {r.host && !r.probeable ? <p role="note" className="mb-4 rounded-md border border-border bg-muted px-3 py-2 text-sm">This domain is not a public address (for example a local or internal name), so it cannot be checked from here.</p> : null}
      <div className="mb-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label="Website uptime" value={r.range.uptimePct === null ? "No checks recorded yet" : `${r.range.uptimePct}%`} />
        <StatCard label="Checks in range" value={r.range.total === 0 ? "None" : `${r.range.up} up · ${r.range.down} down`} />
        <StatCard label="Average response" value={r.range.avgMs === null ? "No checks recorded yet" : `${r.range.avgMs} ms`} />
        <StatCard label="Latest check" value={r.latest ? `${r.latest.ok ? "Up" : "Down"}${r.latest.statusCode ? ` (${r.latest.statusCode})` : ""} · ${r.latest.checkedAt.toISOString().slice(0, 16).replace("T", " ")} UTC` : "No checks recorded yet"} />
      </div>
      <div className="grid gap-4 lg:grid-cols-2">
        <Card className="p-4"><BarChart title="Average response, last 7 days (ms)" data={r.last7.last7Days} /></Card>
        <Card className="p-4"><BarChart title={`Average response since first check, per week (ms)${r.firstCheckAt ? ` · first check ${r.firstCheckAt.toISOString().slice(0, 10)}` : ""}`} data={r.weekly} /></Card>
      </div>
      <p className="mt-4 text-xs text-muted-foreground">Checks run from this server over HTTPS about every few minutes when the uptime job is scheduled (POST /api/cron/uptime). A response below HTTP 400 counts as up. Times are UTC.</p>
    </>
  );
}
