import { and, eq } from "drizzle-orm";
import { schema } from "@/db";
import { requireCtx } from "@/lib/auth";
import { ATTRIBUTION_MODELS, attribution, dailyTrend, externalAnalytics, funnel, parseFilters, repPerformance } from "@/lib/services/analytics";
import { formatMoney, formatMoneyShort } from "@/lib/util";
import { FunnelBars, MultiLine, SimpleBars, TrendChart } from "@/components/charts";
import { QuerySelect, RangePicker } from "@/components/range-picker";
import { Badge, Card, Empty, PageHeader, Stat } from "@/components/ui";

export const metadata = { title: "Analytics" };
const SOURCES = [["meta_lead_ad", "Meta Lead Ads"], ["google_lead_form", "Google lead forms"], ["web_form", "Web forms"], ["whatsapp", "WhatsApp"], ["messenger", "Messenger"], ["call", "Calls"], ["api", "API"], ["import", "Import"]];

export default async function AnalyticsPage({ searchParams }: { searchParams: Promise<Record<string, string>> }) {
  const ctx = await requireCtx("reports");
  const sp = await searchParams;
  const f = parseFilters(sp);
  if (ctx.perms.reports === "V:own" && ctx.user) f.rep = ctx.user.id;
  const model = sp.model ?? ctx.workspace.settings?.attributionModel ?? "last_touch";
  const group = sp.group === "campaign" ? "campaign" : "channel";
  const cur = ctx.workspace.currency;
  const [fun, attr, reps, trend, campaigns, members, integrations] = await Promise.all([
    funnel(ctx, f), attribution(ctx, f, model, group), repPerformance(ctx, f), dailyTrend(ctx, f),
    ctx.db.select({ e: schema.campaigns.externalId, n: schema.campaigns.name }).from(schema.campaigns).where(eq(schema.campaigns.workspaceId, ctx.workspace.id)),
    ctx.db.select({ id: schema.users.id, name: schema.users.name }).from(schema.memberships).innerJoin(schema.users, eq(schema.users.id, schema.memberships.userId)).where(and(eq(schema.memberships.workspaceId, ctx.workspace.id), eq(schema.memberships.active, true))),
    ctx.db.select().from(schema.integrations).where(eq(schema.integrations.workspaceId, ctx.workspace.id)),
  ]);
  const projects = [...new Set((fun?.byStage ?? []).length ? (await ctx.db.selectDistinct({ p: schema.deals.project }).from(schema.deals).where(eq(schema.deals.workspaceId, ctx.workspace.id))).map((r) => r.p).filter(Boolean) as string[] : [])];
  const ext = externalAnalytics(integrations);
  const extMerged = ext.ga4.map((g) => ({ date: g.date, sessions: g.sessions, conversions: g.conversions, organic: ext.gsc.find((s) => s.date === g.date)?.clicks ?? 0, leads: trend.find((t) => t.date === g.date)?.leads ?? 0 }));
  const visibleReps = ctx.perms.reports === "V:own" ? reps.filter((r) => r.userId === ctx.user?.id) : reps;

  return (
    <>
      <PageHeader title="Analytics & attribution" subtitle="Full funnel from spend to sale — CPL → cost per qualified lead → cost per visit → cost per sale" actions={<RangePicker options={[7, 30, 90, 180]} />}>
        <div className="mt-3 flex flex-wrap gap-2">
          <QuerySelect name="source" placeholder="All sources" options={SOURCES.map(([v, l]) => ({ value: v, label: l }))} />
          <QuerySelect name="campaign" placeholder="All campaigns" options={campaigns.map((c) => ({ value: c.e, label: c.n }))} />
          <QuerySelect name="project" placeholder="All projects" options={projects.map((p) => ({ value: p, label: p }))} />
          {ctx.perms.reports !== "V:own" && <QuerySelect name="rep" placeholder="All reps" options={members.map((m) => ({ value: m.id, label: m.name }))} />}
        </div>
      </PageHeader>

      <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
        <Stat label="Spend" value={formatMoneyShort(fun?.spend ?? 0, cur)} />
        {fun?.stages.map((s) => <Stat key={s.key} label={s.label} value={s.count} sub={s.cost ? `${s.costLabel} ${formatMoney(s.cost, cur)}` : s.costLabel} />)}
        <Stat label="Revenue · ROAS" value={formatMoneyShort(fun?.revenue ?? 0, cur)} sub={fun?.roas ? `${fun.roas.toFixed(1)}× ROAS` : "—"} tone="up" />
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-3">
        <Card title="Funnel" subtitle="Deals created in the period and the furthest stage they reached">{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 data" />}</Card>
        <Card title="Trend" className="xl:col-span-2"><TrendChart data={trend} currency={cur} /></Card>
      </div>

      <Card className="mt-4" title="Attribution" subtitle="How won deals credit their sources — switch the model to recalculate"
        actions={<div className="flex flex-wrap gap-2"><QuerySelect name="model" placeholder={ATTRIBUTION_MODELS.find((m) => m.key === model)?.label ?? "Model"} options={ATTRIBUTION_MODELS.filter((m) => m.key !== model).map((m) => ({ value: m.key, label: m.label }))} /><QuerySelect name="group" placeholder={group === "campaign" ? "By campaign" : "By channel"} options={[{ value: group === "campaign" ? "channel" : "campaign", label: group === "campaign" ? "By channel" : "By campaign" }]} /></div>} bodyClass="p-0">
        <div className="grid gap-0 lg:grid-cols-2">
          <div className="border-b border-line/60 p-4 lg:border-b-0 lg:border-r">{attr.length ? <SimpleBars data={attr.slice(0, 8).map((a) => ({ name: a.key.replace(/_/g, " "), revenue: a.revenue / 100 }))} xKey="name" yKey="revenue" /> : <Empty title="No won deals in this period" />}</div>
          <div className="max-h-[320px] overflow-y-auto">
            <table className="table-mac">
              <thead><tr><th>{group === "campaign" ? "Campaign" : "Source"}</th><th className="text-right">Leads</th><th className="text-right">Won (credit)</th><th className="text-right">Revenue</th></tr></thead>
              <tbody>{attr.map((a) => <tr key={a.key}><td className="capitalize">{a.key.replace(/_/g, " ")}</td><td className="text-right">{a.leads}</td><td className="text-right">{a.won}</td><td className="text-right font-medium">{formatMoney(a.revenue, cur)}</td></tr>)}</tbody>
            </table>
          </div>
        </div>
      </Card>

      <Card className="mt-4" title="Rep performance" subtitle="Response time, conversion rate and activity — leaderboard for the period" bodyClass="p-0">
        <div className="overflow-x-auto">
          <table className="table-mac min-w-[880px]">
            <thead><tr><th>#</th><th>Rep</th><th className="text-right">Leads</th><th className="text-right">Won</th><th className="text-right">Conversion</th><th className="text-right">Revenue</th><th className="text-right">Median response</th><th className="text-right">SLA breaches</th><th className="text-right">Calls</th><th className="text-right">Visits</th><th className="text-right">Activities</th></tr></thead>
            <tbody>{visibleReps.filter((r) => r.leads || r.activities).map((r, i) => (
              <tr key={r.userId}><td>{i < 3 ? ["🥇", "🥈", "🥉"][i] : i + 1}</td><td className="font-medium">{r.name}</td><td className="text-right">{r.leads}</td><td className="text-right">{r.won}</td><td className="text-right">{r.conversionRate.toFixed(1)}%</td><td className="text-right">{formatMoneyShort(r.revenue, cur)}</td>
                <td className="text-right">{r.medianResponseMin == null ? "—" : <Badge tone={r.medianResponseMin <= 5 ? "green" : r.medianResponseMin <= 30 ? "amber" : "red"}>{r.medianResponseMin < 60 ? `${r.medianResponseMin.toFixed(0)} min` : `${(r.medianResponseMin / 60).toFixed(1)} h`}</Badge>}</td>
                <td className="text-right">{r.slaBreaches}</td><td className="text-right">{r.calls}</td><td className="text-right">{r.visits}</td><td className="text-right">{r.activities}</td></tr>
            ))}</tbody>
          </table>
        </div>
      </Card>

      <Card className="mt-4" title="Website & search" subtitle="GA4 sessions and Search Console organic clicks alongside CRM leads">
        {ext.ga4Connected || ext.gscConnected ? <MultiLine data={extMerged} lines={[{ key: "sessions", name: "GA4 sessions" }, { key: "organic", name: "Organic clicks (GSC)" }, { key: "leads", name: "CRM leads", axis: "r" }]} /> : <Empty title="Connect GA4 and Search Console">Go to Integrations to add website and organic search metrics here.</Empty>}
      </Card>
    </>
  );
}
