"use client";
/** Engagement rules (SOC-050…058): builder + dry-run test panel. Moderation rules always run before replies. */
import Link from "next/link";
import { useState } from "react";
import { ArrowLeft, FlaskConical, Plus, Trash2, Wand2 } from "lucide-react";
import { Badge, Button, Card, Checkbox, Empty, Field, Input, PageHeader, Segmented, Select, Sheet, Spinner, Textarea, Toggle, api, useAction, useUI } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";
import { CHANNEL_LABEL, INTENTS, intentLabel } from "@/components/social";

type Action = { type: string; config?: Record<string, any> };
type Rule = {
  id: string; name: string; type: string; channels: string[]; socialAccountIds: string[]; socialObjectIds: string[]; trigger: string; conditions: Record<string, any>; actions: Action[];
  priority: number; stopProcessing: boolean; isActive: boolean; schedule: Record<string, any>; rateLimit: Record<string, any>; stats: Record<string, any>;
};
const TYPES: Record<string, string> = { auto_reply: "Auto-reply", comment_to_dm: "Comment → DM", moderation: "Moderation", routing: "Routing", ai_autopilot: "AI autopilot", alert: "Alert" };
const ACTIONS: Record<string, string> = {
  public_reply: "Public reply / message", private_reply: "Private reply (DM the commenter)", hide: "Hide comment", like: "Like comment", tag: "Add tags", assign: "Assign (round-robin)", set_priority: "Set priority",
  create_lead: "Create lead", start_journey: "Start journey", notify: "Notify team", send_whatsapp_template: "Send WhatsApp template", ai_reply: "AI reply (autopilot / approval)", mark_spam: "Mark spam", block_author: "Block author",
};
const SOCIAL_CHANNELS = ["facebook_comment", "instagram_comment", "youtube", "tiktok", "linkedin", "google_review", "whatsapp", "messenger", "instagram", "sms", "email"];
const blank = (): Rule => ({ id: "", name: "", type: "auto_reply", channels: [], socialAccountIds: [], socialObjectIds: [], trigger: "new_comment", conditions: { keywordMode: "any" }, actions: [{ type: "public_reply", config: { texts: [""] } }], priority: 100, stopProcessing: false, isActive: true, schedule: { mode: "always" }, rateLimit: { oncePerUserPerObject: true }, stats: {} });

export default function RulesPage() {
  const rules = useApi<{ data: Rule[] }>("/engagement-rules");
  const [edit, setEdit] = useState<Rule | null>(null);
  const [testOpen, setTestOpen] = useState(false);
  const { push } = useUI();
  const toggle = async (r: Rule) => { try { await api(`/engagement-rules/${r.id}`, { method: "PATCH", body: { is_active: !r.isActive } }); rules.reload(); } catch (e) { push("error", (e as Error).message); } };
  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 rules" subtitle="Automate replies, comment-to-DM, moderation, routing and alerts. Moderation runs first, then rules in priority order." actions={<><Button icon={<FlaskConical className="h-4 w-4" />} onClick={() => setTestOpen(true)}>Test rules</Button><Button variant="primary" icon={<Plus className="h-4 w-4" />} onClick={() => setEdit(blank())}>New rule</Button></>} />
      {!rules.data ? <Spinner /> : !rules.data.data.length ? <Empty icon={<Wand2 className="h-5 w-5" />} title="No rules yet" action={<Button variant="primary" onClick={() => setEdit(blank())}>Create your first rule</Button>}>Example: reply “price?” comments publicly and send the brochure by private reply.</Empty> : (
        <div className="space-y-2">
          {rules.data.data.map((r, i) => (
            <Card key={r.id} bodyClass="p-3">
              <div className="flex flex-wrap items-center gap-3">
                <span className="w-6 text-center text-[12px] text-ink-3">{i + 1}</span>
                <div className="min-w-0 flex-1">
                  <button className="text-left text-[14px] font-semibold hover:text-brand" onClick={() => setEdit(r)}>{r.name}</button>
                  <div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-[12px] text-ink-3">
                    <Badge tone={r.type === "moderation" ? "amber" : r.type === "ai_autopilot" ? "violet" : "gray"}>{TYPES[r.type] ?? r.type}</Badge>
                    <span>{r.trigger.replace("new_", "on ").replace("_", " ")}</span>
                    {r.conditions.keywords?.length > 0 && <span>· “{r.conditions.keywords.slice(0, 3).join("”, “")}”{r.conditions.keywords.length > 3 ? "…" : ""}</span>}
                    {r.conditions.intents?.length > 0 && <span>· {r.conditions.intents.map(intentLabel).join(", ")}</span>}
                    <span>→ {r.actions.map((a) => ACTIONS[a.type]?.split(" (")[0]).join(", ")}</span>
                    {r.stopProcessing && <Badge>stops</Badge>}
                    {r.schedule?.mode && r.schedule.mode !== "always" && <Badge tone="blue">{r.schedule.mode === "in_hours" ? "business hours" : "after hours"}</Badge>}
                  </div>
                </div>
                <div className="text-right text-[11.5px] text-ink-3"><div><b className="text-ink">{r.stats.fires ?? 0}</b> fires · {r.stats.replies ?? 0} replies · {r.stats.leads ?? 0} leads · {r.stats.hides ?? 0} hidden</div><div>{r.stats.lastFiredAt ? `last ${ago(r.stats.lastFiredAt)}` : "never fired"}</div></div>
                <Toggle checked={r.isActive} onChange={() => toggle(r)} label={<span className="sr-only">Active</span>} />
              </div>
            </Card>
          ))}
        </div>
      )}
      {edit && <RuleEditor rule={edit} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); rules.reload(); }} />}
      <TestPanel open={testOpen} onClose={() => setTestOpen(false)} />
    </div>
  );
}

function ListInput({ value, onChange, placeholder }: { value: string[] | undefined; onChange: (v: string[]) => void; placeholder: string }) {
  return <Input placeholder={placeholder} defaultValue={(value ?? []).join(", ")} onBlur={(e) => onChange(e.target.value.split(",").map((s) => s.trim()).filter(Boolean))} />;
}

function RuleEditor({ rule, onClose, onSaved }: { rule: Rule; onClose: () => void; onSaved: () => void }) {
  const [r, setR] = useState<Rule>(JSON.parse(JSON.stringify(rule)));
  const accounts = useApi<{ data: { id: string; name: string }[] }>("/social/accounts");
  const saved = useApi<{ data: { id: string; shortcut: string; title: string | null }[] }>("/saved-replies");
  const journeys = useApi<{ data: { id: string; name: string; status: string }[] }>("/journeys");
  const tpls = useApi<{ data: { id: string; name: string; providerStatus: string }[] }>("/templates?channel=whatsapp");
  const team = useApi<{ data: { id: string; name: string }[] }>("/team");
  const { busy, run } = useAction();
  const set = (p: Partial<Rule>) => setR((x) => ({ ...x, ...p }));
  const cond = (p: Record<string, any>) => setR((x) => ({ ...x, conditions: { ...x.conditions, ...p } }));
  const setAction = (i: number, a: Action) => setR((x) => ({ ...x, actions: x.actions.map((y, j) => (j === i ? a : y)) }));
  const save = () => run(async () => {
    const body = { name: r.name, type: r.type, channels: r.channels, social_account_ids: r.socialAccountIds, social_object_ids: r.socialObjectIds, trigger: r.trigger, conditions: Object.fromEntries(Object.entries(r.conditions).filter(([, v]) => v !== undefined && v !== "" && !(Array.isArray(v) && !v.length))), actions: r.actions.map((a) => ({ type: a.type, config: { ...a.config, ...(Array.isArray(a.config?.texts) ? { texts: a.config!.texts.filter((t: string) => t.trim()) } : {}) } })), priority: r.priority, stop_processing: r.stopProcessing, is_active: r.isActive, schedule: r.schedule, rate_limit: r.rateLimit };
    if (r.id) await api(`/engagement-rules/${r.id}`, { method: "PATCH", body });
    else await api("/engagement-rules", { body });
    onSaved();
  }, "Rule saved");
  const remove = () => run(async () => { if (!confirm("Delete this rule?")) return; await api(`/engagement-rules/${r.id}`, { method: "DELETE" }); onSaved(); }, "Rule deleted");

  return (
    <Sheet open onClose={onClose} title={r.id ? "Edit rule" : "New rule"} width={620} footer={<div className="flex gap-2">{r.id && <Button variant="ghost" icon={<Trash2 className="h-4 w-4" />} onClick={remove}>Delete</Button>}<div className="flex-1" /><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={save}>Save rule</Button></div>}>
      <div className="space-y-5">
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="Name"><Input value={r.name} onChange={(e) => set({ name: e.target.value })} placeholder="Price comments → DM brochure" /></Field>
          <Field label="Type"><Select value={r.type} onChange={(e) => set({ type: e.target.value })}>{Object.entries(TYPES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</Select></Field>
          <Field label="When"><Select value={r.trigger} onChange={(e) => set({ trigger: e.target.value })}><option value="new_comment">A new comment arrives</option><option value="new_dm">A new message (DM) arrives</option><option value="new_review">A new review arrives</option><option value="any">Anything arrives</option></Select></Field>
          <Field label="Priority" hint="Lower runs first"><Input type="number" value={r.priority} onChange={(e) => set({ priority: Number(e.target.value) })} /></Field>
        </div>
        <section className="space-y-2">
          <h3 className="text-[13px] font-semibold">Where</h3>
          <div className="flex flex-wrap gap-1.5">{SOCIAL_CHANNELS.map((c) => <button key={c} type="button" onClick={() => set({ channels: r.channels.includes(c) ? r.channels.filter((x) => x !== c) : [...r.channels, c] })} className={`rounded-full border px-2.5 py-1 text-[12px] ${r.channels.includes(c) ? "border-brand bg-brand/10 text-brand" : "border-line"}`}>{CHANNEL_LABEL[c]}</button>)}</div>
          <p className="text-[11.5px] text-ink-3">{r.channels.length ? "" : "All channels. "}Limit to accounts:</p>
          <div className="flex flex-wrap gap-3">{accounts.data?.data.map((a) => <Checkbox key={a.id} checked={r.socialAccountIds.includes(a.id)} onChange={(v) => set({ socialAccountIds: v ? [...r.socialAccountIds, a.id] : r.socialAccountIds.filter((x) => x !== a.id) })} label={a.name} />)}</div>
        </section>
        <section className="space-y-3">
          <h3 className="text-[13px] font-semibold">If (all conditions must match)</h3>
          <div className="grid gap-3 sm:grid-cols-[1fr_120px]"><Field label="Keywords (comma separated; English, Bangla or Banglish)"><ListInput value={r.conditions.keywords} onChange={(v) => cond({ keywords: v })} placeholder="price, dam koto, দাম, koto" /></Field><Field label="Match"><Select value={r.conditions.keywordMode ?? "any"} onChange={(e) => cond({ keywordMode: e.target.value })}><option value="any">Any word</option><option value="all">All words</option></Select></Field></div>
          <Field label="Intent"><div className="flex flex-wrap gap-1.5">{INTENTS.map((i) => { const on = (r.conditions.intents ?? []).includes(i); return <button key={i} type="button" onClick={() => cond({ intents: on ? r.conditions.intents.filter((x: string) => x !== i) : [...(r.conditions.intents ?? []), 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-3">
            <Field label="Sentiment"><Select value={r.conditions.sentiments?.[0] ?? ""} onChange={(e) => cond({ sentiments: e.target.value ? [e.target.value] : [] })}><option value="">Any</option><option value="negative">Negative</option><option value="neutral">Neutral</option><option value="positive">Positive</option></Select></Field>
            <Field label="Language"><Select value={r.conditions.languages?.[0] ?? ""} onChange={(e) => cond({ languages: e.target.value ? [e.target.value] : [] })}><option value="">Any</option><option value="en">English</option><option value="bn">Bangla</option><option value="banglish">Banglish</option></Select></Field>
            <Field label="Max rating (reviews)"><Select value={r.conditions.maxRating ?? ""} onChange={(e) => cond({ maxRating: e.target.value ? Number(e.target.value) : undefined })}><option value="">Any</option>{[1, 2, 3, 4].map((n) => <option key={n} value={n}>≤ {n}★</option>)}</Select></Field>
          </div>
          <div className="flex flex-wrap gap-4">
            <Checkbox checked={!!r.conditions.hasPhone} onChange={(v) => cond({ hasPhone: v || undefined })} label="Contains a phone number" />
            <Checkbox checked={!!r.conditions.hasLink} onChange={(v) => cond({ hasLink: v || undefined })} label="Contains a link" />
            <Checkbox checked={!!r.conditions.profanity} onChange={(v) => cond({ profanity: v || undefined })} label="Profanity / spam" />
            <Checkbox checked={!!r.conditions.firstMessageFromNewContact} onChange={(v) => cond({ firstMessageFromNewContact: v || undefined })} label="First message from a new contact" />
          </div>
          <Field label="Competitor names"><ListInput value={r.conditions.competitorNames} onChange={(v) => cond({ competitorNames: v })} placeholder="Competitor A, Competitor B" /></Field>
        </section>
        <section className="space-y-2">
          <h3 className="text-[13px] font-semibold">Then</h3>
          {r.actions.map((a, i) => (
            <div key={i} className="space-y-2 rounded-[10px] border border-line p-3">
              <div className="flex gap-2"><Select value={a.type} onChange={(e) => setAction(i, { type: e.target.value, config: e.target.value.endsWith("_reply") && e.target.value !== "ai_reply" ? { texts: [""] } : {} })}>{Object.entries(ACTIONS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</Select>{r.actions.length > 1 && <Button variant="ghost" aria-label="Remove action" icon={<Trash2 className="h-4 w-4" />} onClick={() => set({ actions: r.actions.filter((_, j) => j !== i) })} />}</div>
              {(a.type === "public_reply" || a.type === "private_reply") && (
                <div className="space-y-1.5">
                  <Select value={a.config?.savedReplyId ?? ""} onChange={(e) => setAction(i, { ...a, config: { ...a.config, savedReplyId: e.target.value || undefined } })}><option value="">Write reply variations…</option>{saved.data?.data.map((s) => <option key={s.id} value={s.id}>{s.shortcut} {s.title ?? ""}</option>)}</Select>
                  {!a.config?.savedReplyId && (a.config?.texts ?? [""]).map((t: string, k: number) => <Textarea key={k} rows={2} value={t} placeholder={k === 0 ? "Hi {{first_name}}! We've sent you the price list in a private message 📩" : "Variation (rotated to avoid spam filters)"} onChange={(e) => setAction(i, { ...a, config: { ...a.config, texts: (a.config?.texts ?? [""]).map((x: string, j: number) => (j === k ? e.target.value : x)) } })} />)}
                  {!a.config?.savedReplyId && <button type="button" className="text-[12px] text-brand" onClick={() => setAction(i, { ...a, config: { ...a.config, texts: [...(a.config?.texts ?? [""]), ""] } })}>+ Add variation</button>}
                </div>
              )}
              {a.type === "tag" && <ListInput value={a.config?.tags} onChange={(v) => setAction(i, { ...a, config: { ...a.config, tags: v } })} placeholder="price-inquiry, hot" />}
              {a.type === "assign" && <div className="grid gap-2 sm:grid-cols-2"><Input placeholder="Team (e.g. sales)" value={a.config?.team ?? ""} onChange={(e) => setAction(i, { ...a, config: { ...a.config, team: e.target.value || undefined } })} /><Select value={a.config?.userIds?.[0] ?? ""} onChange={(e) => setAction(i, { ...a, config: { ...a.config, userIds: e.target.value ? [e.target.value] : [] } })}><option value="">…or any available agent</option>{team.data?.data.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</Select></div>}
              {a.type === "set_priority" && <Segmented size="sm" value={a.config?.priority ?? "high"} onChange={(v) => setAction(i, { ...a, config: { priority: v } })} options={[{ value: "urgent", label: "Urgent" }, { value: "high", label: "High" }, { value: "normal", label: "Normal" }]} />}
              {a.type === "start_journey" && <Select value={a.config?.journeyId ?? ""} onChange={(e) => setAction(i, { ...a, config: { journeyId: e.target.value } })}><option value="">Choose a live journey…</option>{journeys.data?.data.filter((j) => j.status === "live").map((j) => <option key={j.id} value={j.id}>{j.name}</option>)}</Select>}
              {a.type === "send_whatsapp_template" && <Select value={a.config?.templateId ?? ""} onChange={(e) => setAction(i, { ...a, config: { templateId: e.target.value } })}><option value="">Choose an approved template…</option>{tpls.data?.data.filter((t) => t.providerStatus === "approved").map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}</Select>}
              {a.type === "notify" && <Input placeholder="Notification title (optional)" value={a.config?.title ?? ""} onChange={(e) => setAction(i, { ...a, config: { ...a.config, title: e.target.value } })} />}
              {a.type === "hide" && <Input placeholder="Reason (shown in the moderation log)" value={a.config?.reason ?? ""} onChange={(e) => setAction(i, { ...a, config: { ...a.config, reason: e.target.value } })} />}
              {a.type === "ai_reply" && <p className="text-[12px] text-ink-3">Uses the knowledge base. Sends automatically only when autopilot is on, confidence ≥ threshold and the message isn't a complaint — otherwise the draft goes to <Link className="text-brand" href="/ai/approvals">Approvals</Link>.</p>}
              {a.type === "private_reply" && <p className="text-[12px] text-ink-3">Facebook & Instagram only · one private reply per comment · within the platform window.</p>}
            </div>
          ))}
          <Button size="sm" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => set({ actions: [...r.actions, { type: "tag", config: { tags: [] } }] })}>Add action</Button>
        </section>
        <section className="space-y-3">
          <h3 className="text-[13px] font-semibold">Schedule & limits</h3>
          <Segmented size="sm" value={r.schedule.mode ?? "always"} onChange={(v) => set({ schedule: { ...r.schedule, mode: v } })} options={[{ value: "always", label: "Always" }, { value: "in_hours", label: "Business hours" }, { value: "out_of_hours", label: "After hours (away reply)" }]} />
          <div className="flex flex-wrap gap-4">
            <Checkbox checked={!!r.rateLimit.oncePerUserPerObject} onChange={(v) => set({ rateLimit: { ...r.rateLimit, oncePerUserPerObject: v } })} label="Once per person per post" />
            <Checkbox checked={!!r.rateLimit.oncePerUserPerDay} onChange={(v) => set({ rateLimit: { ...r.rateLimit, oncePerUserPerDay: v } })} label="Once per person per day" />
            <label className="flex items-center gap-2 text-[13px]">Max <Input type="number" className="w-20" value={r.rateLimit.perMinute ?? ""} onChange={(e) => set({ rateLimit: { ...r.rateLimit, perMinute: e.target.value ? Number(e.target.value) : undefined } })} /> per minute</label>
          </div>
          <div className="flex flex-wrap gap-4"><Toggle checked={r.stopProcessing} onChange={(v) => set({ stopProcessing: v })} label="Stop processing further rules" /><Toggle checked={r.isActive} onChange={(v) => set({ isActive: v })} label="Active" /></div>
        </section>
      </div>
    </Sheet>
  );
}

function TestPanel({ open, onClose }: { open: boolean; onClose: () => void }) {
  const [text, setText] = useState("Price koto? 3 bed er");
  const [trigger, setTrigger] = useState("new_comment");
  const [channel, setChannel] = useState("facebook_comment");
  const [rating, setRating] = useState(5);
  const [out, setOut] = useState<any>(null);
  const { busy, run } = useAction();
  const test = () => run(async () => { const r = await api<{ data: any }>("/engagement-rules/test", { body: { text, trigger, channel, rating: trigger === "new_review" ? rating : undefined, new_contact: true } }); setOut(r.data); });
  return (
    <Sheet open={open} onClose={onClose} title="Test rules" width={520}>
      <div className="space-y-3">
        <p className="text-[12.5px] text-ink-3">Simulate an incoming item. Nothing is sent — you see the classification and what each rule would do.</p>
        <div className="grid gap-2 sm:grid-cols-2">
          <Select value={trigger} onChange={(e) => setTrigger(e.target.value)}><option value="new_comment">Comment</option><option value="new_dm">Direct message</option><option value="new_review">Review</option></Select>
          <Select value={channel} onChange={(e) => setChannel(e.target.value)}>{SOCIAL_CHANNELS.map((c) => <option key={c} value={c}>{CHANNEL_LABEL[c]}</option>)}</Select>
        </div>
        {trigger === "new_review" && <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>}
        <Textarea rows={3} value={text} onChange={(e) => setText(e.target.value)} />
        <Button variant="primary" loading={busy} onClick={test} icon={<FlaskConical className="h-4 w-4" />}>Run test</Button>
        {out && (
          <div className="space-y-3 pt-2">
            <div className="flex flex-wrap gap-1.5 text-[12px]"><Badge tone="violet">{intentLabel(out.classification.intent)}</Badge><Badge tone={out.classification.sentiment === "negative" ? "red" : out.classification.sentiment === "positive" ? "green" : "gray"}>{out.classification.sentiment}</Badge><Badge>{out.classification.language}</Badge>{out.classification.phones.length > 0 && <Badge tone="blue">phone: {out.classification.phones.join(", ")}</Badge>}{out.classification.spam && <Badge tone="red">spam</Badge>}{out.classification.profanity && <Badge tone="red">profanity</Badge>}</div>
            {!out.matched.length ? <p className="text-[13px] text-ink-3">No rule matches — it would land in the inbox for a human.</p> : out.matched.map((m: any) => (
              <div key={m.ruleId} className="rounded-[10px] border border-line p-2.5 text-[13px]"><div className="font-semibold">{m.ruleName}{m.stopped && <span className="ml-1 text-[11px] font-normal text-ink-3">(stops here)</span>}</div><ul className="mt-1 list-disc pl-5 text-ink-2">{m.actions.map((a: any, i: number) => <li key={i}>{a.detail ?? a.type}</li>)}</ul></div>
            ))}
          </div>
        )}
      </div>
    </Sheet>
  );
}
