"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { recordConsumption } from "../actions";

const INPUT = "rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none";

interface Props {
  siteId: string;
  products: { id: string; name: string; code: string }[];
}

export function ConsumptionForm({ siteId, products }: Props) {
  const router = useRouter();
  const [pending, setPending] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setPending(true); setSuccess(false); setError("");
    const fd = new FormData(e.currentTarget);
    fd.set("siteId", siteId);
    const result = await recordConsumption(fd);
    if ("error" in result) { setError(result.error); }
    else { setSuccess(true); (e.target as HTMLFormElement).reset(); router.refresh(); }
    setPending(false);
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-wrap items-end gap-3">
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Item *</label>
        <select name="productId" required className={INPUT + " w-56"}>
          <option value="">Select item…</option>
          {products.map((p) => (
            <option key={p.id} value={p.id}>{p.name}</option>
          ))}
        </select>
      </div>
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Date *</label>
        <input name="date" type="date" required defaultValue={new Date().toISOString().split("T")[0]} className={INPUT} />
      </div>
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Qty consumed *</label>
        <input name="quantity" type="number" step="any" min="0.001" required placeholder="e.g. 2" className={INPUT + " w-28"} />
      </div>
      <div className="flex-1">
        <label className="block text-xs font-medium text-neutral-700 mb-1">Note</label>
        <input name="note" className={INPUT + " w-full"} placeholder="Optional" />
      </div>
      <button type="submit" disabled={pending} className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">
        {pending ? "Saving…" : "Record"}
      </button>
      {success && <p className="text-sm text-success-700">Recorded.</p>}
      {error && <p className="text-sm text-danger-700">{error}</p>}
    </form>
  );
}
