"use client";

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

interface Vendor {
  id: string;
  name: string;
  vendorId: string | null;
}

export function VendorIdForm({ poId, vendors }: { poId: string; vendors: Vendor[] }) {
  const router = useRouter();
  const [selectedVendorId, setSelectedVendorId] = useState("");
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  const verifiedVendors = vendors.filter((v) => v.vendorId);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!selectedVendorId) { setError("Please select a vendor."); return; }
    setPending(true);
    setError("");
    const result = await provideVendorId({ poId, vendorId: selectedVendorId });
    if ("error" in result) { setError(result.error); setPending(false); }
    else { setPending(false); router.refresh(); }
  }

  return (
    <div className="rounded-lg border border-primary-100 bg-primary-50 p-5">
      <p className="text-sm font-medium text-primary-800 mb-3">
        A vendor ID is required before this PO can be approved. Select a verified vendor below.
      </p>
      <form onSubmit={handleSubmit} className="flex items-center gap-3">
        <select
          value={selectedVendorId}
          onChange={(e) => setSelectedVendorId(e.target.value)}
          className="flex-1 rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20"
        >
          <option value="">Select verified vendor…</option>
          {verifiedVendors.map((v) => (
            <option key={v.id} value={v.id}>
              {v.name} ({v.vendorId})
            </option>
          ))}
        </select>
        {error && <span className="text-xs text-danger-700">{error}</span>}
        <button
          type="submit"
          disabled={pending}
          className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60 transition-colors whitespace-nowrap"
        >
          {pending ? "Submitting…" : "Provide Vendor ID"}
        </button>
      </form>
      {verifiedVendors.length === 0 && (
        <p className="mt-2 text-xs text-primary-700">
          No verified vendors found. Ask an Admin to add one in the Vendor Registry.
        </p>
      )}
    </div>
  );
}
