"use client";

import { useState, useTransition } from "react";
import { Button, Card } from "@/components/ui";
import { saveRelatedPagesAction } from "@/lib/actions/site-admin";

type Link = { siteId: string; pageId: string };
export interface RelatedData {
  pages: { id: string; title: string; slug: string; links: Link[] }[];
  sites: { id: string; name: string; locale: string; pages: { id: string; title: string }[] }[];
}

/** ShowOff "Page Relationships": link a page to its counterpart on the organisation's other websites (for example other languages). */
export function RelatedPagesPanel({ siteId, data }: { siteId: string; data: RelatedData }) {
  const [rows, setRows] = useState(data.pages);
  const [open, setOpen] = useState<string | null>(null);
  const [draft, setDraft] = useState<Link[]>([]);
  const [pending, start] = useTransition();
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [q, setQ] = useState("");
  const [pageNo, setPageNo] = useState(0);
  const PER = 10;
  const filtered = rows.filter((r) => r.title.toLowerCase().includes(q.toLowerCase()));
  const shown = filtered.slice(pageNo * PER, pageNo * PER + PER);
  const siteName = (id: string) => data.sites.find((s) => s.id === id);

  if (data.sites.length === 0) return <Card className="p-4 text-sm text-muted-foreground">Related pages link a page to its counterpart on another website of the same organisation. This organisation has no other active website yet.</Card>;

  const edit = (id: string) => { setOpen(id); setDraft(rows.find((r) => r.id === id)?.links ?? []); setMsg(null); };
  const setLink = (sid: string, pageId: string) => setDraft((d) => [...d.filter((l) => l.siteId !== sid), ...(pageId ? [{ siteId: sid, pageId }] : [])]);
  const submit = () => {
    if (!open) return;
    start(async () => {
      const r = await saveRelatedPagesAction(siteId, { pageId: open, links: draft });
      if (r.ok) { setRows((rs) => rs.map((x) => (x.id === open ? { ...x, links: draft } : x))); setMsg({ ok: true, text: "Saved" }); setOpen(null); }
      else setMsg({ ok: false, text: r.error });
    });
  };

  return (
    <div className="space-y-3">
      <p role="status" aria-live="polite" className={msg ? (msg.ok ? "text-sm text-success" : "text-sm text-danger") : "sr-only"}>{msg?.text}</p>
      <Card>
        <div className="flex items-center justify-between gap-3 border-b border-border p-3">
          <h2 className="text-sm font-semibold">Page relationships</h2>
          <label className="text-sm">Search <input type="search" className="ml-1 rounded-md border border-border bg-card px-2 py-1 text-sm" value={q} onChange={(e) => { setQ(e.target.value); setPageNo(0); }} /></label>
        </div>
        <table className="w-full text-left text-sm">
          <thead className="border-b border-border text-xs text-muted-foreground"><tr><th className="px-4 py-2 font-medium">Page on this site</th><th className="px-4 py-2 font-medium">Related pages</th><th 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}>
                <td className="px-4 py-2">{r.title}</td>
                <td className="px-4 py-2 text-muted-foreground">{r.links.length ? r.links.map((l) => `${siteName(l.siteId)?.name ?? "Other site"}`).join(", ") : "—"}</td>
                <td className="px-4 py-2 text-right"><Button variant="secondary" onClick={() => edit(r.id)} aria-label={`Edit related pages for ${r.title}`}>Edit</Button></td>
              </tr>
            ))}
            {shown.length === 0 ? <tr><td colSpan={3} className="px-4 py-6 text-center text-muted-foreground">No pages found</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 ${pageNo * PER + 1} to ${Math.min(filtered.length, pageNo * PER + PER)} of ${filtered.length} entries` : "Showing 0 entries"}</span>
          <span className="flex gap-1">
            <Button variant="secondary" disabled={pageNo === 0} onClick={() => setPageNo((n) => n - 1)}>Previous</Button>
            <Button variant="secondary" disabled={(pageNo + 1) * PER >= filtered.length} onClick={() => setPageNo((n) => n + 1)}>Next</Button>
          </span>
        </div>
      </Card>
      {open ? (
        <Card className="space-y-3 p-4" role="group" aria-label="Edit related pages">
          <h3 className="text-sm font-semibold">Related pages for “{rows.find((r) => r.id === open)?.title}”</h3>
          <p className="text-xs text-muted-foreground">Pick the matching page on each other website. Search engines are told about them with hreflang links, using each website&apos;s language.</p>
          {data.sites.map((s) => (
            <div key={s.id} className="space-y-1">
              <label htmlFor={`rel-${s.id}`} className="block text-sm font-medium">{s.name} <span className="font-normal text-muted-foreground">({s.locale})</span></label>
              <select id={`rel-${s.id}`} className="w-full rounded-md border border-border bg-card px-3 py-2 text-sm" value={draft.find((l) => l.siteId === s.id)?.pageId ?? ""} onChange={(e) => setLink(s.id, e.target.value)}>
                <option value="">- None -</option>
                {s.pages.map((p) => <option key={p.id} value={p.id}>{p.title}</option>)}
              </select>
            </div>
          ))}
          <div className="flex gap-2"><Button onClick={submit} disabled={pending}>{pending ? "Saving…" : "Save"}</Button><Button variant="secondary" onClick={() => setOpen(null)}>Cancel</Button></div>
        </Card>
      ) : null}
    </div>
  );
}
