"use client";

import { useRouter } from "next/navigation";
import { useId, useState, useTransition } from "react";
import { Badge, Button, Card } from "@/components/ui";
import { decideRapportAction, deleteRapportAction } from "@/lib/actions/approvals";
import { saveSiteSectionAction } from "@/lib/actions/site-admin";

export interface RapportItem { id: string; targetName: string; name: string; email: string; company: string; message: string; status: "PENDING" | "APPROVED" | "DECLINED"; createdAt: string }
export interface RapportOptions { enabled: boolean; notifyAdmin: boolean; captcha: boolean }
const LABEL = { PENDING: "Awaiting approval", APPROVED: "Approved", DECLINED: "Declined" } as const;
const TONE = { PENDING: "warning", APPROVED: "success", DECLINED: "danger" } as const;
const PER_PAGE = 10;
const selectCls = "w-full rounded-md border border-border bg-card px-3 py-2 text-sm";

/** ShowOff "Rapports": requests from visitors to meet someone, with Options for the request form. */
export function RapportsPanel({ siteId, rows, options, canDecide, canConfigure, publicPath }: { siteId: string; rows: RapportItem[]; options: RapportOptions; canDecide: boolean; canConfigure: boolean; publicPath: string }) {
  const uid = useId();
  const router = useRouter();
  const [tab, setTab] = useState<"requests" | "options">("requests");
  const [status, setStatus] = useState("PENDING");
  const [q, setQ] = useState("");
  const [page, setPage] = useState(0);
  const [armed, setArmed] = useState<string | null>(null);
  const [opts, setOpts] = useState(options);
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [pending, start] = useTransition();
  const count = (s: string) => rows.filter((r) => !s || r.status === s).length;
  const filtered = rows.filter((r) => (!status || r.status === status) && `${r.targetName} ${r.name} ${r.email} ${r.company} ${r.message}`.toLowerCase().includes(q.toLowerCase()));
  const shown = filtered.slice(page * PER_PAGE, page * PER_PAGE + PER_PAGE);
  const run = (f: () => Promise<{ ok: boolean; message?: string; error?: string }>) => start(async () => { const r = await f(); setMsg({ ok: r.ok, text: r.ok ? (r.message ?? "Saved") : (r.error ?? "Failed") }); setArmed(null); if (r.ok) router.refresh(); });
  const tabCls = (on: boolean) => `-mb-px border-b-2 px-4 py-2 text-sm font-medium ${on ? "border-primary text-foreground" : "border-transparent text-muted-foreground hover:text-foreground"}`;

  return (
    <>
      <div role="tablist" aria-label="Rapport sections" className="mb-4 flex gap-1 border-b border-border">
        <button role="tab" id={`${uid}-t1`} aria-selected={tab === "requests"} aria-controls={`${uid}-p1`} type="button" className={tabCls(tab === "requests")} onClick={() => setTab("requests")}>Rapports</button>
        <button role="tab" id={`${uid}-t2`} aria-selected={tab === "options"} aria-controls={`${uid}-p2`} type="button" className={tabCls(tab === "options")} onClick={() => setTab("options")}>Options</button>
      </div>
      <p role="status" aria-live="polite" className={msg ? (msg.ok ? "mb-3 text-sm text-success" : "mb-3 text-sm text-danger") : "sr-only"}>{msg?.text}</p>

      {tab === "requests" ? (
        <Card id={`${uid}-p1`} role="tabpanel" aria-labelledby={`${uid}-t1`}>
          <div className="flex flex-wrap items-center gap-2 border-b border-border p-3">
            <label htmlFor={`${uid}-q`} className="sr-only">Search rapports</label>
            <input id={`${uid}-q`} type="search" placeholder="Search…" className="w-full max-w-xs rounded-md border border-border bg-card px-3 py-2 text-sm sm:mr-auto" value={q} onChange={(e) => { setQ(e.target.value); setPage(0); }} />
            <label htmlFor={`${uid}-s`} className="sr-only">Status</label>
            <select id={`${uid}-s`} className="rounded-md border border-border bg-card px-3 py-2 text-sm" value={status} onChange={(e) => { setStatus(e.target.value); setPage(0); }}>
              <option value="PENDING">Awaiting Approval ({count("PENDING")})</option>
              <option value="">Any Status ({count("")})</option>
              <option value="APPROVED">Approved ({count("APPROVED")})</option>
            </select>
          </div>
          <table className="w-full text-left text-sm">
            <thead className="border-b border-border text-xs text-muted-foreground"><tr>{["Content", "Author", "Rapport request", "Date", "Status"].map((h) => <th key={h} scope="col" className="px-4 py-2 font-medium">{h}</th>)}<th scope="col" className="px-4 py-2"><span className="sr-only">Actions</span></th></tr></thead>
            <tbody className="divide-y divide-border">
              {shown.map((r) => (
                <tr key={r.id} className="align-top">
                  <td className="px-4 py-3 font-medium">{r.targetName}</td>
                  <td className="px-4 py-3">{r.name}<div className="text-xs text-muted-foreground"><a className="underline" href={`mailto:${r.email}`}>{r.email}</a>{r.company ? ` · ${r.company}` : ""}</div></td>
                  <td className="max-w-sm whitespace-pre-wrap px-4 py-3 text-muted-foreground">{r.message}</td>
                  <td className="px-4 py-3 text-muted-foreground">{new Date(r.createdAt).toLocaleDateString("en-GB", { timeZone: "UTC", day: "numeric", month: "short", year: "numeric" })}</td>
                  <td className="px-4 py-3"><Badge tone={TONE[r.status]}>{LABEL[r.status]}</Badge></td>
                  <td className="space-x-2 whitespace-nowrap px-4 py-3 text-right">
                    {canDecide && r.status === "PENDING" ? (<><Button variant="secondary" disabled={pending} onClick={() => run(() => decideRapportAction(siteId, { id: r.id, decision: "approve" }))}>Approve<span className="sr-only"> request from {r.name}</span></Button><Button variant="secondary" disabled={pending} onClick={() => run(() => decideRapportAction(siteId, { id: r.id, decision: "decline" }))}>Decline<span className="sr-only"> request from {r.name}</span></Button></>) : null}
                    {canDecide ? (armed === r.id ? (<><Button variant="danger" disabled={pending} onClick={() => run(() => deleteRapportAction(siteId, r.id))}>Confirm delete</Button><Button variant="secondary" onClick={() => setArmed(null)}>Cancel</Button></>) : <Button variant="secondary" onClick={() => setArmed(r.id)}>Delete<span className="sr-only"> request from {r.name}</span></Button>) : null}
                  </td>
                </tr>
              ))}
              {shown.length === 0 ? <tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">No data available in table</td></tr> : null}
            </tbody>
          </table>
          <div className="flex items-center justify-between border-t border-border p-3 text-xs text-muted-foreground">
            <span>{filtered.length ? `Showing ${page * PER_PAGE + 1} to ${Math.min(filtered.length, page * PER_PAGE + PER_PAGE)} of ${filtered.length} entries` : "Showing 0 to 0 of 0 entries"}</span>
            <span className="flex gap-1"><Button variant="secondary" disabled={page === 0} onClick={() => setPage((n) => n - 1)}>Previous</Button><Button variant="secondary" disabled={(page + 1) * PER_PAGE >= filtered.length} onClick={() => setPage((n) => n + 1)}>Next</Button></span>
          </div>
        </Card>
      ) : (
        <Card id={`${uid}-p2`} role="tabpanel" aria-labelledby={`${uid}-t2`} className="max-w-2xl p-5">
          <form className="space-y-5" onSubmit={(e) => { e.preventDefault(); run(() => saveSiteSectionAction(siteId, { section: "rapport", value: opts })); }}>
            <div>
              <label htmlFor={`${uid}-en`} className="block text-sm font-medium">Rapport enabled</label>
              <select id={`${uid}-en`} className={selectCls} disabled={!canConfigure} value={opts.enabled ? "1" : "0"} onChange={(e) => setOpts({ ...opts, enabled: e.target.value === "1" })}><option value="1">Enabled</option><option value="0">Disabled</option></select>
              <p className="mt-1 text-xs text-muted-foreground">The request form is at <code>{publicPath}</code> on your website. When disabled, that address and its submit endpoint return “not found”.</p>
            </div>
            <div>
              <label htmlFor={`${uid}-nt`} className="block text-sm font-medium">Rapport moderation notifications</label>
              <select id={`${uid}-nt`} aria-describedby={`${uid}-nt-h`} className={selectCls} disabled={!canConfigure} value={opts.notifyAdmin ? "1" : "0"} onChange={(e) => setOpts({ ...opts, notifyAdmin: e.target.value === "1" })}><option value="0">Disabled</option><option value="1">Enabled</option></select>
              <p id={`${uid}-nt-h`} className="mt-1 text-xs text-muted-foreground">Send an email to the notification address (SEO &amp; settings → Site settings → Email) when a rapport request needs approval.</p>
            </div>
            <div>
              <label htmlFor={`${uid}-cp`} className="block text-sm font-medium">Captcha enabled</label>
              <select id={`${uid}-cp`} aria-describedby={`${uid}-cp-h`} className={selectCls} disabled={!canConfigure} value={opts.captcha ? "1" : "0"} onChange={(e) => setOpts({ ...opts, captcha: e.target.value === "1" })}><option value="1">Enabled</option><option value="0">Disabled</option></select>
              <p id={`${uid}-cp-h`} className="mt-1 text-xs text-muted-foreground">Bot protection for the form: a hidden trap field, a signed page-load token and a minimum fill time. No third-party captcha is shown to visitors.</p>
            </div>
            {canConfigure ? <Button type="submit" disabled={pending}>Save</Button> : <p className="text-sm text-muted-foreground">You can view these options but not change them.</p>}
          </form>
        </Card>
      )}
    </>
  );
}
