"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { confirmReceipt } from "./actions";
import { FileUploader } from "@/components/po/file-uploader";
import { uploadAndLinkFiles } from "@/lib/upload-files";

export function ReceiptForm({ poId }: { poId: string }) {
  const router = useRouter();
  const [notes, setNotes] = useState("");
  const [files, setFiles] = useState<File[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    const result = await confirmReceipt({ poId, notes });
    if ("error" in result) {
      setError(result.error);
      setSubmitting(false);
      return;
    }
    if (files.length > 0) {
      const uploadErr = await uploadAndLinkFiles(poId, files, "receipt");
      if (uploadErr) {
        setError(uploadErr.error);
        setSubmitting(false);
        return;
      }
    }
    router.push(`/po/${poId}`);
    router.refresh();
  }

  return (
    <div className="rounded-lg border border-neutral-200 bg-white p-6">
      <form onSubmit={handleSubmit} className="space-y-4">
        <p className="text-sm text-neutral-600">
          Confirming receipt will close this purchase order. Please verify that all
          items have been received before proceeding.
        </p>

        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-1.5">
            Delivery notes (optional)
          </label>
          <textarea
            rows={4}
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            className="w-full rounded-lg border border-neutral-300 px-3 py-2.5 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 resize-none"
            placeholder="Any notes about the delivery…"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-1.5">
            Attachments (optional)
          </label>
          <FileUploader files={files} onChange={setFiles} disabled={submitting} />
        </div>

        {error && (
          <p className="text-sm text-danger-700 bg-danger-50 rounded-lg px-3 py-2">{error}</p>
        )}

        <div className="flex gap-3">
          <button
            type="button"
            onClick={() => router.back()}
            className="rounded-lg border border-neutral-300 bg-white px-4 py-2.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50 transition-colors"
          >
            Cancel
          </button>
          <button
            type="submit"
            disabled={submitting}
            className="rounded-lg bg-success px-4 py-2.5 text-sm font-semibold text-white hover:opacity-90 disabled:opacity-60 transition-opacity"
          >
            {submitting ? "Confirming…" : "Confirm Receipt & Close PO"}
          </button>
        </div>
      </form>
    </div>
  );
}
