"use client";
/** Settings → Social (Module 11): accounts, capabilities, webhook health, backfill, flags, SLA, hours, AI autopilot, moderation, saved replies, team routing. */
import Link from "next/link";
import { useEffect, useState } from "react";
import { Activity, Check, Copy, FlaskConical, MessageSquarePlus, Plus, RefreshCw, Trash2, X } from "lucide-react";
import { Badge, Button, Card, Checkbox, Empty, Field, Input, PageHeader, Select, Sheet, Spinner, Tabs, Textarea, Toggle, api, useAction, useUI } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";
import { CHANNEL_LABEL, INTENTS, PLATFORM_LABEL, intentLabel } from "@/components/social";

type Account = { id: string; name: string; platform: string; status: string; capabilities: Record<string, boolean>; webhookSubscribed: boolean; lastEventAt: string | null; lastPolledAt: string | null; backfill: { status?: string; done?: number; error?: string }; lastError: string | null; open: number; total: number; polled: boolean; integration: { mode: string; status: string } | null };
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const CAP_LABEL: Record<string, string> = { can_reply: "Reply", can_private_reply: "Private reply", can_hide: "Hide", can_delete: "Delete", can_like: "Like", can_dm: "DMs", can_reply_review: "Review replies" };

export default function SocialSettings() {
  const [tab, setTab] = useState<"accounts" | "inbox" | "ai" | "replies" | "team">("accounts");
  return (
    <div>
      <PageHeader title="Social inbox" subtitle="Comments, DMs and reviews from Facebook, Instagram, YouTube, Google Business Profile, TikTok and LinkedIn." />
      <div className="mb-4 overflow-x-auto"><Tabs value={tab} onChange={setTab} tabs={[{ value: "accounts", label: "Accounts" }, { value: "inbox", label: "SLA & hours" }, { value: "ai", label: "AI & moderation" }, { value: "replies", label: "Saved replies" }, { value: "team", label: "Team routing" }]} /></div>
      {tab === "accounts" && <Accounts />}
      {tab === "inbox" && <InboxSettings />}
      {tab === "ai" && <AiSettings />}
      {tab === "replies" && <SavedReplies />}
      {tab === "team" && <TeamRouting />}
    </div>
  );
}

function useWorkspace() {
  const ws = useApi<{ data: { settings: Record<string, any>; timezone: string } }>("/workspace");
  const { push } = useUI();
  const save = async (social: Record<string, unknown>) => {
    try { await api("/workspace", { method: "PATCH", body: { settings: { social } } }); push("ok", "Saved"); ws.reload(); } catch (e) { push("error", (e as Error).message); }
  };
  return { ws, social: (ws.data?.data.settings?.social ?? {}) as Record<string, any>, save };
}

function Accounts() {
  const list = useApi<{ data: Account[] }>("/social/accounts");
  const { ws, social, save } = useWorkspace();
  const { busy, run } = useAction();
  const [sim, setSim] = useState<Account | null>(null);
  const [origin, setOrigin] = useState("");
  useEffect(() => setOrigin(window.location.origin), []);
  const act = (path: string, ok: string) => run(async () => { await api(path, { body: {} }); list.reload(); }, ok);
  const flags = social.featureFlags ?? {};
  return (
    <div className="space-y-4">
      <Card title="Connected accounts" actions={<Button size="sm" loading={busy} icon={<RefreshCw className="h-3.5 w-3.5" />} onClick={() => act("/social/accounts/discover", "Accounts discovered — activate the ones you want in the inbox")}>Discover accounts</Button>} bodyClass="p-0">
        {!list.data ? <div className="p-4"><Spinner /></div> : !list.data.data.length ? <div className="p-4"><Empty title="No social accounts yet" action={<Link href="/integrations"><Button variant="primary">Connect Meta, YouTube or Google Business</Button></Link>}>Connect an integration, then click <b>Discover accounts</b>. New accounts start inactive.</Empty></div> : (
          <ul className="divide-y divide-line/60">
            {list.data.data.map((a) => (
              <li key={a.id} className="flex flex-wrap items-start gap-3 px-4 py-3 text-[13px]">
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-1.5"><b>{a.name}</b><Badge>{PLATFORM_LABEL[a.platform] ?? a.platform}</Badge><Badge tone={a.status === "active" ? "green" : a.status === "inactive" ? "gray" : "red"} dot>{a.status}</Badge>{a.integration?.mode === "sandbox" && <Badge tone="violet">sandbox</Badge>}</div>
                  <div className="mt-1 flex flex-wrap gap-1">{Object.entries(a.capabilities).filter(([, v]) => v).map(([k]) => <span key={k} className="inline-flex items-center gap-0.5 rounded bg-sunken px-1.5 text-[11px] text-ink-2"><Check className="h-2.5 w-2.5" />{CAP_LABEL[k] ?? k}</span>)}</div>
                  <div className="mt-1 flex flex-wrap gap-x-3 text-[11.5px] text-ink-3">
                    <span><Activity className="mr-0.5 inline h-3 w-3" />{a.polled ? `Polled · last ${ago(a.lastPolledAt)}` : a.webhookSubscribed ? `Webhook on · last event ${ago(a.lastEventAt)}` : "Webhook off"}</span>
                    <span>Backfill: {a.backfill.status ?? "not started"}{a.backfill.done != null ? ` (${a.backfill.done})` : ""}</span>
                    <span>{a.open} open / {a.total} conversations</span>
                  </div>
                  {(a.lastError || a.backfill.error) && <p className="mt-1 text-[12px] text-bad">⚠ {a.lastError ?? a.backfill.error}</p>}
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {a.status === "active" ? <>
                    <Button size="sm" onClick={() => act(`/social/accounts/${a.id}/poll`, "Polled")}>Poll now</Button>
                    <Button size="sm" onClick={() => act(`/social/accounts/${a.id}/backfill`, "Backfill complete")}>Backfill</Button>
                    {a.integration?.mode === "sandbox" && <Button size="sm" icon={<FlaskConical className="h-3.5 w-3.5" />} onClick={() => setSim(a)}>Simulate</Button>}
                    <Button size="sm" variant="ghost" onClick={() => act(`/social/accounts/${a.id}/deactivate`, "Deactivated")}>Deactivate</Button>
                  </> : <Button size="sm" variant="primary" onClick={() => act(`/social/accounts/${a.id}/activate`, "Activated — backfilling the last 30 days")}>Activate</Button>}
                </div>
              </li>
            ))}
          </ul>
        )}
      </Card>
      <Card title="Meta webhook (one URL for the whole app)">
        <div className="space-y-2 text-[13px]">
          <p className="text-ink-2">In the Meta app dashboard → Webhooks, subscribe <b>Page</b> (feed, messages, leadgen), <b>Instagram</b> (comments, mentions, messages) and <b>WhatsApp Business Account</b> (messages) to:</p>
          <CopyRow value={`${origin}/api/meta/webhook`} />
          <p className="text-[12px] text-ink-3">Verify token = the <code>META_VERIFY_TOKEN</code> environment variable. Signatures are checked with <code>META_APP_SECRET</code>. Events are routed to the workspace that activated the page.</p>
        </div>
      </Card>
      <Card title="Feature flags">
        {!ws.data ? <Spinner /> : <div className="flex flex-wrap gap-6"><Toggle checked={!!flags.tiktok} onChange={(v) => save({ featureFlags: { ...flags, tiktok: v } })} label="TikTok comments (needs TikTok for Business API approval)" /><Toggle checked={!!flags.linkedin} onChange={(v) => save({ featureFlags: { ...flags, linkedin: v } })} label="LinkedIn comments (needs Community Management API)" /></div>}
      </Card>
      {sim && <Simulator account={sim} onClose={() => setSim(null)} />}
    </div>
  );
}

function CopyRow({ value }: { value: string }) {
  const { push } = useUI();
  return <div className="flex gap-2"><Input readOnly value={value} onFocus={(e) => e.target.select()} /><Button icon={<Copy className="h-4 w-4" />} onClick={() => { navigator.clipboard?.writeText(value).then(() => push("ok", "Copied")).catch(() => {}); }}>Copy</Button></div>;
}

function Simulator({ account, onClose }: { account: Account; onClose: () => void }) {
  const [kind, setKind] = useState(account.platform === "google_business" ? "review" : "comment");
  const [text, setText] = useState(account.platform === "google_business" ? "Waited a long time and nobody answers the phone." : "Price koto? Details please");
  const [author, setAuthor] = useState("Test Customer");
  const [rating, setRating] = useState(2);
  const [ad, setAd] = useState("");
  const { busy, run } = useAction();
  const [res, setRes] = useState<any>(null);
  const go = () => run(async () => { const r = await api<{ data: any }>(`/social/accounts/${account.id}/simulate`, { body: { kind, text, author_name: author, rating: kind === "review" ? rating : undefined, external_ad_id: ad || undefined } }); setRes(r.data); }, "Injected — check the inbox");
  return (
    <Sheet open onClose={onClose} title={`Simulate on ${account.name}`} width={460}>
      <div className="space-y-3">
        <Select value={kind} onChange={(e) => setKind(e.target.value)}>{account.platform === "google_business" ? <option value="review">Review</option> : <><option value="comment">Comment</option>{["facebook", "instagram"].includes(account.platform) && <option value="dm">Direct message</option>}</>}</Select>
        <Field label="Author"><Input value={author} onChange={(e) => setAuthor(e.target.value)} /></Field>
        {kind === "review" && <Field label="Rating"><Select value={rating} onChange={(e) => setRating(Number(e.target.value))}>{[1, 2, 3, 4, 5].map((n) => <option key={n} value={n}>{n}★</option>)}</Select></Field>}
        {kind === "comment" && <Field label="Ad ID (optional — simulates a comment on an ad)"><Input value={ad} onChange={(e) => setAd(e.target.value)} placeholder="meta-0-0-0" /></Field>}
        <Field label="Text"><Textarea rows={3} value={text} onChange={(e) => setText(e.target.value)} /></Field>
        <Button variant="primary" loading={busy} onClick={go}>Send test item</Button>
        {res && <div className="rounded-[8px] bg-sunken p-2 text-[12px]">Status: <b>{res.status ?? "received"}</b>{res.conversationId && <> · <Link className="text-brand" href={`/inbox?c=${res.conversationId}`}>Open in inbox</Link></>}</div>}
      </div>
    </Sheet>
  );
}

function InboxSettings() {
  const { ws, social, save } = useWorkspace();
  const [sla, setSla] = useState<Record<string, number>>({});
  const [hours, setHours] = useState<{ days: number[]; start: string; end: string }>({ days: [0, 1, 2, 3, 4, 6], start: "09:00", end: "18:00" });
  const [hoursOn, setHoursOn] = useState(false);
  useEffect(() => { if (ws.data) { setSla({ dm: social.sla?.dm ?? 15, comment: social.sla?.comment ?? 60, review: social.sla?.review ?? 1440 }); if (social.hours) { setHours(social.hours); setHoursOn(true); } } }, [ws.data]); // eslint-disable-line react-hooks/exhaustive-deps
  if (!ws.data) return <Spinner />;
  return (
    <div className="space-y-4">
      <Card title="First-response targets (SLA)" subtitle="Minutes, counted in business hours when set. Urgent = ¼, high = ½ of the target.">
        <div className="grid gap-3 sm:grid-cols-3">{(["dm", "comment", "review"] as const).map((k) => <Field key={k} label={k === "dm" ? "Direct messages" : k === "comment" ? "Comments" : "Reviews"}><Input type="number" min={1} value={sla[k] ?? ""} onChange={(e) => setSla({ ...sla, [k]: Number(e.target.value) })} /></Field>)}</div>
        <div className="mt-3 flex flex-wrap items-center gap-3">
          <Field label="When the SLA is breached"><Select value={social.escalation ?? "notify"} onChange={(e) => save({ escalation: e.target.value })}><option value="notify">Notify managers</option><option value="reassign">Notify and reassign to an available agent</option></Select></Field>
          <div className="flex-1" />
          <Button variant="primary" onClick={() => save({ sla })}>Save targets</Button>
        </div>
      </Card>
      <Card title="Business hours" subtitle={`Workspace timezone: ${ws.data.data.timezone}. Used for SLAs and “after hours” away replies.`}>
        <Toggle checked={hoursOn} onChange={setHoursOn} label="Use business hours" />
        {hoursOn && <div className="mt-3 space-y-3">
          <div className="flex flex-wrap gap-1.5">{DAYS.map((d, i) => <button key={d} type="button" onClick={() => setHours({ ...hours, days: hours.days.includes(i) ? hours.days.filter((x) => x !== i) : [...hours.days, i].sort() })} className={`rounded-full border px-3 py-1 text-[12px] ${hours.days.includes(i) ? "border-brand bg-brand/10 text-brand" : "border-line"}`}>{d}</button>)}</div>
          <div className="flex gap-3"><Field label="Opens"><Input type="time" value={hours.start} onChange={(e) => setHours({ ...hours, start: e.target.value })} /></Field><Field label="Closes"><Input type="time" value={hours.end} onChange={(e) => setHours({ ...hours, end: e.target.value })} /></Field></div>
        </div>}
        <div className="mt-3 text-right"><Button variant="primary" onClick={() => save({ hours: hoursOn ? hours : undefined })}>Save hours</Button></div>
      </Card>
      <Card title="Alerts & WhatsApp hand-off">
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="Comment spike alert" hint="Comments on one post within 30 minutes"><Input type="number" min={3} defaultValue={social.spikeThreshold ?? 20} onBlur={(e) => save({ spikeThreshold: Number(e.target.value) })} /></Field>
          <Field label="WhatsApp business number" hint="Used for “Move to WhatsApp” click-to-chat links"><Input defaultValue={social.whatsappNumber ?? ""} placeholder="8801XXXXXXXXX" onBlur={(e) => save({ whatsappNumber: e.target.value.trim() })} /></Field>
        </div>
      </Card>
    </div>
  );
}

function AiSettings() {
  const { ws, social, save } = useWorkspace();
  const [words, setWords] = useState("");
  const [comp, setComp] = useState("");
  useEffect(() => { if (ws.data) { setWords((social.moderation?.blockedWords ?? []).join(", ")); setComp((social.moderation?.competitorNames ?? []).join(", ")); } }, [ws.data]); // eslint-disable-line react-hooks/exhaustive-deps
  if (!ws.data) return <Spinner />;
  const ai = social.ai ?? {};
  const setAi = (p: Record<string, unknown>) => save({ ai: { ...ai, ...p } });
  return (
    <div className="space-y-4">
      <Card title="AI autopilot" subtitle="Replies are grounded in the knowledge base. Complaints and legal threats are never answered publicly by AI.">
        <div className="space-y-3 text-[13px]">
          <Toggle checked={!!ai.autopilot} onChange={(v) => setAi({ autopilot: v })} label="Send confident AI replies automatically (others go to Approvals)" />
          <Toggle checked={ai.publicReplies !== false} onChange={(v) => setAi({ publicReplies: v })} label="Allow AI to reply publicly on comments" />
          <Toggle checked={ai.classify !== false} onChange={(v) => setAi({ classify: v })} label="AI classification of intent & sentiment (rules-based fallback always on)" />
          <Field label={`Confidence threshold: ${Math.round((ai.threshold ?? 0.8) * 100)}%`}><input type="range" min={50} max={100} step={5} defaultValue={Math.round((ai.threshold ?? 0.8) * 100)} onMouseUp={(e) => setAi({ threshold: Number((e.target as HTMLInputElement).value) / 100 })} onTouchEnd={(e) => setAi({ threshold: Number((e.target as HTMLInputElement).value) / 100 })} className="w-full accent-brand" /></Field>
          <Field label="Intents autopilot may answer (none selected = all safe intents)"><div className="flex flex-wrap gap-1.5">{INTENTS.filter((i) => !["complaint", "legal", "spam"].includes(i)).map((i) => { const on = (ai.allowedIntents ?? []).includes(i); return <button key={i} type="button" onClick={() => setAi({ allowedIntents: on ? ai.allowedIntents.filter((x: string) => x !== i) : [...(ai.allowedIntents ?? []), i] })} className={`rounded-full border px-2 py-0.5 text-[12px] ${on ? "border-violet bg-violet/10 text-violet" : "border-line"}`}>{intentLabel(i)}</button>; })}</div></Field>
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Reply language"><Select value={ai.languageMode ?? "match"} onChange={(e) => setAi({ languageMode: e.target.value })}><option value="match">Match the customer</option><option value="bangla">Always Bangla</option><option value="english">Always English</option></Select></Field>
            <Field label="When the customer writes Banglish"><Select value={ai.banglishReply ?? "banglish"} onChange={(e) => setAi({ banglishReply: e.target.value })}><option value="banglish">Reply in Banglish</option><option value="bangla">Reply in Bangla script</option></Select></Field>
          </div>
          <p className="text-[12px] text-ink-3">Manage answers in the <Link href="/inbox/knowledge" className="text-brand">knowledge base</Link> · review drafts in <Link href="/ai/approvals" className="text-brand">Approvals</Link>.</p>
        </div>
      </Card>
      <Card title="Moderation lists" subtitle="Used by moderation rules (profanity condition) alongside the built-in English / Bangla / Banglish list.">
        <div className="space-y-3">
          <Field label="Extra blocked words (comma separated)"><Textarea rows={2} value={words} onChange={(e) => setWords(e.target.value)} /></Field>
          <Field label="Competitor names"><Input value={comp} onChange={(e) => setComp(e.target.value)} /></Field>
          <div className="text-right"><Button variant="primary" onClick={() => save({ moderation: { blockedWords: words.split(",").map((s) => s.trim()).filter(Boolean), competitorNames: comp.split(",").map((s) => s.trim()).filter(Boolean) } })}>Save lists</Button></div>
        </div>
      </Card>
    </div>
  );
}

function SavedReplies() {
  const list = useApi<{ data: { id: string; shortcut: string; title: string | null; body: string; channels: string[]; language: string; variables: string[] }[] }>("/saved-replies");
  const [edit, setEdit] = useState<Record<string, any> | null>(null);
  const { busy, run } = useAction();
  const save = () => run(async () => {
    const body = { title: edit!.title, shortcut: edit!.shortcut, body: edit!.body, channels: edit!.channels ?? [], language: edit!.language ?? "en", tags: [] };
    if (edit!.id) await api(`/saved-replies/${edit!.id}`, { method: "PATCH", body }); else await api("/saved-replies", { body });
    setEdit(null); list.reload();
  }, "Saved reply stored");
  const del = (id: string) => run(async () => { await api(`/saved-replies/${id}`, { method: "DELETE" }); list.reload(); }, "Deleted");
  return (
    <Card title="Saved replies" subtitle="Type / in any reply box. Variables: {{first_name}}, {{project_name}}, {{workspace}}" actions={<Button size="sm" variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setEdit({ shortcut: "/", channels: [], language: "en" })}>New</Button>} bodyClass="p-0">
      {!list.data ? <div className="p-4"><Spinner /></div> : !list.data.data.length ? <div className="p-4"><Empty icon={<MessageSquarePlus className="h-5 w-5" />} title="No saved replies" /></div> : (
        <ul className="divide-y divide-line/60">{list.data.data.map((s) => <li key={s.id} className="flex items-start gap-3 px-4 py-2.5 text-[13px]"><code className="shrink-0 rounded bg-sunken px-1.5 text-[12px]">{s.shortcut}</code><button className="min-w-0 flex-1 text-left" onClick={() => setEdit(s)}><div className="font-medium">{s.title ?? s.shortcut}</div><div className="line-clamp-1 text-ink-3">{s.body}</div><div className="mt-0.5 text-[11px] text-ink-3">{s.channels.length ? s.channels.map((c) => CHANNEL_LABEL[c] ?? c).join(", ") : "All channels"} · {s.language}</div></button><button onClick={() => del(s.id)} aria-label="Delete"><Trash2 className="h-4 w-4 text-ink-3 hover:text-bad" /></button></li>)}</ul>
      )}
      {edit && (
        <Sheet open onClose={() => setEdit(null)} title={edit.id ? "Edit saved reply" : "New saved reply"} width={480} footer={<div className="flex justify-end gap-2"><Button onClick={() => setEdit(null)}>Cancel</Button><Button variant="primary" loading={busy} onClick={save}>Save</Button></div>}>
          <div className="space-y-3">
            <div className="grid gap-3 sm:grid-cols-2"><Field label="Title"><Input value={edit.title ?? ""} onChange={(e) => setEdit({ ...edit, title: e.target.value })} /></Field><Field label="Shortcut"><Input value={edit.shortcut ?? "/"} onChange={(e) => setEdit({ ...edit, shortcut: e.target.value })} /></Field></div>
            <Field label="Reply"><Textarea rows={5} value={edit.body ?? ""} onChange={(e) => setEdit({ ...edit, body: e.target.value })} /></Field>
            <Field label="Language"><Select value={edit.language ?? "en"} onChange={(e) => setEdit({ ...edit, language: e.target.value })}><option value="en">English</option><option value="bn">Bangla</option><option value="banglish">Banglish</option></Select></Field>
            <Field label="Channels (none = all)"><div className="flex flex-wrap gap-1.5">{Object.keys(CHANNEL_LABEL).map((c) => { const on = (edit.channels ?? []).includes(c); return <button key={c} type="button" onClick={() => setEdit({ ...edit, channels: on ? edit.channels.filter((x: string) => x !== c) : [...(edit.channels ?? []), c] })} className={`rounded-full border px-2 py-0.5 text-[12px] ${on ? "border-brand bg-brand/10 text-brand" : "border-line"}`}>{CHANNEL_LABEL[c]}</button>; })}</div></Field>
          </div>
        </Sheet>
      )}
    </Card>
  );
}

function TeamRouting() {
  const users = useApi<{ data: { u: { id: string; name: string; email: string }; m: { team: string | null; availability: string; socialAccountIds: string[] }; role: { name: string } }[] }>("/users");
  const accounts = useApi<{ data: Account[] }>("/social/accounts");
  const { push } = useUI();
  const patch = async (id: string, body: Record<string, unknown>) => { try { await api(`/users/${id}`, { method: "PATCH", body }); users.reload(); } catch (e) { push("error", (e as Error).message); } };
  if (users.error) return <p className="text-[13px] text-ink-3">Only admins can change team routing.</p>;
  return (
    <Card title="Teams, availability & account access" subtitle="Round-robin skips agents marked away. Restrict agents to specific pages (empty = all accounts)." bodyClass="p-0">
      {!users.data ? <div className="p-4"><Spinner /></div> : (
        <ul className="divide-y divide-line/60">
          {users.data.data.map(({ u, m, role }) => (
            <li key={u.id} className="flex flex-wrap items-center gap-3 px-4 py-3 text-[13px]">
              <div className="min-w-[160px] flex-1"><div className="font-medium">{u.name}</div><div className="text-[11.5px] text-ink-3">{role.name}</div></div>
              <Input className="w-[120px]" placeholder="Team" defaultValue={m.team ?? ""} onBlur={(e) => e.target.value !== (m.team ?? "") && patch(u.id, { team: e.target.value || null })} aria-label="Team" />
              <Toggle checked={m.availability !== "away"} onChange={(v) => patch(u.id, { availability: v ? "online" : "away" })} label={m.availability === "away" ? "Away" : "Available"} />
              <div className="flex flex-wrap gap-2">{accounts.data?.data.map((a) => <Checkbox key={a.id} checked={m.socialAccountIds.includes(a.id)} onChange={(v) => patch(u.id, { social_account_ids: v ? [...m.socialAccountIds, a.id] : m.socialAccountIds.filter((x) => x !== a.id) })} label={<span className="text-[12px]">{a.name}</span>} />)}</div>
              {m.socialAccountIds.length > 0 && <button className="text-[11.5px] text-ink-3" onClick={() => patch(u.id, { social_account_ids: [] })}><X className="inline h-3 w-3" />all accounts</button>}
            </li>
          ))}
        </ul>
      )}
    </Card>
  );
}
