import type { Dispatch, SetStateAction } from "react";
import type { MachineFormState } from "@/components/network-admin-client-config";
import { readNetworkAdminError } from "@/components/network-admin-mutation-helpers";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

type NetworkAdminCreateMachineFormProps = {
  busy: boolean;
  venueId: string;
  machineForm: MachineFormState;
  setMachineForms: Dispatch<SetStateAction<Record<string, MachineFormState>>>;
  emptyMachineForm: MachineFormState;
  runMutation: (task: () => Promise<void>, successMessage: string) => Promise<void>;
};

export function NetworkAdminCreateMachineForm({
  busy,
  venueId,
  machineForm,
  setMachineForms,
  emptyMachineForm,
  runMutation,
}: NetworkAdminCreateMachineFormProps) {
  return (
    <div className="mt-3 grid gap-3 md:grid-cols-[1.4fr_1fr_auto]">
      <Input
        value={machineForm.label}
        onChange={(event) =>
          setMachineForms((current) => ({ ...current, [venueId]: { ...machineForm, label: event.target.value } }))
        }
        placeholder="Machine label"
        disabled={busy}
      />
      <label className="flex h-9 items-center gap-3 rounded-md border border-input bg-card/70 px-3 text-sm">
        <input
          type="checkbox"
          checked={machineForm.active}
          onChange={(event) =>
            setMachineForms((current) => ({ ...current, [venueId]: { ...machineForm, active: event.target.checked } }))
          }
          disabled={busy}
        />
        active
      </label>
      <Button
        loading={busy}
        disabled={busy || machineForm.label.trim().length === 0}
        onClick={() =>
          runMutation(async () => {
            const response = await fetch(`/api/network/venues/${venueId}/vending-machines`, {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify(machineForm),
            });

            if (!response.ok) throw new Error(await readNetworkAdminError(response));
            setMachineForms((current) => ({ ...current, [venueId]: emptyMachineForm }));
          }, "Vending machine created")
        }
      >
        Add machine
      </Button>
    </div>
  );
}
