"use client";

import { useActionState } from "react";
import { updateSiteSettings } from "@/lib/actions/admin";

export function SiteSettingsForm({
  settings,
}: {
  settings: { key: string; label: string; value: string }[];
}) {
  const [state, formAction, isPending] = useActionState(
    updateSiteSettings,
    undefined,
  );

  return (
    <form action={formAction} className="flex flex-col gap-4">
      <div className="grid gap-4 sm:grid-cols-2">
        {settings.map(({ key, label, value }) => (
          <label key={key} className="flex flex-col gap-1">
            <span className="text-sm font-medium text-charcoal">{label}</span>
            <input
              type="text"
              name={key}
              defaultValue={value}
              required
              className="rounded border border-charcoal/20 bg-warm-white px-4 py-2 text-charcoal"
            />
          </label>
        ))}
      </div>

      <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 thresholds"}
      </button>
      {state?.error && <p className="text-sm text-terracotta">{state.error}</p>}
      {state?.success && <p className="text-sm text-charcoal/60">Saved.</p>}
    </form>
  );
}
