"use client";

import Link from "next/link";
import { useId, useMemo, useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { addDpaItemAction, addScheduledTaskAction, deleteDpaItemAction, deleteScheduledTaskAction, saveCountriesAction } from "@/lib/actions/organizations";
import { useRun } from "@/components/features/accounts/use-run";
import { EdField, IconBtn, Modal, Pill, Switch, edInput, pillClass } from "@/components/features/page-editor/ed-ui";
import { cn } from "@/lib/utils";
import { Pager, SearchBox, SettingsFrame, usePaging } from "./ed-table";

const fmt = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-GB", { timeZone: "UTC", dateStyle: "medium", timeStyle: "short" }) + " UTC" : "Never");
const th = "px-3 py-3 text-left text-xs font-bold text-[var(--ed-ink)]";
const td = "px-3 py-3 text-[var(--ed-ink)]";

function Status({ msg }: { msg: { ok: boolean; text: string } | null }) {
  return <p role="status" aria-live="polite" className={cn("text-xs font-bold", msg ? (msg.ok ? "text-[#0f7a55]" : "text-[#b91c1c]") : "sr-only")}>{msg?.text}</p>;
}

/** Delete with a visible two-step confirmation (no browser dialogs). */
function RowDelete({ label, disabled, onDelete }: { label: string; disabled?: boolean; onDelete: () => void }) {
  const [armed, setArmed] = useState(false);
  return armed ? (
    <span className="inline-flex gap-1">
      <Pill variant="pink" disabled={disabled} onClick={() => { setArmed(false); onDelete(); }}>Delete</Pill>
      <Pill variant="grey" onClick={() => setArmed(false)}>Cancel</Pill>
    </span>
  ) : (
    <IconBtn label={`Delete ${label}`} disabled={disabled} onClick={() => setArmed(true)}><Trash2 className="size-4" aria-hidden /></IconBtn>
  );
}

function Empty({ cols }: { cols: number }) {
  return <tr><td colSpan={cols} className="px-3 py-8 text-center text-[var(--ed-soft)]">No data available in table</td></tr>;
}

// ------------------------------------------------------------------ countries
export function CountriesManager({ orgId, orgName, base, countries }: { orgId: string; orgName: string; base: string; countries: { code: string; standard: string; enabled: boolean; name: string }[]; tableMissing: boolean }) {
  const { pending, msg, run } = useRun();
  const [draft, setDraft] = useState(() => Object.fromEntries(countries.map((c) => [c.code, { enabled: c.enabled, name: c.name }])));
  const [saved, setSaved] = useState(draft);
  const [q, setQ] = useState("");
  const rows = useMemo(() => { const n = q.trim().toLowerCase(); return countries.filter((c) => !n || `${c.code} ${c.standard} ${draft[c.code]?.name ?? ""}`.toLowerCase().includes(n)); }, [q, countries, draft]);
  const paging = usePaging(rows);
  const changed = countries.filter((c) => draft[c.code]?.enabled !== saved[c.code]?.enabled || draft[c.code]?.name !== saved[c.code]?.name);
  const idp = useId();
  const submit = () => run(() => saveCountriesAction(orgId, changed.map((c) => ({ code: c.code, enabled: draft[c.code]?.enabled ?? true, name: draft[c.code]?.name ?? "" }))), () => setSaved(draft));
  return (
    <SettingsFrame orgName={orgName} title={`${orgName} · countries`} actions={<Link href={`${base}?tab=translations`} className={pillClass("outline", "py-2.5")}>Client level translations</Link>}>
      <div className="space-y-3 rounded-2xl bg-white p-5">
        <div className="flex flex-wrap items-center gap-3">
          <SearchBox value={q} onChange={setQ} label="Search countries" />
          <p className="text-xs text-[var(--ed-soft)]">Hide a country from the lists on this organization&apos;s websites, or change how its name is shown.</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-sm">
            <caption className="sr-only">Countries</caption>
            <thead><tr className="border-b border-[var(--ed-line)]"><th scope="col" className={th}>Code</th><th scope="col" className={th}>Standard name</th><th scope="col" className={th}>Shown as</th><th scope="col" className={th}>Available</th></tr></thead>
            <tbody>
              {paging.slice.map((c) => {
                const d = draft[c.code] ?? { enabled: true, name: "" };
                return (
                  <tr key={c.code} className="border-b border-[var(--ed-line)]">
                    <td className={td}>{c.code}</td>
                    <td className={td}>{c.standard}</td>
                    <td className="min-w-56 px-3 py-2">
                      <label className="sr-only" htmlFor={`${idp}-${c.code}`}>Display name for {c.standard}</label>
                      <input id={`${idp}-${c.code}`} value={d.name} maxLength={120} placeholder={c.standard} onChange={(e) => setDraft((s) => ({ ...s, [c.code]: { ...d, name: e.target.value } }))} className={cn(edInput, "rounded-xl")} />
                    </td>
                    <td className="px-3 py-2"><Switch checked={d.enabled} label={`${c.standard} available`} onChange={(v) => setDraft((s) => ({ ...s, [c.code]: { ...d, enabled: v } }))} /></td>
                  </tr>
                );
              })}
              {rows.length === 0 ? <tr><td colSpan={4} className="px-3 py-8 text-center text-[var(--ed-soft)]">No countries match your search.</td></tr> : null}
            </tbody>
          </table>
        </div>
        <Pager paging={paging} label="countries" />
      </div>
      <div role="region" aria-label="Country actions" className="sticky bottom-0 z-30 flex items-center justify-end gap-3 rounded-3xl bg-[var(--ed-dark)] px-4 py-3 text-white shadow-xl">
        <div className="flex-1 text-xs" aria-live="polite">{msg ? <span className={cn("font-bold", msg.ok ? "text-[#9be7c9]" : "text-[#ffb4c8]")}>{msg.text}</span> : changed.length ? <span className="font-bold text-[#ffe08a]">{changed.length} unsaved change{changed.length === 1 ? "" : "s"}</span> : null}</div>
        <Pill variant="green" disabled={pending || changed.length === 0} onClick={submit}>{pending ? "Saving…" : "Submit"}</Pill>
      </div>
    </SettingsFrame>
  );
}

// ------------------------------------------------------------------ DPA
type Kind = "SECTOR" | "CONTACT_TYPE" | "SCOPE";
const OPTION_GROUPS: { kind: Kind; heading: string; add: string }[] = [
  { kind: "SECTOR", heading: "Trade / Consumer", add: "Add Sector" },
  { kind: "CONTACT_TYPE", heading: "Email", add: "Add Contact Type" },
  { kind: "SCOPE", heading: "Client", add: "Add Scope" },
];

interface DpaProps {
  orgId: string; orgName: string; tableMissing: boolean;
  groups: { id: string; name: string; questions: number }[];
  questions: { id: string; name: string; group: string }[];
  options: { id: string; kind: Kind; name: string }[];
}
type Adding = { entity: "group" } | { entity: "question" } | { entity: "option"; kind: Kind; label: string } | null;

export function DpaManager({ orgId, orgName, groups, questions, options }: DpaProps) {
  const { pending, msg, run } = useRun();
  const [adding, setAdding] = useState<Adding>(null);
  const [name, setName] = useState("");
  const [groupId, setGroupId] = useState("");
  const [gq, setGq] = useState("");
  const [qq, setQq] = useState("");
  const gRows = useMemo(() => groups.filter((g) => g.name.toLowerCase().includes(gq.trim().toLowerCase())), [groups, gq]);
  const qRows = useMemo(() => questions.filter((x) => `${x.name} ${x.group}`.toLowerCase().includes(qq.trim().toLowerCase())), [questions, qq]);
  const gPaging = usePaging(gRows);
  const qPaging = usePaging(qRows);
  const idp = useId();
  const del = (entity: string, id: string) => run(() => deleteDpaItemAction(orgId, entity, id));
  const close = () => { setAdding(null); setName(""); setGroupId(""); };
  const submit = () => {
    if (!adding) return;
    const body = adding.entity === "group" ? { entity: "group", name } : adding.entity === "question" ? { entity: "question", name, ...(groupId ? { groupId } : {}) } : { entity: "option", kind: adding.kind, name };
    run(() => addDpaItemAction(orgId, body), close);
  };
  const title = adding?.entity === "group" ? "Add DPA group" : adding?.entity === "question" ? "Add DPA question" : adding?.label ?? "";
  return (
    <SettingsFrame orgName={orgName} title="DPA Settings">
      <Status msg={msg} />
      <section aria-labelledby={`${idp}-g`} className="space-y-3 rounded-2xl bg-white p-5">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <h3 id={`${idp}-g`} className="text-lg font-bold text-[var(--ed-ink)]">DPA Groups</h3>
          <Pill variant="outline" className="py-2.5" onClick={() => setAdding({ entity: "group" })}><Plus className="size-3.5" aria-hidden /> Add DPA group</Pill>
        </div>
        <SearchBox value={gq} onChange={setGq} label="Search DPA groups" />
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-sm">
            <caption className="sr-only">DPA groups</caption>
            <thead><tr className="border-b border-[var(--ed-line)]"><th scope="col" className={th}>Name</th><th scope="col" className={th}>Questions</th><th scope="col" className={cn(th, "w-32")}><span className="sr-only">Actions</span></th></tr></thead>
            <tbody>
              {gPaging.slice.map((g) => <tr key={g.id} className="border-b border-[var(--ed-line)]"><td className={td}>{g.name}</td><td className={td}>{g.questions}</td><td className="px-3 py-2 text-right"><RowDelete label={g.name} disabled={pending} onDelete={() => del("group", g.id)} /></td></tr>)}
              {gRows.length === 0 ? <Empty cols={3} /> : null}
            </tbody>
          </table>
        </div>
        <Pager paging={gPaging} label="DPA groups" />
      </section>

      <section aria-labelledby={`${idp}-q`} className="space-y-3 rounded-2xl bg-white p-5">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <h3 id={`${idp}-q`} className="text-lg font-bold text-[var(--ed-ink)]">DPA Questions</h3>
          <Pill variant="outline" className="py-2.5" onClick={() => setAdding({ entity: "question" })}><Plus className="size-3.5" aria-hidden /> Add DPA question</Pill>
        </div>
        <SearchBox value={qq} onChange={setQq} label="Search DPA questions" />
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-sm">
            <caption className="sr-only">DPA questions</caption>
            <thead><tr className="border-b border-[var(--ed-line)]"><th scope="col" className={th}>Name</th><th scope="col" className={th}>Group</th><th scope="col" className={cn(th, "w-32")}><span className="sr-only">Actions</span></th></tr></thead>
            <tbody>
              {qPaging.slice.map((x) => <tr key={x.id} className="border-b border-[var(--ed-line)]"><td className={td}>{x.name}</td><td className={td}>{x.group || "—"}</td><td className="px-3 py-2 text-right"><RowDelete label={x.name} disabled={pending} onDelete={() => del("question", x.id)} /></td></tr>)}
              {qRows.length === 0 ? <Empty cols={3} /> : null}
            </tbody>
          </table>
        </div>
        <Pager paging={qPaging} label="DPA questions" />
      </section>

      <section aria-labelledby={`${idp}-o`} className="space-y-4 rounded-2xl bg-white p-5">
        <h3 id={`${idp}-o`} className="text-lg font-bold text-[var(--ed-ink)]">DPA Options</h3>
        <div className="grid gap-4 md:grid-cols-3">
          {OPTION_GROUPS.map((og) => {
            const items = options.filter((o) => o.kind === og.kind);
            return (
              <div key={og.kind} className="space-y-2 rounded-xl border border-[var(--ed-line)] p-4">
                <h4 className="text-sm font-bold text-[var(--ed-ink)]">{og.heading}</h4>
                <ul className="space-y-1 text-sm text-[var(--ed-ink)]">
                  {items.length === 0 ? <li className="text-[var(--ed-soft)]">None yet</li> : items.map((o) => <li key={o.id} className="flex items-center justify-between gap-2"><span>{o.name}</span><RowDelete label={o.name} disabled={pending} onDelete={() => del("option", o.id)} /></li>)}
                </ul>
                <Pill variant="outline" onClick={() => setAdding({ entity: "option", kind: og.kind, label: og.add })}><Plus className="size-3.5" aria-hidden /> {og.add}</Pill>
              </div>
            );
          })}
        </div>
      </section>

      {adding ? (
        <Modal title={title} onClose={close}>
          <form className="space-y-4 px-8 pb-8" onSubmit={(e) => { e.preventDefault(); submit(); }}>
            <EdField id={`${idp}-name`} label="Name: *"><input id={`${idp}-name`} value={name} onChange={(e) => setName(e.target.value)} maxLength={200} required className={cn(edInput, "rounded-xl")} autoComplete="off" /></EdField>
            {adding.entity === "question" ? (
              <EdField id={`${idp}-grp`} label="Group:">
                <select id={`${idp}-grp`} value={groupId} onChange={(e) => setGroupId(e.target.value)} className={cn(edInput, "rounded-xl")}>
                  <option value="">- None -</option>
                  {groups.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
                </select>
              </EdField>
            ) : null}
            <Status msg={msg} />
            <div className="flex justify-end"><Pill type="submit" variant="dark" className="min-w-28 py-3" disabled={pending || !name.trim()}>{pending ? "Saving…" : "Submit"}</Pill></div>
          </form>
        </Modal>
      ) : null}
    </SettingsFrame>
  );
}

// ------------------------------------------------------------------ scheduled tasks
interface TaskProps {
  orgId: string; orgName: string; tableMissing: boolean;
  sites: { id: string; name: string }[];
  types: { id: string; label: string }[];
  tasks: { id: string; website: string; type: string; lastRan: string | null; created: string }[];
}

export function ScheduledTasksManager({ orgId, orgName, sites, types, tasks }: TaskProps) {
  const { pending, msg, run } = useRun();
  const [open, setOpen] = useState(false);
  const [siteId, setSiteId] = useState("");
  const [type, setType] = useState("");
  const [q, setQ] = useState("");
  const rows = useMemo(() => tasks.filter((t) => `${t.website} ${t.type}`.toLowerCase().includes(q.trim().toLowerCase())), [tasks, q]);
  const paging = usePaging(rows);
  const idp = useId();
  const close = () => { setOpen(false); setSiteId(""); setType(""); };
  return (
    <SettingsFrame orgName={orgName} title="Scheduler" actions={<Pill variant="outline" className="py-2.5" disabled={sites.length === 0} onClick={() => setOpen(true)}>Add scheduled task</Pill>}>
      <Status msg={msg} />
      <div className="space-y-3 rounded-2xl bg-white p-5">
        <SearchBox value={q} onChange={setQ} label="Search scheduled tasks" />
        {sites.length === 0 ? <p className="text-sm text-[var(--ed-soft)]">Add a website to this organization before scheduling tasks.</p> : null}
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-sm">
            <caption className="sr-only">Scheduled tasks</caption>
            <thead><tr className="border-b border-[var(--ed-line)]"><th scope="col" className={th}>Website</th><th scope="col" className={th}>Type</th><th scope="col" className={th}>Last ran</th><th scope="col" className={th}>Date created</th><th scope="col" className={cn(th, "w-32")}><span className="sr-only">Actions</span></th></tr></thead>
            <tbody>
              {paging.slice.map((t) => (
                <tr key={t.id} className="border-b border-[var(--ed-line)]">
                  <td className={td}>{t.website}</td><td className={td}>{t.type}</td><td className={td}>{fmt(t.lastRan)}</td><td className={td}>{fmt(t.created)}</td>
                  <td className="px-3 py-2 text-right"><RowDelete label={`${t.type} for ${t.website}`} disabled={pending} onDelete={() => run(() => deleteScheduledTaskAction(orgId, t.id))} /></td>
                </tr>
              ))}
              {rows.length === 0 ? <Empty cols={5} /> : null}
            </tbody>
          </table>
        </div>
        <Pager paging={paging} label="scheduled tasks" />
      </div>
      {open ? (
        <Modal title="New scheduled task" onClose={close}>
          <form className="space-y-4 px-8 pb-8" onSubmit={(e) => { e.preventDefault(); run(() => addScheduledTaskAction(orgId, { siteId, type }), close); }}>
            <EdField id={`${idp}-site`} label="Site: *">
              <select id={`${idp}-site`} value={siteId} onChange={(e) => setSiteId(e.target.value)} required className={cn(edInput, "rounded-xl")}>
                <option value="">- Select -</option>
                {sites.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </EdField>
            <EdField id={`${idp}-type`} label="Type: *">
              <select id={`${idp}-type`} value={type} onChange={(e) => setType(e.target.value)} required className={cn(edInput, "rounded-xl")}>
                <option value="">- Select -</option>
                {types.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
              </select>
            </EdField>
            <Status msg={msg} />
            <div className="flex justify-end"><Pill type="submit" variant="dark" className="min-w-28 py-3" disabled={pending || !siteId || !type}>{pending ? "Saving…" : "Submit"}</Pill></div>
          </form>
        </Modal>
      ) : null}
    </SettingsFrame>
  );
}
