import { permissions } from "@mrp/shared";
import type { PurchaseOrderDetailDto, PurchaseOrderStatus } from "@mrp/shared";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { purchaseStatusOptions } from "./config";
import { PurchaseStatusBadge } from "./PurchaseStatusBadge";

export function PurchaseDetailPage() {
  const { token, user } = useAuth();
  const { orderId } = useParams();
  const [document, setDocument] = useState<PurchaseOrderDetailDto | null>(null);
  const [status, setStatus] = useState("Loading purchase order...");
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);

  const canManage = user?.permissions.includes("purchasing.write") ?? false;

  useEffect(() => {
    if (!token || !orderId) {
      return;
    }

    api.getPurchaseOrder(token, orderId)
      .then((nextDocument) => {
        setDocument(nextDocument);
        setStatus("Purchase order loaded.");
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load purchase order.";
        setStatus(message);
      });
  }, [orderId, token]);

  if (!document) {
    return <div className="rounded-[28px] border border-line/70 bg-surface/90 p-4 text-sm text-muted shadow-panel">{status}</div>;
  }

  const activeDocument = document;

  async function handleStatusChange(nextStatus: PurchaseOrderStatus) {
    if (!token) {
      return;
    }

    setIsUpdatingStatus(true);
    setStatus("Updating purchase order status...");

    try {
      const nextDocument = await api.updatePurchaseOrderStatus(token, activeDocument.id, nextStatus);
      setDocument(nextDocument);
      setStatus("Purchase order status updated.");
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : "Unable to update purchase order status.";
      setStatus(message);
    } finally {
      setIsUpdatingStatus(false);
    }
  }

  return (
    <section className="space-y-4">
      <div className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Purchase Order</p>
            <h3 className="mt-2 text-xl font-bold text-text">{activeDocument.documentNumber}</h3>
            <p className="mt-1 text-sm text-text">{activeDocument.vendorName}</p>
            <div className="mt-3 flex flex-wrap gap-2">
              <PurchaseStatusBadge status={activeDocument.status} />
            </div>
          </div>
          <div className="flex flex-wrap gap-3">
            <Link to="/purchasing/orders" className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text">
              Back to purchase orders
            </Link>
            {canManage ? (
              <Link to={`/purchasing/orders/${activeDocument.id}/edit`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">
                Edit purchase order
              </Link>
            ) : null}
          </div>
        </div>
      </div>
      {canManage ? (
        <section className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Quick Actions</p>
              <p className="mt-2 text-sm text-muted">Update purchase-order status without opening the full editor.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              {purchaseStatusOptions.map((option) => (
                <button key={option.value} type="button" onClick={() => handleStatusChange(option.value)} disabled={isUpdatingStatus || activeDocument.status === option.value} className="rounded-2xl border border-line/70 px-2 py-2 text-sm font-semibold text-text disabled:cursor-not-allowed disabled:opacity-60">
                  {option.label}
                </button>
              ))}
            </div>
          </div>
        </section>
      ) : null}
      <section className="grid gap-3 xl:grid-cols-4">
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Issue Date</p><div className="mt-2 text-base font-bold text-text">{new Date(activeDocument.issueDate).toLocaleDateString()}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Lines</p><div className="mt-2 text-base font-bold text-text">{activeDocument.lineCount}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Subtotal</p><div className="mt-2 text-base font-bold text-text">${activeDocument.subtotal.toFixed(2)}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Total</p><div className="mt-2 text-base font-bold text-text">${activeDocument.total.toFixed(2)}</div></article>
      </section>
      <section className="grid gap-3 xl:grid-cols-4">
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Tax</p><div className="mt-2 text-base font-bold text-text">${activeDocument.taxAmount.toFixed(2)}</div><div className="mt-1 text-xs text-muted">{activeDocument.taxPercent.toFixed(2)}%</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Freight</p><div className="mt-2 text-base font-bold text-text">${activeDocument.freightAmount.toFixed(2)}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Payment Terms</p><div className="mt-2 text-base font-bold text-text">{activeDocument.paymentTerms || "N/A"}</div></article>
        <article className="rounded-[24px] border border-line/70 bg-surface/90 px-3 py-3 shadow-panel"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Currency</p><div className="mt-2 text-base font-bold text-text">{activeDocument.currencyCode || "USD"}</div></article>
      </section>
      <div className="grid gap-3 xl:grid-cols-[minmax(0,1.05fr)_minmax(320px,0.95fr)]">
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Vendor</p>
          <dl className="mt-5 grid gap-3">
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Account</dt><dd className="mt-1 text-sm text-text">{activeDocument.vendorName}</dd></div>
            <div><dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Email</dt><dd className="mt-1 text-sm text-text">{activeDocument.vendorEmail}</dd></div>
          </dl>
        </article>
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Notes</p>
          <p className="mt-3 whitespace-pre-line text-sm leading-6 text-text">{activeDocument.notes || "No notes recorded for this document."}</p>
        </article>
      </div>
      <section className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel 2xl:p-5">
        <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Line Items</p>
        {activeDocument.lines.length === 0 ? (
          <div className="mt-6 rounded-3xl border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">No line items have been added yet.</div>
        ) : (
          <div className="mt-6 overflow-hidden rounded-2xl border border-line/70">
            <table className="min-w-full divide-y divide-line/70 text-sm">
              <thead className="bg-page/80 text-left text-muted">
                <tr><th className="px-2 py-2">Item</th><th className="px-2 py-2">Description</th><th className="px-2 py-2">Qty</th><th className="px-2 py-2">UOM</th><th className="px-2 py-2">Unit Cost</th><th className="px-2 py-2">Total</th></tr>
              </thead>
              <tbody className="divide-y divide-line/70 bg-surface">
                {activeDocument.lines.map((line: PurchaseOrderDetailDto["lines"][number]) => (
                  <tr key={line.id}>
                    <td className="px-2 py-2"><div className="font-semibold text-text">{line.itemSku}</div><div className="mt-1 text-xs text-muted">{line.itemName}</div></td>
                    <td className="px-2 py-2 text-muted">{line.description}</td>
                    <td className="px-2 py-2 text-muted">{line.quantity}</td>
                    <td className="px-2 py-2 text-muted">{line.unitOfMeasure}</td>
                    <td className="px-2 py-2 text-muted">${line.unitCost.toFixed(2)}</td>
                    <td className="px-2 py-2 text-muted">${line.lineTotal.toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
      <div className="rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm text-muted">{status}</div>
    </section>
  );
}
