"use client";

import { useActionState } from "react";
import { updateRejectionMessages } from "@/lib/actions/admin";
import { rejectionMessageSettingKey } from "@/lib/rejection-reasons";
import type { RejectionReason } from "@prisma/client";

export function RejectionMessagesForm({
  messages,
}: {
  messages: { reason: RejectionReason; label: string; message: string }[];
}) {
  const [state, formAction, isPending] = useActionState(
    updateRejectionMessages,
    undefined,
  );

  return (
    <form action={formAction} className="flex flex-col gap-5">
      {messages.map(({ reason, label, message }) => (
        <label key={reason} className="flex flex-col gap-1">
          <span className="text-sm font-medium text-charcoal">{label}</span>
          <textarea
            name={rejectionMessageSettingKey(reason)}
            defaultValue={message}
            rows={2}
            required
            className="rounded border border-charcoal/20 bg-warm-white px-4 py-2 text-charcoal"
          />
        </label>
      ))}

      <button
        type="submit"
        disabled={isPending}
        className="w-fit rounded-full bg-terracotta px-6 py-2 text-sm font-medium text-white hover:bg-terracotta/90 disabled:opacity-60"
      >
        {isPending ? "Saving..." : "Save messages"}
      </button>
      {state?.error && (
        <p className="text-sm text-terracotta">{state.error}</p>
      )}
      {state?.success && (
        <p className="text-sm text-charcoal/60">Saved.</p>
      )}
    </form>
  );
}
