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

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

export function SalesDetailPage({ entity }: { entity: SalesDocumentEntity }) {
  const { token, user } = useAuth();
  const navigate = useNavigate();
  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 [isUpdatingStatus, setIsUpdatingStatus] = useState(false);
  const [isConverting, setIsConverting] = useState(false);

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

  const activeDocument = document;

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

    setIsUpdatingStatus(true);
    setStatus(`Updating ${config.singularLabel.toLowerCase()} status...`);

    try {
      const nextDocument =
        entity === "quote"
          ? await api.updateQuoteStatus(token, activeDocument.id, nextStatus)
          : await api.updateSalesOrderStatus(token, activeDocument.id, nextStatus);
      setDocument(nextDocument);
      setStatus(`${config.singularLabel} status updated.`);
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : `Unable to update ${config.singularLabel.toLowerCase()} status.`;
      setStatus(message);
    } finally {
      setIsUpdatingStatus(false);
    }
  }

  async function handleConvert() {
    if (!token || entity !== "quote") {
      return;
    }

    setIsConverting(true);
    setStatus("Converting quote to sales order...");

    try {
      const order = await api.convertQuoteToSalesOrder(token, activeDocument.id);
      navigate(`/sales/orders/${order.id}`);
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : "Unable to convert quote to sales order.";
      setStatus(message);
      setIsConverting(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">{config.detailEyebrow}</p>
            <h3 className="mt-2 text-xl font-bold text-text">{activeDocument.documentNumber}</h3>
            <p className="mt-1 text-sm text-text">{activeDocument.customerName}</p>
            <div className="mt-3 flex flex-wrap gap-2">
              <SalesStatusBadge status={activeDocument.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}/${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 {config.singularLabel.toLowerCase()}
                </Link>
                {entity === "quote" ? (
                  <button
                    type="button"
                    onClick={handleConvert}
                    disabled={isConverting}
                    className="inline-flex items-center justify-center rounded-2xl border border-emerald-400/40 px-2 py-2 text-sm font-semibold text-emerald-700 disabled:cursor-not-allowed disabled:opacity-60 dark:text-emerald-300"
                  >
                    {isConverting ? "Converting..." : "Convert to sales order"}
                  </button>
                ) : null}
              </>
            ) : 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 document status without opening the full editor.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              {salesStatusOptions.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">Expires</p>
          <div className="mt-2 text-base font-bold text-text">{activeDocument.expiresAt ? new Date(activeDocument.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">{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>
      </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">{activeDocument.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">{activeDocument.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">{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 Price</th>
                  <th className="px-2 py-2">Total</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line/70 bg-surface">
              {activeDocument.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>
  );
}
