"use client";

import { useActionState } from "react";
import { FormField } from "@/components/admin/FormField";
import { ImageUploadField } from "@/components/admin/ImageUploadField";
import type { GalleryFormState } from "@/app/(admin-group)/admin/galleries/actions";
import type { Gallery } from "@/generated/prisma/client";

interface GalleryFormProps {
  action: (
    state: GalleryFormState,
    formData: FormData
  ) => Promise<GalleryFormState>;
  gallery?: Gallery;
  submitLabel: string;
}

export function GalleryForm({
  action,
  gallery,
  submitLabel,
}: GalleryFormProps) {
  const [state, formAction, isPending] = useActionState<
    GalleryFormState,
    FormData
  >(action, undefined);

  return (
    <form action={formAction} className="space-y-5">
      <FormField
        label="Judul Foto (opsional)"
        name="title"
        defaultValue={gallery?.title ?? ""}
      />

      <FormField
        label="Kategori (opsional)"
        name="category"
        defaultValue={gallery?.category ?? ""}
      />

      <ImageUploadField
        name="image"
        label="Gambar"
        defaultImageUrl={gallery?.imageUrl}
        required
      />

      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <FormField
          label="Urutan Tampil"
          name="sortOrder"
          type="number"
          defaultValue={gallery?.sortOrder ?? 0}
        />
        <div className="flex items-center gap-2 pt-6">
          <input
            id="isFeatured"
            name="isFeatured"
            type="checkbox"
            defaultChecked={gallery?.isFeatured ?? false}
            className="h-4 w-4 rounded border-gray-300 text-merah-ranata focus:ring-merah-ranata"
          />
          <label htmlFor="isFeatured" className="text-sm text-heading">
            Tampilkan sebagai unggulan
          </label>
        </div>
      </div>

      {state?.message && (
        <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">
          {state.message}
        </p>
      )}

      <button
        type="submit"
        disabled={isPending}
        className="rounded-full bg-merah-ranata px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-merah-hover disabled:opacity-60"
      >
        {isPending ? "Menyimpan..." : submitLabel}
      </button>
    </form>
  );
}
