"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { saveLibrarySettingsAction } from "@/lib/actions/content";
import { setLibraryActiveAction } from "@/lib/actions/modules";
import { Modal } from "./modal";

export interface LibraryBarProps {
  siteId: string; base: string; typeKey: string; name: string; description: string; singular: string; fieldCount: number; total: number;
  isSuperAdmin: boolean; canManage: boolean;
  settings: { pageSize: number; orderBy: string };
  pageSizes: readonly number[]; orders: { key: string; label: string }[];
}

const seg = (on: boolean) => `inline-flex h-9 min-w-12 items-center justify-center px-3 text-sm font-medium ${on ? "bg-success text-white" : "bg-muted text-muted-foreground"}`;

/** ShowOff-style bar under the entries list: library key, Active switch and the Library Options dialog. */
export function LibraryBar(p: LibraryBarProps) {
  const uid = useId();
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [tab, setTab] = useState<"general" | "display">("general");
  const [pageSize, setPageSize] = useState(p.settings.pageSize);
  const [orderBy, setOrderBy] = useState(p.settings.orderBy);
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [confirmOff, setConfirmOff] = useState(false);
  const [pending, start] = useTransition();

  const saveOptions = () => start(async () => {
    const r = await saveLibrarySettingsAction({ siteId: p.siteId, typeKey: p.typeKey, pageSize, orderBy });
    setMsg({ ok: r.ok, text: r.ok ? (r.message ?? "Saved") : r.error });
    if (r.ok) router.refresh();
  });
  const turnOff = () => start(async () => {
    const r = await setLibraryActiveAction(p.siteId, p.typeKey, false);
    if (r.ok) router.push(`${p.base}/libraries`); else { setMsg({ ok: false, text: r.error }); setConfirmOff(false); }
  });

  return (
    <div className="sticky bottom-0 z-10 mt-6 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-card px-4 py-3 shadow-sm">
      <p className="text-sm text-muted-foreground">Library key: <span className="font-mono text-foreground">{p.typeKey}</span></p>
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex items-center gap-2 text-sm">
          <span id={`${uid}-active`}>Active:</span>
          <div role="group" aria-labelledby={`${uid}-active`} className="inline-flex overflow-hidden rounded-md border border-border">
            <span className={seg(true)} aria-current="true">Yes</span>
            {p.isSuperAdmin ? (
              confirmOff
                ? <button type="button" className={`${seg(false)} bg-danger text-white`} disabled={pending} onClick={turnOff}>Confirm No</button>
                : <button type="button" className={seg(false)} onClick={() => setConfirmOff(true)} aria-label="Set inactive: remove this library from this website">No</button>
            ) : <span className={seg(false)} title="Only a platform administrator can remove a library from a website">No</span>}
          </div>
          {confirmOff ? <Button variant="ghost" onClick={() => setConfirmOff(false)}>Cancel</Button> : null}
        </div>
        <Button variant="secondary" onClick={() => { setMsg(null); setOpen(true); }}>Library Options</Button>
      </div>
      {msg && !open ? <p role="status" aria-live="polite" className={`w-full text-sm ${msg.ok ? "text-success" : "text-danger"}`}>{msg.text}</p> : null}

      <Modal open={open} onClose={() => setOpen(false)} title="Library Options">
        <div role="tablist" aria-label="Library options" className="mb-4 flex gap-1 border-b border-border">
          {(["general", "display"] as const).map((t) => (
            <button key={t} type="button" role="tab" id={`${uid}-tab-${t}`} aria-selected={tab === t} aria-controls={`${uid}-panel-${t}`} onClick={() => setTab(t)} className={`-mb-px border-b-2 px-4 py-2 text-sm ${tab === t ? "border-primary font-medium text-primary" : "border-transparent text-muted-foreground"}`}>{t === "general" ? "General" : "Display"}</button>
          ))}
        </div>
        {tab === "general" ? (
          <div role="tabpanel" id={`${uid}-panel-general`} aria-labelledby={`${uid}-tab-general`} className="space-y-3">
            <dl className="grid gap-3 text-sm sm:grid-cols-2">
              <div><dt className="text-xs text-muted-foreground">Title</dt><dd className="font-medium">{p.name}</dd></div>
              <div><dt className="text-xs text-muted-foreground">Library key</dt><dd className="font-mono">{p.typeKey}</dd></div>
              <div><dt className="text-xs text-muted-foreground">Entry type</dt><dd>{p.singular}</dd></div>
              <div><dt className="text-xs text-muted-foreground">Entries / fields</dt><dd>{p.total} entries · {p.fieldCount} fields</dd></div>
              <div className="sm:col-span-2"><dt className="text-xs text-muted-foreground">Description</dt><dd>{p.description || "—"}</dd></div>
            </dl>
            {p.isSuperAdmin ? <p className="text-sm"><Link href={`/dashboard/modules/${p.typeKey}`} className="text-primary underline">Edit the title, description and fields of this library</Link></p> : <p className="text-xs text-muted-foreground">The title, description and fields are set by your platform administrator.</p>}
          </div>
        ) : (
          <div role="tabpanel" id={`${uid}-panel-display`} aria-labelledby={`${uid}-tab-display`} className="space-y-3">
            <Field id={`${uid}-size`} label="Entries per page" help="How many entries the list shows on one page."><select id={`${uid}-size`} className={inputClass} value={pageSize} disabled={!p.canManage} onChange={(e) => setPageSize(Number(e.target.value))}>{p.pageSizes.map((n) => <option key={n} value={n}>{n}</option>)}</select></Field>
            <Field id={`${uid}-order`} label="Order by" help="The order entries are listed in."><select id={`${uid}-order`} className={inputClass} value={orderBy} disabled={!p.canManage} onChange={(e) => setOrderBy(e.target.value)}>{p.orders.map((o) => <option key={o.key} value={o.key}>{o.label}</option>)}</select></Field>
            {!p.canManage ? <p className="text-xs text-muted-foreground">You can view these options; people who manage content can change them.</p> : null}
          </div>
        )}
        <div className="mt-5 flex items-center justify-between gap-3">
          <p role="status" aria-live="polite" className={msg ? (msg.ok ? "text-sm text-success" : "text-sm text-danger") : "sr-only"}>{msg?.text}</p>
          {tab === "display" && p.canManage ? <Button disabled={pending} onClick={saveOptions}>{pending ? "Saving…" : "Submit"}</Button> : <Button variant="secondary" onClick={() => setOpen(false)}>Close</Button>}
        </div>
      </Modal>
    </div>
  );
}
