"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";

interface LineItem {
  id: string;
  name: string;
  quantity: number;
  unit: string;
  deliveredQuantity: number | null;
}

interface Props {
  poId: string;
  lineItems: LineItem[];
  isPartiallyReceived: boolean;
  isPartiallyPaid?: boolean;
  paidAmount?: number;
  totalAmount?: number;
}

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

  // Per-item: how many are being delivered in this batch
  const [deliveries, setDeliveries] = useState<Record<string, number>>(() => {
    const init: Record<string, number> = {};
    for (const li of lineItems) {
      const remaining = li.quantity - (li.deliveredQuantity ?? 0);
      init[li.id] = remaining; // default: all remaining
    }
    return init;
  });

  function setDelivery(id: string, value: number) {
    const li = lineItems.find((l) => l.id === id)!;
    const remaining = li.quantity - (li.deliveredQuantity ?? 0);
    setDeliveries((prev) => ({ ...prev, [id]: Math.max(0, Math.min(value, remaining)) }));
  }

  function markAllRemaining() {
    const all: Record<string, number> = {};
    for (const li of lineItems) {
      all[li.id] = li.quantity - (li.deliveredQuantity ?? 0);
    }
    setDeliveries(all);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError("");

    const result = await confirmReceipt({ poId, notes, deliveries });
    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();
  }

  const allFullyDelivered = lineItems.every(
    (li) => (li.deliveredQuantity ?? 0) + (deliveries[li.id] ?? 0) >= li.quantity
  );
  const nothingDelivered = Object.values(deliveries).every((v) => v === 0);

  return (
    <div className="space-y-5">
      {/* Partial payment warning banner */}
      {isPartiallyPaid && (
        <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3">
          <p className="text-sm font-medium text-amber-800 mb-0.5">Payment not yet complete</p>
          <p className="text-sm text-amber-700">
            You can confirm received items now, but the PO will not be closed until full payment is made.
            {paidAmount != null && totalAmount != null && (
              <> Currently {paidAmount.toLocaleString("en-IN", { style: "currency", currency: "INR" })} of {totalAmount.toLocaleString("en-IN", { style: "currency", currency: "INR" })} has been paid.</>
            )}
          </p>
        </div>
      )}

      {/* Line items delivery tracker */}
      <div className="rounded-lg border border-neutral-200 bg-white overflow-hidden">
        <div className="px-4 py-3 border-b border-neutral-100 flex items-center justify-between">
          <h3 className="text-sm font-semibold text-neutral-800">Items to Receive</h3>
          <button
            type="button"
            onClick={markAllRemaining}
            className="text-xs text-primary-600 hover:text-primary-700 font-medium"
          >
            Mark all remaining
          </button>
        </div>
        <table className="w-full text-sm">
          <thead className="bg-neutral-50 border-b border-neutral-100">
            <tr>
              <th className="px-4 py-2.5 text-left font-medium text-neutral-600">Item</th>
              <th className="px-4 py-2.5 text-right font-medium text-neutral-600">Ordered</th>
              <th className="px-4 py-2.5 text-right font-medium text-neutral-600">Previously Received</th>
              <th className="px-4 py-2.5 text-right font-medium text-neutral-600">Remaining</th>
              <th className="px-4 py-2.5 text-right font-medium text-neutral-600">Receiving Now</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {lineItems.map((li) => {
              const prevDelivered = li.deliveredQuantity ?? 0;
              const remaining = li.quantity - prevDelivered;
              const nowDelivering = deliveries[li.id] ?? 0;
              const isFullyReceived = remaining <= 0;

              return (
                <tr key={li.id} className={isFullyReceived ? "bg-neutral-50" : ""}>
                  <td className="px-4 py-3 font-medium text-neutral-900">
                    {li.name}
                    {isFullyReceived && (
                      <span className="ml-2 text-xs text-success-600 font-normal">✓ fully received</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-right font-mono text-xs text-neutral-600">
                    {li.quantity} {li.unit}
                  </td>
                  <td className="px-4 py-3 text-right font-mono text-xs text-neutral-500">
                    {isPartiallyReceived || prevDelivered > 0 ? `${prevDelivered} ${li.unit}` : "—"}
                  </td>
                  <td className="px-4 py-3 text-right font-mono text-xs">
                    <span className={remaining > 0 ? "text-amber-700 font-medium" : "text-neutral-400"}>
                      {remaining > 0 ? `${remaining} ${li.unit}` : "—"}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-right">
                    {isFullyReceived ? (
                      <span className="text-xs text-neutral-400">—</span>
                    ) : (
                      <input
                        type="number"
                        min={0}
                        max={remaining}
                        step="any"
                        value={nowDelivering}
                        onChange={(e) => setDelivery(li.id, parseFloat(e.target.value) || 0)}
                        className="w-24 rounded border border-neutral-300 px-2 py-1 text-right text-sm font-mono focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500/30"
                      />
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="rounded-lg border border-neutral-200 bg-white p-5">
        <form onSubmit={handleSubmit} className="space-y-4">
          {allFullyDelivered ? (
            <p className="text-sm text-success-700 bg-success-50 border border-success-100 rounded-lg px-3 py-2">
              All items will be marked as received. Confirming will fully close this PO.
            </p>
          ) : (
            <p className="text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
              Not all items are being received. The PO will remain open as &ldquo;Partially Received&rdquo; until
              all items are delivered.
            </p>
          )}

          <div>
            <label className="block text-sm font-medium text-neutral-700 mb-1.5">
              Delivery notes (optional)
            </label>
            <textarea
              rows={3}
              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 this delivery batch…"
            />
          </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 || nothingDelivered}
              className={`rounded-lg px-4 py-2.5 text-sm font-semibold text-white disabled:opacity-60 transition-opacity ${
                allFullyDelivered
                  ? "bg-success hover:opacity-90"
                  : "bg-primary-600 hover:bg-primary-700"
              }`}
            >
              {submitting
                ? "Confirming…"
                : allFullyDelivered
                ? "Confirm Receipt & Close PO"
                : "Confirm Partial Receipt"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
