import { permissions } from "@mrp/shared";
import type { SalesDocumentDetailDto } from "@mrp/shared/dist/sales/types.js";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

import { useAuth } from "../../auth/AuthProvider";
import { api, ApiError } from "../../lib/api";
import { salesConfigs, type SalesDocumentEntity } from "./config";
import { SalesStatusBadge } from "./SalesStatusBadge";

export function SalesDetailPage({ entity }: { entity: SalesDocumentEntity }) {
  const { token, user } = useAuth();
  const { quoteId, orderId } = useParams();
  const config = salesConfigs[entity];
  const documentId = entity === "quote" ? quoteId : orderId;
  const [document, setDocument] = useState<SalesDocumentDetailDto | null>(null);
  const [status, setStatus] = useState(`Loading ${config.singularLabel.toLowerCase()}...`);

  const canManage = user?.permissions.includes(permissions.salesWrite) ?? false;

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

    const loader = entity === "quote" ? api.getQuote(token, documentId) : api.getSalesOrder(token, documentId);
    loader
      .then((nextDocument) => {
        setDocument(nextDocument);
        setStatus(`${config.singularLabel} loaded.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : `Unable to load ${config.singularLabel.toLowerCase()}.`;
        setStatus(message);
      });
  }, [config.singularLabel, documentId, entity, 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>;
  }

  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">{config.detailEyebrow}</p>
            <h3 className="mt-2 text-xl font-bold text-text">{document.documentNumber}</h3>
            <p className="mt-1 text-sm text-text">{document.customerName}</p>
            <div className="mt-3 flex flex-wrap gap-2">
              <SalesStatusBadge status={document.status} />
            </div>
          </div>
          <div className="flex flex-wrap gap-3">
            <Link to={config.routeBase} 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 {config.collectionLabel.toLowerCase()}
            </Link>
            {canManage ? (
              <Link to={`${config.routeBase}/${document.id}/edit`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white">
                Edit {config.singularLabel.toLowerCase()}
              </Link>
            ) : null}
          </div>
        </div>
      </div>
      <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(document.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">Expires</p>
          <div className="mt-2 text-base font-bold text-text">{document.expiresAt ? new Date(document.expiresAt).toLocaleDateString() : "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">Lines</p>
          <div className="mt-2 text-base font-bold text-text">{document.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">${document.subtotal.toFixed(2)}</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">Customer</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">{document.customerName}</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">{document.customerEmail}</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">{document.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>
        {document.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 Price</th>
                  <th className="px-2 py-2">Total</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line/70 bg-surface">
              {document.lines.map((line: SalesDocumentDetailDto["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.unitPrice.toFixed(2)}</td>
                    <td className="px-2 py-2 text-muted">${line.lineTotal.toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </section>
  );
}
