import Link from "next/link";
import { and, asc, desc, eq, gte, isNull, lte, sql } from "drizzle-orm";
import { AlertTriangle, ArrowRight, ArrowUpRight, CalendarCheck, Clock, Inbox, Plus, Sparkles, Target, TrendingUp, UserPlus, Users } from "lucide-react";
import { schema } from "@/db";
import { requireCtx } from "@/lib/auth";
import { dailyTrend, funnel, kpis, parseFilters } from "@/lib/services/analytics";
import { formatMoney, formatMoneyShort, fullName, timeAgo } from "@/lib/util";
import { isScopedToOwn } from "@/lib/rbac";
import { industryOf } from "@/lib/industry";
import { defaultLayout, resolveLayout, type WidgetId } from "@/lib/dashboard";
import { FunnelBars, TrendChart, WonLostBars } from "@/components/charts";
import { RangePicker } from "@/components/range-picker";
import { DashboardGrid, RecentDeals, type DealRow } from "@/components/dashboard-grid";
import { Badge, Card, Empty } from "@/components/ui";

export const metadata = { title: "Dashboard" };

export default async function Dashboard({ searchParams }: { searchParams: Promise<Record<string, string>> }) {
  const ctx = await requireCtx();
  const sp = await searchParams;
  const f = parseFilters(sp);
  if (ctx.perms.reports === "V:own" && ctx.user) f.rep = ctx.user.id;
  const ws = ctx.workspace;
  const cur = ws.currency;
  const ind = industryOf(ws.settings);
  const prev = { ...f, from: new Date(f.from.getTime() - (f.to.getTime() - f.from.getTime())), to: f.from };
  const own = isScopedToOwn(ctx.perms, "contacts") && ctx.user ? ctx.user.id : null;
  const D = schema.deals;
  const dealScope = and(eq(D.workspaceId, ws.id), own ? eq(D.ownerId, own) : undefined);
  const sixMonthsAgo = new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1);
  const qStart = new Date(new Date().getFullYear(), Math.floor(new Date().getMonth() / 3) * 3, 1);

  const [k, kPrev, fun, trend, tasks, anomalies, recent, membership, pipeline] = await Promise.all([
    kpis(ctx, f), kpis(ctx, prev), funnel(ctx, f), dailyTrend(ctx, f),
    ctx.db.select({ a: schema.activities, c: { id: schema.contacts.id, firstName: schema.contacts.firstName, lastName: schema.contacts.lastName } }).from(schema.activities).leftJoin(schema.contacts, eq(schema.contacts.id, schema.activities.contactId))
      .where(and(eq(schema.activities.workspaceId, ws.id), isNull(schema.activities.completedAt), lte(schema.activities.dueAt, new Date(Date.now() + 86400000)), ctx.user ? eq(schema.activities.userId, ctx.user.id) : undefined)).orderBy(asc(schema.activities.dueAt)).limit(6),
    ctx.db.select().from(schema.anomalies).where(and(eq(schema.anomalies.workspaceId, ws.id), isNull(schema.anomalies.acknowledgedAt))).orderBy(desc(schema.anomalies.createdAt)).limit(4),
    ctx.db.select().from(schema.contacts).where(and(eq(schema.contacts.workspaceId, ws.id), isNull(schema.contacts.deletedAt), own ? eq(schema.contacts.ownerId, own) : undefined)).orderBy(desc(schema.contacts.createdAt)).limit(6),
    ctx.user ? ctx.db.query.memberships.findFirst({ where: and(eq(schema.memberships.workspaceId, ws.id), eq(schema.memberships.userId, ctx.user.id)) }) : null,
    ctx.db.query.pipelines.findFirst({ where: and(eq(schema.pipelines.workspaceId, ws.id), eq(schema.pipelines.isDefault, true)) }),
  ]);
  const [wonNow, wonPrev, openByStage, monthly, quarterWon, recentDeals, upcomingVisits, inboxStats] = await Promise.all([
    ctx.db.select({ n: sql<number>`count(*)::int`, v: sql<number>`coalesce(sum(${D.value}),0)::bigint` }).from(D).where(and(dealScope, gte(D.wonAt, f.from), lte(D.wonAt, f.to))),
    ctx.db.select({ n: sql<number>`count(*)::int`, v: sql<number>`coalesce(sum(${D.value}),0)::bigint`, lost: sql<number>`0` }).from(D).where(and(dealScope, gte(D.wonAt, prev.from), lte(D.wonAt, prev.to))),
    ctx.db.select({ stage: D.stageId, n: sql<number>`count(*)::int`, v: sql<number>`coalesce(sum(${D.value}),0)::bigint` }).from(D).where(and(dealScope, isNull(D.wonAt), isNull(D.lostAt), pipeline ? eq(D.pipelineId, pipeline.id) : undefined)).groupBy(D.stageId),
    ctx.db.select({ m: sql<string>`to_char(coalesce(${D.wonAt}, ${D.lostAt}), 'YYYY-MM')`, won: sql<number>`count(*) FILTER (WHERE ${D.wonAt} IS NOT NULL)::int`, lost: sql<number>`count(*) FILTER (WHERE ${D.lostAt} IS NOT NULL AND ${D.wonAt} IS NULL)::int` }).from(D)
      .where(and(dealScope, sql`coalesce(${D.wonAt}, ${D.lostAt}) >= ${sixMonthsAgo}`)).groupBy(sql`1`),
    ctx.db.select({ v: sql<number>`coalesce(sum(${D.value}),0)::bigint` }).from(D).where(and(dealScope, gte(D.wonAt, qStart))),
    ctx.db.select({ d: D, c: { id: schema.contacts.id, firstName: schema.contacts.firstName, lastName: schema.contacts.lastName } }).from(D).innerJoin(schema.contacts, eq(schema.contacts.id, D.contactId)).where(dealScope).orderBy(desc(D.updatedAt)).limit(25),
    ctx.db.select({ n: sql<number>`count(*)::int` }).from(schema.activities).where(and(eq(schema.activities.workspaceId, ws.id), eq(schema.activities.type, "visit"), isNull(schema.activities.completedAt), gte(schema.activities.dueAt, new Date()), lte(schema.activities.dueAt, new Date(Date.now() + 7 * 86400000)))),
    ctx.db.select({ open: sql<number>`count(*) FILTER (WHERE status IN ('open','pending'))::int`, unanswered: sql<number>`count(*) FILTER (WHERE status IN ('open','pending') AND first_response_at IS NULL AND last_inbound_at IS NOT NULL)::int`, breached: sql<number>`count(*) FILTER (WHERE sla_breached_at IS NOT NULL AND first_response_at IS NULL AND status IN ('open','pending'))::int` }).from(schema.conversations).where(eq(schema.conversations.workspaceId, ws.id)),
  ]);
  const [closed] = await ctx.db.select({ won: sql<number>`count(*) FILTER (WHERE ${D.wonAt} IS NOT NULL)::int`, lost: sql<number>`count(*) FILTER (WHERE ${D.lostAt} IS NOT NULL AND ${D.wonAt} IS NULL)::int` }).from(D)
    .where(and(dealScope, sql`coalesce(${D.wonAt}, ${D.lostAt}) BETWEEN ${f.from} AND ${f.to}`));

  const delta = (a: number, b: number) => (b ? ((a - b) / b) * 100 : null);
  const won = { n: wonNow[0]?.n ?? 0, v: Number(wonNow[0]?.v ?? 0) };
  const wonDelta = delta(won.v, Number(wonPrev[0]?.v ?? 0));
  const leadDelta = delta(k.newLeads, kPrev.newLeads);
  const stages = (pipeline?.stages ?? []).filter((s) => s.kind === "open" || !s.kind).sort((a, b) => a.order - b.order);
  const stageName = (id: string) => pipeline?.stages.find((s) => s.id === id)?.name ?? id;
  const openTotal = openByStage.reduce((s, r) => s + Number(r.v), 0);
  const openCount = openByStage.reduce((s, r) => s + r.n, 0);
  const winRate = closed && closed.won + closed.lost ? (closed.won / (closed.won + closed.lost)) * 100 : null;
  const target = Number(ws.settings?.salesTargetQuarterly ?? 0) || Math.max(Number(quarterWon[0]?.v ?? 0) * 1.25, 1);
  const targetPct = Math.min(100, (Number(quarterWon[0]?.v ?? 0) / target) * 100);
  const months = Array.from({ length: 6 }, (_, i) => { const d = new Date(sixMonthsAgo.getFullYear(), sixMonthsAgo.getMonth() + i, 1); const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; const r = monthly.find((m) => m.m === key); return { month: d.toLocaleString("en", { month: "short" }), won: r?.won ?? 0, lost: r?.lost ?? 0 }; });
  const hour = Number(new Intl.DateTimeFormat("en-GB", { hour: "numeric", hour12: false, timeZone: ws.timezone }).format(new Date()));
  const greeting = hour < 12 ? "Good morning" : hour < 17 ? "Good afternoon" : "Good evening";
  const days = Math.round((f.to.getTime() - f.from.getTime()) / 86400000);
  const deals: DealRow[] = recentDeals.map(({ d, c }) => ({
    id: d.id, ref: `DL-${d.id.slice(0, 4).toUpperCase()}`, title: d.title, contact: fullName(c as never), contactId: c.id, value: formatMoneyShort(Number(d.value), d.currency),
    stage: d.wonAt ? "Won" : d.lostAt ? "Lost" : stageName(d.stageId), tone: d.wonAt ? "green" : d.lostAt ? "red" : "blue", updated: timeAgo(d.updatedAt),
  }));
  const topStages = [...openByStage].sort((a, b) => Number(b.v) - Number(a.v)).slice(0, 3);
  const focusStages = stages.filter((s) => s.id !== "new").slice(0, 5);

  const widgets: Partial<Record<WidgetId, React.ReactNode>> = {
    pipeline_value: (
      <section className="card lift h-full p-5">
        <div className="flex items-center justify-between text-[13px] font-medium text-ink-2">Pipeline value<span className="rounded-full bg-white/70 px-2 py-0.5 text-[11.5px] font-semibold text-ink-2 dark:bg-white/10">{cur}</span></div>
        <div className="mt-2 font-display text-[34px] font-extrabold leading-tight tracking-tight">{formatMoney(openTotal, cur)}</div>
        <div className="mt-1 text-[12px] text-ink-3">{openCount} open deal{openCount === 1 ? "" : "s"} · {pipeline?.name ?? "pipeline"}</div>
        <div className="mt-4 grid grid-cols-2 gap-2">
          <Link href="/pipeline?new=1" className="flex h-10 items-center justify-center gap-1.5 rounded-[12px] bg-ink text-[13px] font-semibold text-white hover:opacity-90 dark:bg-white dark:text-ink"><Plus className="h-4 w-4" />New deal</Link>
          <Link href="/contacts?new=1" className="flex h-10 items-center justify-center gap-1.5 rounded-[12px] border border-white/80 bg-white/70 text-[13px] font-semibold hover:bg-white dark:border-white/10 dark:bg-white/5"><UserPlus className="h-4 w-4" />Add lead</Link>
        </div>
        <div className="mt-4 rounded-[16px] bg-white/55 p-3 dark:bg-white/5">
          <div className="mb-2 flex items-center justify-between text-[11.5px] font-semibold text-ink-3"><span>Top stages</span><span>{stages.length} stages</span></div>
          <div className="grid grid-cols-3 gap-2">{topStages.length ? topStages.map((s) => <div key={s.stage} className="min-w-0"><div className="truncate text-[11.5px] text-ink-3">{stageName(s.stage)}</div><div className="truncate text-[14px] font-bold">{formatMoneyShort(Number(s.v), cur)}</div><div className="text-[11px] text-ink-3">{s.n} deals</div></div>) : <div className="col-span-3 text-[12px] text-ink-3">No open deals yet</div>}</div>
        </div>
      </section>
    ),
    hero: (
      <section className="hero-blue lift relative h-full overflow-hidden rounded-[22px] p-5">
        <div className="pointer-events-none absolute -right-10 -top-10 h-40 w-40 rounded-full bg-white/10 blur-2xl" />
        <div className="flex items-center justify-between text-[13px] font-medium text-white/85">Revenue won<span className="grid h-8 w-8 place-items-center rounded-full bg-white/15"><TrendingUp className="h-4 w-4" /></span></div>
        <div className="mt-3 font-display text-[36px] font-extrabold leading-tight tracking-tight">{formatMoneyShort(won.v, cur)}</div>
        <div className="mt-2 flex items-center gap-2 text-[12px]"><span className="rounded-full bg-white/20 px-2 py-0.5 font-semibold">{wonDelta == null ? "—" : `${wonDelta >= 0 ? "▲" : "▼"} ${Math.abs(wonDelta).toFixed(0)}%`}</span><span className="text-white/75">vs previous {days} days</span></div>
        <div className="mt-6 flex items-end justify-between"><div><div className="text-[11.5px] text-white/70">{ind.wonLabel}</div><div className="text-[20px] font-bold">{won.n} deals</div></div><Link href="/analytics" className="flex items-center gap-1 rounded-full bg-white px-3 py-1.5 text-[12px] font-semibold text-brand">Analytics <ArrowUpRight className="h-3.5 w-3.5" /></Link></div>
      </section>
    ),
    kpis: (
      <div className="grid h-full grid-cols-2 gap-3">
        {[
          { label: "New leads", value: k.newLeads, sub: leadDelta == null ? "—" : `${leadDelta >= 0 ? "+" : ""}${leadDelta.toFixed(0)}%`, up: (leadDelta ?? 0) >= 0, icon: <Users className="h-4 w-4" /> },
          { label: "Open deals", value: openCount, sub: formatMoneyShort(openTotal, cur), up: true, icon: <Target className="h-4 w-4" /> },
          { label: "Win rate", value: winRate == null ? "—" : `${winRate.toFixed(1)}%`, sub: `${closed?.won ?? 0} won · ${closed?.lost ?? 0} lost`, up: (winRate ?? 0) >= 20, icon: <Sparkles className="h-4 w-4" /> },
          { label: "First response", value: k.medianResponseMin == null ? "—" : k.medianResponseMin < 60 ? `${k.medianResponseMin.toFixed(1)}m` : `${(k.medianResponseMin / 60).toFixed(1)}h`, sub: "median", up: (k.medianResponseMin ?? 99) <= 5, icon: <Clock className="h-4 w-4" /> },
        ].map((x) => (
          <div key={x.label} className="card lift flex flex-col justify-between p-4">
            <div className="flex items-center justify-between text-[12px] font-medium text-ink-2">{x.label}<span className="grid h-7 w-7 place-items-center rounded-full bg-brand/10 text-brand">{x.icon}</span></div>
            <div className="mt-2 font-display text-[24px] font-extrabold leading-tight">{x.value}</div>
            <div className={`mt-1 text-[11.5px] font-medium ${x.up ? "text-ok" : "text-ink-3"}`}>{x.sub}</div>
          </div>
        ))}
      </div>
    ),
    sales_overview: (
      <Card title="Sales overview" subtitle="Won vs lost deals, last 6 months" className="h-full" actions={<span className="flex items-center gap-3 text-[11.5px] text-ink-2"><span className="flex items-center gap-1"><span className="h-2.5 w-2.5 rounded-full bg-[#8B7CF6]" />Won</span><span className="flex items-center gap-1"><span className="h-2.5 w-2.5 rounded-full bg-ink" />Lost</span></span>}>
        <WonLostBars data={months} />
      </Card>
    ),
    sales_target: (
      <section className="card lift h-full p-5">
        <div className="text-[13px] font-medium text-ink-2">Quarterly sales target</div>
        <div className="mt-2 font-display text-[26px] font-extrabold">{formatMoneyShort(Number(quarterWon[0]?.v ?? 0), cur)} <span className="text-[14px] font-semibold text-ink-3">/ {formatMoneyShort(target, cur)}</span></div>
        <div className="mt-3 h-3 overflow-hidden rounded-full bg-white/70 dark:bg-white/10"><div className="h-full rounded-full bg-gradient-to-r from-brand to-[#8B7CF6] shadow-[0_0_12px_rgb(var(--brand)/.5)]" style={{ width: `${targetPct}%` }} /></div>
        <div className="mt-2 flex justify-between text-[11.5px] text-ink-3"><span>{targetPct.toFixed(0)}% achieved</span><span>{ws.settings?.salesTargetQuarterly ? "Target set in Settings" : "Suggested: +25% on this quarter"}</span></div>
      </section>
    ),
    recent_deals: <RecentDeals rows={deals} />,
    industry_focus: (
      <Card title={`${ind.label.split(" &")[0]} focus`} subtitle={`Where your ${ind.offering} deals are now`} className="h-full">
        <div className="mb-3 flex items-center gap-3 rounded-[16px] bg-brand/5 p-3"><span className="grid h-10 w-10 place-items-center rounded-full bg-brand/10 text-brand"><CalendarCheck className="h-5 w-5" /></span><div><div className="text-[20px] font-extrabold leading-none">{upcomingVisits[0]?.n ?? 0}</div><div className="text-[12px] text-ink-3">{ind.visitPlural} in the next 7 days</div></div></div>
        <ul className="space-y-2">{focusStages.map((s) => { const r = openByStage.find((x) => x.stage === s.id); const n = r?.n ?? 0; const max = Math.max(1, ...openByStage.map((x) => x.n)); return (
          <li key={s.id}><div className="flex justify-between text-[12.5px]"><span className="truncate">{s.name}</span><b>{n}</b></div><div className="mt-1 h-1.5 rounded-full bg-white/70 dark:bg-white/10"><div className="h-1.5 rounded-full bg-brand" style={{ width: `${(n / max) * 100}%` }} /></div></li>
        ); })}</ul>
        <Link href="/pipeline" className="mt-3 inline-flex items-center gap-1 text-[12px] font-semibold text-brand">Open pipeline <ArrowRight className="h-3.5 w-3.5" /></Link>
      </Card>
    ),
    trend: <Card title="Leads, spend & sales" subtitle="CRM leads vs ad spend per day" className="h-full"><TrendChart data={trend} currency={cur} /></Card>,
    funnel: (
      <Card title="Funnel" subtitle="Cost per stage" className="h-full" actions={<Link href="/analytics" className="text-[12px] font-semibold text-brand">Analytics →</Link>}>
        {fun ? <FunnelBars stages={fun.stages.map((s) => ({ label: s.label, count: s.count, costLabel: s.costLabel, cost: s.cost ? formatMoney(s.cost, cur) : undefined }))} /> : <Empty title="No pipeline yet" />}
      </Card>
    ),
    tasks: (
      <Card title="Due today" subtitle="Your tasks & follow-ups" className="h-full" bodyClass="p-0 pb-2" actions={<Link href="/tasks" className="text-[12px] font-semibold text-brand">All →</Link>}>
        {!tasks.length ? <Empty title="Nothing due" /> : <ul className="divide-y divide-line/60">{tasks.map(({ a, c }) => (
          <li key={a.id}><Link href={c?.id ? `/contacts/${c.id}` : "/tasks"} className="flex items-center gap-3 px-5 py-2.5 hover:bg-white/50 dark:hover:bg-white/5">
            <Badge tone={a.dueAt && a.dueAt < new Date() ? "red" : "blue"}>{a.type === "visit" ? ind.visit : a.type}</Badge>
            <span className="min-w-0 flex-1"><span className="block truncate text-[13px]">{a.title}</span><span className="block truncate text-[11.5px] text-ink-3">{c?.id ? fullName(c as never) : "—"}</span></span>
            <span className={a.dueAt && a.dueAt < new Date() ? "text-[11.5px] text-bad" : "text-[11.5px] text-ink-3"}>{timeAgo(a.dueAt)}</span>
          </Link></li>))}</ul>}
      </Card>
    ),
    new_leads: (
      <Card title="Newest leads" className="h-full" bodyClass="p-0 pb-2" actions={<Link href="/contacts" className="text-[12px] font-semibold text-brand">All →</Link>}>
        <ul className="divide-y divide-line/60">{recent.map((c) => (
          <li key={c.id}><Link href={`/contacts/${c.id}`} className="flex items-center gap-3 px-5 py-2.5 hover:bg-white/50 dark:hover:bg-white/5">
            <span className="min-w-0 flex-1"><span className="block truncate text-[13px] font-medium">{fullName(c)}</span><span className="block truncate text-[11.5px] text-ink-3">{[c.project, c.source?.replace(/_/g, " ")].filter(Boolean).join(" · ") || "—"}</span></span>
            {c.score != null && <Badge tone={c.score >= 70 ? "green" : c.score >= 40 ? "amber" : "gray"}>{c.score}</Badge>}
            {!c.firstContactedAt && <Badge tone="red" dot>new</Badge>}
          </Link></li>))}</ul>
      </Card>
    ),
    alerts: (
      <Card title="Alerts" subtitle="Anomalies & budget pacing" className="h-full" bodyClass="p-0 pb-2">
        {!anomalies.length ? <Empty title="All quiet" icon={<Sparkles className="h-5 w-5" />}>No anomalies beyond your thresholds.</Empty> : <ul className="divide-y divide-line/60">{anomalies.map((a) => (
          <li key={a.id} className="flex gap-3 px-5 py-3"><AlertTriangle className={`mt-0.5 h-4 w-4 shrink-0 ${a.changePct > 0 && a.metric !== "Leads" && a.metric !== "CTR" ? "text-bad" : "text-warn"}`} /><div className="min-w-0"><p className="text-[12.5px] leading-snug">{a.message}</p><p className="mt-0.5 text-[11px] text-ink-3">{a.metric} · {timeAgo(a.createdAt)}</p></div></li>))}</ul>}
      </Card>
    ),
    inbox: (
      <Card title="Inbox" subtitle="Messages, comments and reviews" className="h-full" actions={<Link href="/inbox" className="text-[12px] font-semibold text-brand">Open →</Link>}>
        <div className="grid grid-cols-3 gap-2 text-center">
          {[["Open", inboxStats[0]?.open ?? 0, "text-ink"], ["Unanswered", inboxStats[0]?.unanswered ?? 0, "text-warn"], ["SLA breached", inboxStats[0]?.breached ?? 0, "text-bad"]].map(([l, n, c]) => (
            <Link key={String(l)} href="/inbox" className="rounded-[16px] bg-white/55 p-3 hover:bg-white dark:bg-white/5"><div className={`font-display text-[24px] font-extrabold ${c}`}>{n}</div><div className="text-[11.5px] text-ink-3">{l}</div></Link>
          ))}
        </div>
        <div className="mt-3 flex items-center gap-2 rounded-[14px] bg-violet/10 px-3 py-2 text-[12px] text-violet"><Inbox className="h-4 w-4" />Ask AI to draft replies from the inbox.</div>
      </Card>
    ),
  };

  const layout = resolveLayout(membership?.dashboardLayout, ws.settings?.industry);
  return (
    <>
      <div className="mb-2 flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="text-[30px] font-extrabold leading-tight tracking-tight sm:text-[34px]">{greeting}, {ctx.user?.name.split(" ")[0] ?? ""}</h1>
          <p className="mt-1 text-[13.5px] text-ink-2">Track your pipeline, close more deals and keep every customer conversation moving · {ind.label}</p>
        </div>
        <RangePicker />
      </div>
      {sp.welcome && <div className="glass-panel mb-3 rounded-[18px] px-4 py-3 text-[13px]">🎉 Welcome aboard! Your workspace is set up for <b>{ind.label}</b>. Use <b>Customize dashboard</b> to arrange it your way, or tap <b>Ask AI</b> for a guided tour.</div>}
      <DashboardGrid widgets={widgets} layout={layout} defaults={defaultLayout(ws.settings?.industry)} />
    </>
  );
}


