import Link from "next/link";
import { redirect } from "next/navigation";
import { TrendingUp, TrendingDown, Wallet, ShoppingCart, Users, Repeat, Clock, Headphones, AlertTriangle } from "lucide-react";
import { requireUser } from "@/lib/auth";
import { analytics } from "@/lib/analytics";
import { all } from "@/lib/db";
import { Gauge, AreaChart, Donut, BarList } from "@/components/charts";
import { PageHead } from "@/components/dash/Shell";
import { Status } from "@/components/ui";
import { money, short, ago } from "@/lib/format";
import { listRecords, accountsWithBalance } from "@/lib/records";
import { readCfg } from "@/lib/cfg";
import { Stats, taka } from "@/components/dash/RecordPage";

export default async function Overview() {
  const u = await requireUser(["admin", "support"]);
  if (u.role !== "admin") redirect("/dashboard/support");
  const a = analytics();
  const inv = listRecords("invoices").filter((x) => x.kind !== "quotation"), ym = new Date().toISOString().slice(0, 7), accts = accountsWithBalance();
  const thisMonth = inv.filter((x) => String(x.issue_date).startsWith(ym)), sum = (r: any[], k = "total") => r.reduce((s, x) => s + Number(x[k] || 0), 0);
  const open = inv.filter((x) => x.status !== "paid" && x.status !== "draft"), overdue = inv.filter((x) => x.status === "overdue");
  const hr = (new Date().getUTCHours() + 6) % 24, hello = hr < 12 ? "Good morning" : hr < 17 ? "Good afternoon" : "Good evening";
  const recent = all<any>("SELECT o.*, u.name customer, p.name product FROM orders o JOIN users u ON u.id=o.user_id JOIN products p ON p.id=o.product_id ORDER BY o.id DESC LIMIT 7");
  const Delta = ({ v }: { v: number }) => <span className={`inline-flex items-center gap-0.5 text-xs font-semibold ${v >= 0 ? "text-emerald-600" : "text-rose-600"}`}>{v >= 0 ? <TrendingUp size={13} /> : <TrendingDown size={13} />}{Math.abs(v)}%</span>;
  return (
    <>
      <div className="mb-6"><h1 className="text-[1.65rem] font-semibold">{hello}, {u.name.split(" ")[0]}</h1><p className="mt-1 text-sm text-slate-500">{readCfg("company").name} · every figure below is computed from your own records.</p></div>
      <Stats items={[["Money across accounts", taka(sum(accts, "balance")), `${accts.length} accounts`], ["Billed this month", taka(sum(thisMonth)), `${inv.length} invoices in total`], ["To collect", taka(sum(open)), overdue.length ? `${overdue.length} overdue` : "Nothing overdue"], ["VAT charged this month", taka(sum(thisMonth) - sum(thisMonth, "amount")), "See VAT & tax"]]} />
      <div className="mb-4 mt-8 flex items-end justify-between"><div><h2 className="font-semibold">Platform — last 30 days</h2><p className="text-sm text-slate-500">Online store, payments and support.</p></div><div className="flex gap-2"><Link href="/dashboard/analytics" className="btn btn-ghost btn-sm">Full analytics</Link><Link href="/dashboard/payments" className="btn btn-primary btn-sm">Review payments {a.pending ? `(${a.pending})` : ""}</Link></div></div>
      {(a.pending > 0 || a.expiringSoon > 0) && <div className="mb-4 flex flex-wrap gap-2">
        {a.pending > 0 && <Link href="/dashboard/payments" className="flex items-center gap-2 rounded-full border border-amber-200 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-800"><AlertTriangle size={15} />{a.pending} payment(s) waiting for approval</Link>}
        {a.expiringSoon > 0 && <Link href="/dashboard/licenses" className="flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-2 text-sm font-medium"><Clock size={15} />{a.expiringSoon} license(s) expire within 7 days</Link>}</div>}

      <div className="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4">
        {[[Wallet, "Revenue", money(a.revenue), a.revenueDelta, "#2563eb"], [ShoppingCart, "Paid orders", String(a.orders), a.ordersDelta, "#06b6d4"], [Repeat, "Est. MRR", money(a.mrr), null, "#7c3aed"], [Users, "Customers", String(a.customers), null, "#10b981", `+${a.newCustomers} new`]].map(([I, k, v, d, c, s]: 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">{d !== null ? <Delta v={d} /> : <span className="text-xs text-slate-400">{s || "recurring"}</span>}</div></div>))}
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-3">
        <div className="card p-5 xl:col-span-2"><div className="mb-1 flex items-center justify-between"><div><h2 className="font-bold">Revenue</h2><p className="text-xs text-slate-400">Paid orders, daily</p></div><b className="text-xl">{money(a.revenue)}</b></div><AreaChart data={a.series} fmt="money" height={240} /></div>
        <div className="card p-5"><h2 className="mb-2 font-bold">Revenue by category</h2>{a.byCategory.length ? <Donut items={a.byCategory} center={short(a.byCategory.reduce((s: number, x: any) => s + x.value, 0))} /> : <p className="py-10 text-center text-sm text-slate-400">No sales yet</p>}</div>
      </div>

      {/* Speedometers */}
      <div className="card mt-4 p-5"><div className="mb-3 flex items-center justify-between"><div><h2 className="font-bold">Performance gauges</h2><p className="text-xs text-slate-400">Needle shows where you stand against your goal</p></div></div>
        <div className="grid grid-cols-2 gap-x-4 gap-y-6 lg:grid-cols-4">
          <Gauge value={a.month} max={a.target} unit="" format="short" label="Revenue vs monthly target" sub={`Target ${money(a.target)}`} />
          <Gauge value={a.successRate} label="Payment success" sub={`${a.pending} pending review`} />
          <Gauge value={Math.min(a.firstReplyMin, 60)} max={60} unit="m" label="First response time" invert sub={a.firstReplyMin ? "average" : "no chats yet"} />
          <Gauge value={a.csat} label="Customer satisfaction" sub={`${a.csatN} ratings`} />
        </div></div>

      <div className="mt-4 grid gap-4 xl:grid-cols-3">
        <div className="card overflow-hidden xl:col-span-2"><div className="flex items-center justify-between p-5 pb-3"><h2 className="font-bold">Latest orders</h2><Link href="/dashboard/orders" className="text-xs font-semibold text-brand">All orders →</Link></div>
          <div className="scroll-x"><table className="tbl min-w-[560px]"><tbody>{recent.map((o) => <tr key={o.id}><td className="font-semibold">{o.number}</td><td>{o.customer}</td><td className="text-slate-500">{o.product}</td><td className="font-semibold">{money(o.amount)}</td><td><Status s={o.status} /></td><td className="text-xs text-slate-400">{ago(o.created_at)}</td></tr>)}</tbody></table></div></div>
        <div className="card p-5"><h2 className="mb-4 font-bold">Top products</h2><BarList items={a.byProduct} fmt="money" /><div className="mt-5 flex items-center gap-3 rounded-2xl bg-slate-50 p-3 text-sm"><Headphones size={18} className="text-brand" /><span><b>{a.openChats}</b> open support chats</span><Link href="/dashboard/support" className="ml-auto text-xs font-semibold text-brand">Open →</Link></div></div>
      </div>
    </>
  );
}
