"use client";

import { useState, useTransition } from "react";
import StaffForm from "@/components/staff/StaffForm";
import type { StaffPayload } from "@/lib/api/staff";
import type { StaffPermissionTemplate } from "@/lib/api/types";
import { updateStaff } from "./actions";

type Props = {
  id: number;
  template: StaffPermissionTemplate;
  initial: Partial<StaffPayload> & { permission: StaffPermissionTemplate };
};

/**
 * A thin client shell around the shared `StaffForm`, which is controlled and
 * takes an `onSubmit` callback — so the page cannot post to a Server Action
 * directly. This is the whole of what stays client-side on this route: the
 * template and the staff record are fetched during SSR and handed down as props.
 *
 * `useTransition` keeps the submit disabled while the action runs, replacing the
 * `busy` flag; the error banner lives here because that is where the action's
 * result lands.
 */
export default function StaffEditForm({ id, template, initial }: Props) {
  const [pending, startTransition] = useTransition();
  const [err, setErr] = useState<string | null>(null);

  const submit = (payload: StaffPayload) =>
    new Promise<void>((resolve) => {
      setErr(null);
      startTransition(async () => {
        const r = await updateStaff(id, payload);
        if (!r.ok) setErr(r.message ?? "Failed to update staff");
        resolve();
      });
    });

  return (
    <>
      {err && <div className="rounded-lg bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200">{err}</div>}

      <StaffForm
        template={template}
        initial={initial}
        submitLabel="Save changes"
        onSubmit={submit}
        busy={pending}
        passwordOptional
      />
    </>
  );
}
