import Link from "next/link";
import { requireStaff } from "@/lib/auth";
import { dashboardData, parseRange } from "@/lib/analytics";
import { taka } from "@/lib/money";
import { fmtDate } from "@/lib/dates";
import { Badge, Card, PageHead, Stat, Table } from "@/components/admin/ui";
import { BarsChart, DailyChart } from "@/components/admin/Charts";
import { can } from "@/lib/permissions";
import { getSettings } from "@/lib/settings";

type SP = { from?: string; to?: string; preset?: string; demo?: string };
const pct = (cur: number, prev: number) => (prev === 0 ? (cur === 0 ? 0 : null) : ((cur - prev) / prev) * 100);

export default async function Dashboard({ searchParams }: { searchParams: Promise<SP> }) {
  const user = await requireStaff();
  if (!can(user.role, "dashboard.view")) return null;
  const sp = await searchParams;
  const range = parseRange(sp);
  const includeDemo = sp.demo !== "hide";
  const [d, settings] = await Promise.all([dashboardData(range, includeDemo), getSettings()]);
  const full = can(user.role, "orders.view");
  const { cur, prev } = d;
  const trackingConnected = !!(settings.analytics.ga4Id || settings.analytics.metaPixelId);
  const preset = sp.preset ?? (sp.from ? "" : "30");
  const q = (extra: Record<string, string>) => `?${new URLSearchParams({ ...(sp.demo ? { demo: sp.demo } : {}), ...extra })}`;

  return (
    <div>
      <PageHead title="Dashboard" sub={`${range.label}, compared with the previous ${Math.round((range.cur.to.getTime() - range.cur.from.getTime()) / 86400000)} days.`}>
        {["7", "30", "90", "365"].map((p) => <Link key={p} href={q({ preset: p })} className={`px-3 h-9 grid place-items-center text-[13px] border ${preset === p ? "bg-ink text-paper border-ink" : "border-sand bg-paper"}`}>{p === "365" ? "1 year" : `${p} days`}</Link>)}
        <form className="flex gap-2 items-center"><input type="date" name="from" defaultValue={sp.from} className="h-9 border border-sand px-2 text-[13px]" aria-label="From date" /><input type="date" name="to" defaultValue={sp.to} className="h-9 border border-sand px-2 text-[13px]" aria-label="To date" /><button className="h-9 px-3 border border-ink text-[13px]">Apply</button></form>
      </PageHead>

      {d.demoCount > 0 && (
        <div className="mb-6 border border-gilt bg-[#FBF3E2] p-4 text-[14px] flex flex-wrap justify-between gap-3" role="status">
          <p><strong className="font-medium">Demo data.</strong> {includeDemo ? `${d.demoCount} of the ${d.demoCount + d.realCount} orders in this range are sample orders created by the seed script (numbers start with DEMO-). They are not real business performance.` : `Sample orders are hidden. ${d.realCount} real orders in this range.`}</p>
          <Link className="underline underline-offset-4" href={q({ ...(sp.preset ? { preset: sp.preset } : {}), ...(sp.from ? { from: sp.from, to: sp.to! } : {}), demo: includeDemo ? "hide" : "show" })}>{includeDemo ? "Hide demo orders" : "Show demo orders"}</Link>
        </div>
      )}
      {d.pendingVerification > 0 && full && <Link href="/admin/orders?pay=SUBMITTED" className="block mb-6 border border-ink bg-paper p-4 text-[14px] hover:bg-linen">{d.pendingVerification} payment{d.pendingVerification > 1 ? "s" : ""} waiting for verification →</Link>}

      <h2 className="font-display text-[24px] mb-3">Sales, cash and what is still owed</h2>
      <p className="text-[13px] text-stone mb-3 max-w-[90ch]">Three separate views of money. <b className="font-medium">Order value</b> counts an order once, when it is placed. <b className="font-medium">Cash</b> counts verified payments when they are verified. <b className="font-medium">Outstanding</b> is what is still unpaid on open orders right now. A deposit and its later balance are each counted once in cash and never added to order value again.</p>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <Stat label="Gross order value" value={taka(cur.grossOrderValue)} delta={pct(cur.grossOrderValue, prev.grossOrderValue)} sub="All orders placed, incl. later cancelled" hint="Sum of order totals (after discounts, including delivery) for orders placed in the range." />
        <Stat label="Net sales" value={taka(cur.netSales)} delta={pct(cur.netSales, prev.netSales)} sub="Placed orders, not cancelled, minus refunds" hint="Gross order value minus cancelled orders minus refunds recorded on remaining orders. Includes delivery fees." />
        <Stat label="Verified cash collected" value={taka(cur.cashCollected)} delta={pct(cur.cashCollected, prev.cashCollected)} sub={`Refunds paid: ${taka(cur.refunds)}`} hint="Payments verified by staff in the range, before refunds." />
        <Stat label="Outstanding balances" value={taka(d.outstandingPrepaid)} sub={`+ ${taka(d.outstandingCod)} to collect on delivery`} hint="Unpaid amount on open, non-cancelled orders as of now." />
        <Stat label="Deposits collected" value={taka(cur.depositsCollected)} sub={`Balances collected: ${taka(cur.balancesCollected)}`} />
        <Stat label="Refunds and cancellations" value={`${cur.cancelled.length} cancelled`} sub={`${taka(cur.cancelledValue)} cancelled value`} />
        <Stat label="Orders" value={String(cur.orderCount)} delta={pct(cur.orderCount, prev.orderCount)} sub={`${cur.liveCount} not cancelled`} />
        <Stat label="Average order value" value={taka(cur.aov)} delta={pct(cur.aov, prev.aov)} sub="Not-cancelled orders" />
      </div>

      <div className="grid lg:grid-cols-3 gap-4 mt-6">
        <Card title="Order value and verified cash by day" className="lg:col-span-2"><DailyChart data={d.days} /></Card>
        <Card title="Sales by category"><BarsChart label="Sales by category" data={d.byCat.map((c) => ({ name: c.slug, value: c.value }))} /></Card>
      </div>

      <div className="grid lg:grid-cols-2 gap-4 mt-4">
        <Card title="Best-selling products" action={<span className="text-[12px] text-stone">by units, orders not cancelled</span>}>
          <Table head={["Product", "Units", "Sales"]} empty={d.best.length ? undefined : "No sales in this range."}>{d.best.map((b) => <tr key={b.name}><td>{b.name}</td><td>{b.qty}</td><td>{taka(b.revenue)}</td></tr>)}</Table>
        </Card>
        <Card title="Pre-order batches" action={<span className="text-[12px] text-stone">capacity = held + confirmed</span>}>
          <Table head={["Batch", "Used", "Closes", "Dispatch"]} empty={d.batchRows.length ? undefined : "No batches."}>
            {d.batchRows.map((b) => {
              const used = b.held + b.committed; const u = b.capacity ? Math.round((used / b.capacity) * 100) : 0;
              const closed = b.manuallyClosed || b.closesAt < new Date();
              return <tr key={b.id}><td><Link href={`/admin/products/${b.productId}`} className="underline underline-offset-4">{b.code}</Link><br /><span className="text-stone text-[12px]">{b.product}</span></td>
                <td><div className="w-24 h-1.5 bg-linen"><div className="h-full bg-gilt" style={{ width: `${Math.min(100, u)}%` }} /></div><span className="text-[12px]">{used}/{b.capacity} ({u}%){b.held ? `, ${b.held} held` : ""}</span></td>
                <td>{closed ? <Badge tone="neutral">Closed</Badge> : fmtDate(b.closesAt)}</td><td className="text-[13px]">{fmtDate(b.dispatchFrom, { year: undefined })} – {fmtDate(b.dispatchTo, { year: undefined })}</td></tr>;
            })}
          </Table>
        </Card>
      </div>

      <div className="grid lg:grid-cols-2 gap-4 mt-4">
        <Card title="Overdue balances" action={<Badge tone={d.overdue.length ? "bad" : "good"}>{d.overdue.length}</Badge>}>
          <Table head={["Order", "Customer", "Owed", "Was due"]} empty={d.overdue.length ? undefined : "No deposit balances are overdue."}>
            {d.overdue.map((o) => <tr key={o.id}><td><Link className="underline underline-offset-4" href={`/admin/orders/${o.id}`}>{o.number}</Link></td><td>{o.customerName}</td><td>{taka(o.total - o.amountPaid)}</td><td>{fmtDate(o.balanceDueAt)}</td></tr>)}
          </Table>
        </Card>
        <Card title="Customers">
          <p className="text-[14px]">{d.customers.total} customers have ordered. <b className="font-medium">{d.customers.repeat}</b> placed more than one order{d.customers.total ? ` (${Math.round((d.customers.repeat / d.customers.total) * 100)}%)` : ""}.</p>
          <p className="text-[12px] text-stone mt-2">Customers are matched by email, across all time, ignoring cancelled orders.</p>
        </Card>
      </div>

      <Card title="Traffic, conversion and checkout funnel" className="mt-4">
        {trackingConnected
          ? <p className="text-[14px]">An analytics ID is saved in Settings, but this dashboard doesn’t read data from it. Use your {settings.analytics.ga4Id ? "Google Analytics" : "Meta Pixel"} account to see sessions and conversion.</p>
          : <div className="text-[14px] text-stone space-y-1"><p><b className="font-medium text-ink">Not connected.</b> Sessions, conversion rate, traffic sources and checkout funnel need real tracking, so nothing is shown here rather than guessing.</p><p>Add a Google Analytics 4 ID or Meta Pixel ID in <Link className="underline underline-offset-4 text-ink" href="/admin/settings">Settings → Analytics</Link> to start collecting on the storefront.</p></div>}
      </Card>
    </div>
  );
}
