"use client";

import { useActionState } from "react";
import type { ActionState } from "@/app/lib/definitions";
import { AdminField, FieldError, adminInputCls } from "@/app/admin/_components/ui";

type ProgramValues = {
  title?: string;
  description?: string;
  sortOrder?: number;
  published?: boolean;
};

export default function ProgramForm({
  action,
  initial,
  submitLabel,
}: {
  action: (
    prevState: ActionState | undefined,
    formData: FormData,
  ) => Promise<ActionState>;
  initial?: ProgramValues;
  submitLabel: string;
}) {
  const [state, formAction, pending] = useActionState(action, undefined);

  return (
    <form
      action={formAction}
      className="rounded-2xl border border-[#d9e2f7] bg-white p-5 sm:p-6 space-y-5 max-w-2xl"
    >
      <AdminField label="Title" name="title" error={state?.errors?.title?.[0]}>
        <input
          id="title"
          name="title"
          required
          defaultValue={initial?.title ?? ""}
          className={adminInputCls}
        />
      </AdminField>

      <AdminField
        label="Description"
        name="description"
        error={state?.errors?.description?.[0]}
      >
        <textarea
          id="description"
          name="description"
          required
          rows={5}
          defaultValue={initial?.description ?? ""}
          className={`${adminInputCls} resize-y`}
        />
      </AdminField>

      <AdminField
        label="Sort order"
        name="sortOrder"
        error={state?.errors?.sortOrder?.[0]}
      >
        <input
          id="sortOrder"
          name="sortOrder"
          type="number"
          min={0}
          defaultValue={initial?.sortOrder ?? 0}
          className={adminInputCls}
        />
      </AdminField>

      <label className="flex items-center gap-2 text-sm">
        <input
          type="checkbox"
          name="published"
          defaultChecked={initial?.published ?? true}
          className="accent-[#1f3fb8]"
        />
        Published on website
      </label>
      <FieldError message={state?.errors?.published?.[0]} />

      {state?.message && (
        <p className="text-sm text-red-600" role="alert">
          {state.message}
        </p>
      )}

      <button
        type="submit"
        disabled={pending}
        className="rounded-full bg-[#1f3fb8] px-6 py-2.5 text-sm font-semibold text-white hover:bg-[#18339a] disabled:opacity-60"
      >
        {pending ? "Saving..." : submitLabel}
      </button>
    </form>
  );
}
