import { useState } from "react";
import { Pencil } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { updateDeskCopy } from "@/lib/server/api-academy";
import { useRoleStore } from "@/lib/role-store";

type Table = "teams" | "courses" | "game_days" | "capstone_seats" | "member_profiles";

/** Pencil only Super Admin (operator) sees — even while previewing Public / Donor / Student / Instructor. */
export function StaffEditField({
  table,
  id,
  field,
  value,
  label,
  onSaved,
}: {
  table: Table;
  id: string;
  field: string;
  value: string | null | undefined;
  label: string;
  onSaved?: () => void | Promise<void>;
}) {
  const can = useRoleStore((s) => s.operatorRole === "staff");
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState(value ?? "");
  const [busy, setBusy] = useState(false);
  if (!can || !id) return null;

  async function save() {
    setBusy(true);
    try {
      await updateDeskCopy({ data: { table, id, field, value: draft } });
      toast.success(`Saved ${label}.`);
      setOpen(false);
      await onSaved?.();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not save.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <>
      <Button
        type="button"
        size="sm"
        variant="gold"
        className="shrink-0"
        onClick={() => {
          setDraft(value ?? "");
          setOpen(true);
        }}
      >
        <Pencil className="size-3.5" />
        Edit
      </Button>
      <Dialog open={open} onOpenChange={setOpen}>
        {open ? (
          <DialogContent title={`Edit ${label}`} description="Super Admin copy. This is the live desk text.">
            <Label htmlFor={`desk-${id}-${field}`}>{label}</Label>
            <Textarea
              id={`desk-${id}-${field}`}
              className="mt-1 min-h-32"
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
            />
            <div className="mt-3 flex justify-end gap-2">
              <Button variant="outline" onClick={() => setOpen(false)}>
                Cancel
              </Button>
              <Button variant="gold" disabled={busy} onClick={() => void save()}>
                {busy ? "Saving…" : "Save"}
              </Button>
            </div>
          </DialogContent>
        ) : null}
      </Dialog>
    </>
  );
}