"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { cloneLibraryAction, setLibraryActiveAction } from "@/lib/actions/modules";
import { buttonClass } from "@/components/ui/button";

const item = "block w-full rounded px-3 py-1.5 text-left text-sm hover:bg-muted";

/** ShowOff-style split button: "View Entries" plus a dropdown with Edit, Clone and Delete (super admin) for one library. */
export function LibraryRowActions({ base, siteId, typeKey, name, superAdmin }: { base: string; siteId: string; typeKey: string; name: string; superAdmin: boolean }) {
  const router = useRouter();
  const [armed, setArmed] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);
  const [pending, start] = useTransition();
  const clone = () => start(async () => { const r = await cloneLibraryAction(siteId, typeKey); if (r.ok && r.data) router.push(`/dashboard/modules/${r.data.key}`); else if (!r.ok) setMsg(r.error); });
  const remove = () => start(async () => { const r = await setLibraryActiveAction(siteId, typeKey, false); if (r.ok) router.refresh(); else { setMsg(r.error); setArmed(false); } });
  return (
    <div className="flex flex-col items-end gap-1">
      <div className="inline-flex">
        <Link href={`${base}/libraries/${typeKey}`} className={buttonClass("grey", superAdmin ? "rounded-r-none" : undefined)} aria-label={`View entries of ${name}`}>View Entries</Link>
        {superAdmin ? (
          <details className="relative" onToggle={(e) => { if (!(e.currentTarget as HTMLDetailsElement).open) setArmed(false); }}>
            <summary aria-label={`More actions for ${name}`} className={buttonClass("grey", "w-10 cursor-pointer list-none rounded-l-none border-l border-black/10 px-0")}>▾</summary>
            <div className="absolute right-0 z-10 mt-1 w-44 rounded-md border border-border bg-card p-1 shadow-md">
              <Link href={`/dashboard/modules/${typeKey}`} className={item}>Edit</Link>
              <button type="button" className={item} disabled={pending} onClick={clone}>Clone</button>
              {armed ? (
                <div className="flex gap-1 p-1"><button type="button" className={buttonClass("danger", "h-8 px-3 text-xs")} disabled={pending} onClick={remove}>Confirm delete</button><button type="button" className={buttonClass("ghost", "h-8 px-3 text-xs")} onClick={() => setArmed(false)}>Cancel</button></div>
              ) : <button type="button" className={item} onClick={() => setArmed(true)}>Delete</button>}
            </div>
          </details>
        ) : null}
      </div>
      {msg ? <p role="alert" className="max-w-56 text-right text-xs text-danger">{msg}</p> : null}
    </div>
  );
}
