"use client";
import { useEffect, useState } from "react";
import { Copy, RefreshCw } from "lucide-react";
import { Button, Card, Field, Input, PageHeader, Select, Spinner, Textarea, Toggle, api, useAction, useUI } from "@/components/ui";
import { useApi } from "@/components/hooks";
import { INDUSTRIES, normalizeIndustry } from "@/lib/industry";
import { IndustrySelect, industryExamples } from "@/components/industry-select";

const TZ = ["Asia/Dhaka", "Asia/Kolkata", "Asia/Dubai", "Asia/Singapore", "Australia/Sydney", "Australia/Melbourne", "Australia/Perth", "Australia/Brisbane", "America/New_York", "America/Chicago", "America/Los_Angeles", "Europe/London", "UTC"];

export default function GeneralSettings() {
  const ws = useApi<{ data: any }>("/workspace");
  const [f, setF] = useState<any>(null);
  const { busy, run } = useAction();
  const { push, confirm } = useUI();
  useEffect(() => { if (ws.data) setF(structuredClone(ws.data.data)); }, [ws.data]);
  if (!f) return <Spinner />;
  const s = f.settings ?? {};
  const setS = (patch: any) => setF({ ...f, settings: { ...s, ...patch } });
  const save = () => run(async () => {
    await api("/workspace", { method: "PATCH", body: { name: f.name, timezone: f.timezone, currency: f.currency, locale: f.locale, settings: { quietHours: s.quietHours ?? { enabled: false, start: "21:00", end: "09:00" }, frequencyCap: s.frequencyCap ?? { enabled: false, perDay: 3 }, brandVoice: s.brandVoice ?? "", attributionModel: s.attributionModel ?? "last_touch", pacingThresholdPct: Number(s.pacingThresholdPct ?? 15), anomalyThresholdPct: Number(s.anomalyThresholdPct ?? 40), defaultCountryCode: s.defaultCountryCode ?? "880", visitLabel: s.visitLabel ?? "", dataRegion: s.dataRegion ?? "", webhookSecret: s.webhookSecret ?? undefined } } });
    ws.reload();
  }, "Settings saved");
  return (
    <>
      <PageHeader title="General" subtitle="All dates and money render in these workspace settings" actions={<Button variant="primary" loading={busy} onClick={save}>Save changes</Button>} />
      <IndustryCard current={normalizeIndustry(s.industry)} onApplied={() => ws.reload()} />
      <div className="grid gap-4 xl:grid-cols-2">
        <Card title="Workspace">
          <div className="grid gap-3 sm:grid-cols-2">
            <Field label="Name" className="sm:col-span-2"><Input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field>
            <Field label="Name of the booked step" hint="Optional — e.g. Site visit, Appointment, Test drive, Demo. Pipeline stage names are edited under Pipelines & routing."><Input value={s.visitLabel ?? ""} maxLength={40} onChange={(e) => setS({ visitLabel: e.target.value })} placeholder={INDUSTRIES[normalizeIndustry(s.industry)]!.visit} /></Field>
            <Field label="Timezone"><Select value={f.timezone} onChange={(e) => setF({ ...f, timezone: e.target.value })}>{[...new Set([f.timezone, ...TZ])].map((t) => <option key={t}>{t}</option>)}</Select></Field>
            <Field label="Currency"><Select value={f.currency} onChange={(e) => setF({ ...f, currency: e.target.value })}><option value="BDT">BDT — Bangladeshi taka</option><option value="USD">USD — US dollar</option><option value="AUD">AUD — Australian dollar</option></Select></Field>
            <Field label="Language"><Select value={f.locale} onChange={(e) => setF({ ...f, locale: e.target.value })}><option value="en">English</option><option value="bn">বাংলা (Bangla)</option></Select></Field>
            <Field label="Default phone country" hint="Used to normalise local numbers to E.164"><Select value={s.defaultCountryCode ?? "880"} onChange={(e) => setS({ defaultCountryCode: e.target.value })}><option value="880">Bangladesh (+880)</option><option value="61">Australia (+61)</option><option value="1">United States (+1)</option></Select></Field>
            <Field label="Data region" hint="Hosting region preference (open question in BRD — informational)"><Input value={s.dataRegion ?? ""} onChange={(e) => setS({ dataRegion: e.target.value })} placeholder="ap-southeast-1" /></Field>
          </div>
        </Card>
        <Card title="Messaging rules" subtitle="Applied to journeys, broadcasts and AI sends">
          <div className="space-y-4">
            <div>
              <Toggle checked={!!s.quietHours?.enabled} onChange={(v) => setS({ quietHours: { ...(s.quietHours ?? { start: "21:00", end: "09:00" }), enabled: v } })} label="Quiet hours (no automated sends)" />
              <div className="mt-2 flex items-center gap-2 text-[13px]"><input type="time" className="field w-auto" value={s.quietHours?.start ?? "21:00"} onChange={(e) => setS({ quietHours: { ...(s.quietHours ?? { enabled: true, end: "09:00" }), start: e.target.value } })} />to<input type="time" className="field w-auto" value={s.quietHours?.end ?? "09:00"} onChange={(e) => setS({ quietHours: { ...(s.quietHours ?? { enabled: true, start: "21:00" }), end: e.target.value } })} /><span className="text-ink-3">({f.timezone})</span></div>
            </div>
            <div>
              <Toggle checked={!!s.frequencyCap?.enabled} onChange={(v) => setS({ frequencyCap: { ...(s.frequencyCap ?? { perDay: 3 }), enabled: v } })} label="Frequency cap per contact" />
              <div className="mt-2 flex items-center gap-2 text-[13px]"><Input type="number" min="1" max="50" className="w-20" value={s.frequencyCap?.perDay ?? 3} onChange={(e) => setS({ frequencyCap: { ...(s.frequencyCap ?? { enabled: true }), perDay: Number(e.target.value) } })} />automated messages per 24 hours</div>
            </div>
          </div>
        </Card>
        <Card title="AI & analytics">
          <div className="space-y-3">
            <Field label="Brand voice" hint="Used by AI content generation in English and Bangla"><Textarea value={s.brandVoice ?? ""} onChange={(e) => setS({ brandVoice: e.target.value })} placeholder="e.g. Friendly, clear and trustworthy. No hype." /></Field>
            <div className="grid gap-3 sm:grid-cols-3">
              <Field label="Default attribution"><Select value={s.attributionModel ?? "last_touch"} onChange={(e) => setS({ attributionModel: e.target.value })}><option value="first_touch">First touch</option><option value="last_touch">Last touch</option><option value="linear">Linear</option><option value="time_decay">Time decay</option><option value="position_based">Position based</option></Select></Field>
              <Field label="Anomaly threshold (%)"><Input type="number" value={s.anomalyThresholdPct ?? 40} onChange={(e) => setS({ anomalyThresholdPct: e.target.value })} /></Field>
              <Field label="Pacing threshold (%)"><Input type="number" value={s.pacingThresholdPct ?? 15} onChange={(e) => setS({ pacingThresholdPct: e.target.value })} /></Field>
            </div>
          </div>
        </Card>
        <Card title="Inbound webhook" subtitle="Unique URL per workspace for leads and provider callbacks">
          <div className="space-y-3">
            <Field label="Base URL"><div className="flex gap-2"><Input readOnly className="font-mono text-[12px]" value={f.inboundWebhookBase} /><Button icon={<Copy className="h-3.5 w-3.5" />} onClick={() => { navigator.clipboard.writeText(f.inboundWebhookBase); push("ok", "Copied"); }}>Copy</Button></div></Field>
            <Field label="Generic webhook HMAC secret (optional)" hint="If set, generic lead webhooks must send X-Signature = hex(HMAC-SHA256(secret, raw body))"><Input value={s.webhookSecret ?? ""} onChange={(e) => setS({ webhookSecret: e.target.value })} /></Field>
            <Button icon={<RefreshCw className="h-3.5 w-3.5" />} onClick={async () => { if (await confirm({ title: "Rotate webhook key?", body: "All providers posting to the old URL will stop working until you update them.", danger: true, confirmLabel: "Rotate" })) { await api("/workspace/rotate-hook-key", { method: "POST" }); ws.reload(); push("ok", "Key rotated"); } }}>Rotate key</Button>
            <p className="text-[11.5px] text-ink-3">Tracking snippet key (public): <code>{f.slug}</code></p>
          </div>
        </Card>
      </div>
    </>
  );
}

/** Category-specific internal module: switching applies the industry pack without deleting data. */
function IndustryCard({ current, onApplied }: { current: string; onApplied: () => void }) {
  const [v, setV] = useState(current);
  const [pipeline, setPipeline] = useState(true);
  const [starters, setStarters] = useState(true);
  const { busy, run } = useAction();
  useEffect(() => setV(current), [current]);
  const p = INDUSTRIES[v]!;
  const apply = () => run(async () => {
    const r = await api<{ data: { pipeline: string; fields: number; knowledge: number; savedReplies: number } }>("/workspace/industry", { body: { industry: v, apply_pipeline: pipeline, add_starters: starters } });
    onApplied();
    return r;
  }, "Industry applied — funnel, fields, AI and starters updated");
  return (
    <Card title="Industry" subtitle="Shapes this workspace for its category: funnel stages, lead fields, AI agent questions and compliance rules, labels, starter knowledge base and saved replies" className="mb-4">
      <div className="grid gap-4 md:grid-cols-[1fr_1fr]">
        <div className="space-y-2">
          <IndustrySelect value={v} onChange={setV} />
          <p className="text-[12px] text-ink-3">{industryExamples(v)}</p>
          <Toggle checked={pipeline} onChange={setPipeline} label="Set up the funnel for this industry" />
          <Toggle checked={starters} onChange={setStarters} label="Add starter lead fields, knowledge-base questions and saved replies" />
          <Button variant="primary" loading={busy} onClick={apply} disabled={v === current && !pipeline && !starters}>{v === current ? "Re-apply industry setup" : "Switch & apply"}</Button>
          <p className="text-[11.5px] text-ink-3">Nothing is deleted. If the current pipeline already has deals, a new default pipeline is added and existing deals stay where they are.</p>
        </div>
        <div className="rounded-[10px] bg-sunken/70 p-3 text-[12.5px]">
          <div className="mb-1 font-semibold">Funnel</div>
          <div className="flex flex-wrap items-center gap-1">{["New", ...p.stages.map((x) => x[0]), p.wonLabel].map((n, i, a) => <span key={n} className="inline-flex items-center gap-1"><span className="rounded-full bg-panel px-2 py-0.5">{n}</span>{i < a.length - 1 && <span className="text-ink-3">→</span>}</span>)}</div>
          <div className="mb-1 mt-3 font-semibold">AI qualifies by asking</div>
          <p className="text-ink-2">{p.qualification.map((q) => q.label).join(" · ")}</p>
          <div className="mb-1 mt-3 font-semibold">Lead fields</div>
          <p className="text-ink-2">{p.fields.map((f) => f.label).join(" · ")}</p>
          {p.compliance && <><div className="mb-1 mt-3 font-semibold text-warn">Compliance guardrails{p.regulated ? " · regulated" : ""}</div><p className="text-ink-2">{p.compliance}</p></>}
        </div>
      </div>
    </Card>
  );
}
