"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { Badge, Button, Card } from "@/components/ui";
import { submitForApprovalAction } from "@/lib/actions/approvals";

const LABEL = { PENDING: "Awaiting approval", APPROVED: "Approved", ACTION_REQUIRED: "Action required", DECLINED: "Declined" } as const;
const TONE = { PENDING: "warning", APPROVED: "success", ACTION_REQUIRED: "info", DECLINED: "danger" } as const;

/** Sits under the entry editor: shows the latest moderation result and lets the author send the entry to the Approvals queue. */
export function EntryApproval({ siteId, entryId, current, exhibitors }: { siteId: string; entryId: string; current: { status: keyof typeof LABEL; comment: string } | null; exhibitors: { id: string; title: string }[] }) {
  const router = useRouter();
  const [exhibitor, setExhibitor] = useState("");
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [pending, start] = useTransition();
  const waiting = current?.status === "PENDING";
  return (
    <Card className="mt-6 p-4" >
      <h2 className="text-sm font-semibold">Approval</h2>
      {current ? <p className="mt-2 text-sm"><Badge tone={TONE[current.status]}>{LABEL[current.status]}</Badge>{current.comment ? <span className="ml-2 text-muted-foreground">“{current.comment}”</span> : null}</p> : <p className="mt-1 text-sm text-muted-foreground">Not submitted. Approving an entry publishes it.</p>}
      {!waiting ? (
        <div className="mt-3 flex flex-wrap items-end gap-3">
          {exhibitors.length ? (
            <div>
              <label htmlFor="ap-exhibitor" className="block text-xs font-medium">On behalf of exhibitor <span className="font-normal text-muted-foreground">(optional)</span></label>
              <select id="ap-exhibitor" className="mt-1 rounded-md border border-border bg-card px-3 py-2 text-sm" value={exhibitor} onChange={(e) => setExhibitor(e.target.value)}>
                <option value="">None</option>
                {exhibitors.map((x) => <option key={x.id} value={x.id}>{x.title}</option>)}
              </select>
            </div>
          ) : null}
          <Button variant="secondary" disabled={pending} onClick={() => start(async () => { const r = await submitForApprovalAction(siteId, { entryId, exhibitorId: exhibitor || null }); setMsg({ ok: r.ok, text: r.ok ? (r.message ?? "Sent") : r.error }); if (r.ok) router.refresh(); })}>Submit for approval</Button>
        </div>
      ) : null}
      <p role="status" aria-live="polite" className={msg ? (msg.ok ? "mt-2 text-sm text-success" : "mt-2 text-sm text-danger") : "sr-only"}>{msg?.text}</p>
    </Card>
  );
}
