"use client";
/** Engagement analytics (SOC-080…084): response times, volume, sentiment, top posts/ads with leads and revenue, automation impact. */
import Link from "next/link";
import { useState } from "react";
import { Area, AreaChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { ArrowLeft, Download } from "lucide-react";
import { Badge, Button, Card, Empty, PageHeader, Segmented, Spinner, Stat } from "@/components/ui";
import { moneyShort, useApi } from "@/components/hooks";
import { CHANNEL_LABEL, fmtSecs, intentLabel } from "@/components/social";

const RANGES = { "7": "7 days", "30": "30 days", "90": "90 days" } as const;

export default function EngagementAnalytics() {
  const [days, setDays] = useState<keyof typeof RANGES>("30");
  const [groupBy, setGroupBy] = useState<"channel" | "account" | "agent" | "day">("channel");
  const from = new Date(Date.now() - Number(days) * 86400000).toISOString();
  const qs = `from=${encodeURIComponent(from)}&group_by=${groupBy}`;
  const r = useApi<{ data: any }>(`/reports/engagement?${qs}`, [qs]);
  const team = useApi<{ currency: string }>("/team");
  const d = r.data?.data;
  return (
    <div>
      <Link href="/inbox" className="mb-2 inline-flex items-center gap-1 text-[12.5px] text-ink-3 hover:text-brand"><ArrowLeft className="h-3.5 w-3.5" />Inbox</Link>
      <PageHeader title="Engagement analytics" subtitle="How fast and how well the team answers comments, messages and reviews — and what it earns."
        actions={<><Segmented size="sm" value={days} onChange={setDays} options={Object.entries(RANGES).map(([value, label]) => ({ value: value as keyof typeof RANGES, label }))} /><a href={`/api/v1/reports/engagement?${qs}&format=csv`}><Button icon={<Download className="h-4 w-4" />}>CSV</Button></a></>} />
      {r.error && <p className="text-[13px] text-bad">{r.error}</p>}
      {!d ? !r.error && <Spinner /> : (
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-3 lg:grid-cols-6">
            <Stat label="Conversations" value={d.total.conversations} sub={`${d.total.inbound} inbound items`} />
            <Stat label="Replied" value={`${Math.round(d.total.repliedPct)}%`} sub={`${d.total.replied} answered`} />
            <Stat label="Median first response" value={fmtSecs(d.total.medianFirstResponseS)} sub={`p90 ${fmtSecs(d.total.p90FirstResponseS)}`} />
            <Stat label="Median resolution" value={fmtSecs(d.total.medianResolutionS)} sub={`${d.total.resolved} resolved`} />
            <Stat label="Leads from social" value={d.total.leads} sub={`${d.total.negative} negative · ${d.total.hidden} hidden`} />
            <Stat label="Handled by automation" value={`${Math.round(d.total.automatedPct)}%`} sub="of replied, no human touch" />
          </div>
          <Card title="Breakdown" actions={<Segmented size="sm" value={groupBy} onChange={setGroupBy} options={[{ value: "channel", label: "Channel" }, { value: "account", label: "Account" }, { value: "agent", label: "Agent" }, { value: "day", label: "Day" }]} />} bodyClass="p-0 overflow-x-auto">
            {!d.groups.length ? <Empty title="No conversations in this range" /> : (
              <table className="w-full min-w-[720px] text-[12.5px]">
                <thead className="text-left text-[11px] uppercase text-ink-3"><tr className="border-b border-line">{["", "Conversations", "Inbound", "Replied", "Median FRT", "p90 FRT", "Resolution", "Negative", "Leads", "Automated"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}</tr></thead>
                <tbody>{d.groups.map((g: any) => <tr key={g.key} className="border-b border-line/50"><td className="px-3 py-2 font-medium">{groupBy === "channel" ? CHANNEL_LABEL[g.key] ?? g.key : g.key}</td><td className="px-3 py-2 tabular-nums">{g.conversations}</td><td className="px-3 py-2 tabular-nums">{g.inbound}</td><td className="px-3 py-2 tabular-nums">{Math.round(g.repliedPct)}%</td><td className="px-3 py-2 tabular-nums">{fmtSecs(g.medianFirstResponseS)}</td><td className="px-3 py-2 tabular-nums">{fmtSecs(g.p90FirstResponseS)}</td><td className="px-3 py-2 tabular-nums">{fmtSecs(g.medianResolutionS)}</td><td className="px-3 py-2 tabular-nums">{g.negative}</td><td className="px-3 py-2 tabular-nums">{g.leads}</td><td className="px-3 py-2 tabular-nums">{Math.round(g.automatedPct)}%</td></tr>)}</tbody>
              </table>
            )}
          </Card>
          <div className="grid gap-4 lg:grid-cols-3">
            <Card title="Comment sentiment over time" className="lg:col-span-2">
              {!d.sentimentDaily.length ? <Empty title="No comments yet" /> : (
                <ResponsiveContainer width="100%" height={240}>
                  <AreaChart data={d.sentimentDaily} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
                    <CartesianGrid vertical={false} stroke="rgb(var(--line))" />
                    <XAxis dataKey="date" stroke="rgb(var(--ink-3))" fontSize={11} tickLine={false} axisLine={false} tickFormatter={(v) => v.slice(5)} />
                    <YAxis stroke="rgb(var(--ink-3))" fontSize={11} tickLine={false} axisLine={false} allowDecimals={false} />
                    <Tooltip contentStyle={{ background: "rgb(var(--panel))", border: "0.5px solid rgb(var(--line))", borderRadius: 10, fontSize: 12 }} />
                    <Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
                    <Area type="monotone" stackId="1" dataKey="positive" name="Positive" stroke="#2F9E6E" fill="#2F9E6E" fillOpacity={0.35} />
                    <Area type="monotone" stackId="1" dataKey="neutral" name="Neutral" stroke="#8B8B96" fill="#8B8B96" fillOpacity={0.25} />
                    <Area type="monotone" stackId="1" dataKey="negative" name="Negative" stroke="#E13D48" fill="#E13D48" fillOpacity={0.35} />
                  </AreaChart>
                </ResponsiveContainer>
              )}
            </Card>
            <Card title="Top intents">
              {!d.intents.length ? <Empty title="—" /> : <ul className="space-y-1.5 text-[13px]">{d.intents.slice(0, 8).map((i: any) => { const max = d.intents[0].count; return <li key={i.intent}><div className="flex justify-between"><span className="capitalize">{intentLabel(i.intent)}</span><b>{i.count}</b></div><div className="mt-0.5 h-1.5 rounded-full bg-sunken"><div className="h-1.5 rounded-full bg-violet" style={{ width: `${(i.count / max) * 100}%` }} /></div></li>; })}</ul>}
            </Card>
          </div>
          <Card title="Posts & ads by conversation" subtitle="Leads and won revenue attributed to comments on each post or ad" bodyClass="p-0 overflow-x-auto">
            {!d.topObjects.length ? <Empty title="No posts with comments yet" /> : (
              <table className="w-full min-w-[640px] text-[12.5px]">
                <thead className="text-left text-[11px] uppercase text-ink-3"><tr className="border-b border-line">{["Post / ad", "Comments", "Negative", "Leads", "Won", "Revenue"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}</tr></thead>
                <tbody>{d.topObjects.slice(0, 20).map((o: any) => <tr key={o.id} className="border-b border-line/50"><td className="max-w-[340px] px-3 py-2"><Link href={`/inbox?object=${o.id}&view=all`} className="flex items-center gap-2 hover:text-brand">{o.thumbnail && <img src={o.thumbnail} alt="" className="h-8 w-8 rounded object-cover" />}<span className="min-w-0"><span className="flex items-center gap-1"><Badge tone={o.type === "ad" ? "violet" : "gray"}>{o.type}</Badge><span className="truncate text-[11px] text-ink-3">{o.account}{o.campaign ? ` · ${o.campaign}` : ""}</span></span><span className="line-clamp-1">{o.caption ?? "(no caption)"}</span></span></Link></td><td className="px-3 py-2 tabular-nums">{o.comments}</td><td className="px-3 py-2 tabular-nums">{Math.round(o.negativeShare)}%</td><td className="px-3 py-2 tabular-nums">{o.leads}</td><td className="px-3 py-2 tabular-nums">{o.won}</td><td className="px-3 py-2 tabular-nums">{moneyShort(o.revenue, team.data?.currency)}</td></tr>)}</tbody>
              </table>
            )}
          </Card>
          <Card title="Automation impact" subtitle="Rule activity in this range" bodyClass="p-0 overflow-x-auto">
            {!d.rules.length ? <Empty title="No rules yet" action={<Link href="/inbox/rules"><Button size="sm">Create a rule</Button></Link>} /> : (
              <table className="w-full min-w-[520px] text-[12.5px]"><thead className="text-left text-[11px] uppercase text-ink-3"><tr className="border-b border-line">{["Rule", "Type", "Fires (range)", "Replies", "Leads", "Hidden"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}</tr></thead>
                <tbody>{d.rules.map((x: any) => <tr key={x.id} className="border-b border-line/50"><td className="px-3 py-2 font-medium">{x.name}</td><td className="px-3 py-2">{x.type.replace("_", " ")}</td><td className="px-3 py-2 tabular-nums">{x.fires}</td><td className="px-3 py-2 tabular-nums">{x.replies}</td><td className="px-3 py-2 tabular-nums">{x.leads}</td><td className="px-3 py-2 tabular-nums">{x.hides}</td></tr>)}</tbody></table>
            )}
          </Card>
        </div>
      )}
    </div>
  );
}
