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

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

export function SalesListPage({ entity }: { entity: SalesDocumentEntity }) {
  const { token, user } = useAuth();
  const config = salesConfigs[entity];
  const [documents, setDocuments] = useState<SalesDocumentSummaryDto[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | SalesDocumentStatus>("ALL");
  const [status, setStatus] = useState(`Loading ${config.collectionLabel.toLowerCase()}...`);

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

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

    const loader =
      entity === "quote"
        ? api.getQuotes(token, { q: searchTerm.trim() || undefined, status: statusFilter === "ALL" ? undefined : statusFilter })
        : api.getSalesOrders(token, { q: searchTerm.trim() || undefined, status: statusFilter === "ALL" ? undefined : statusFilter });

    loader
      .then((nextDocuments) => {
        setDocuments(nextDocuments);
        setStatus(`${nextDocuments.length} ${config.collectionLabel.toLowerCase()} matched the current filters.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : `Unable to load ${config.collectionLabel.toLowerCase()}.`;
        setStatus(message);
      });
  }, [config.collectionLabel, entity, searchTerm, statusFilter, token]);

  return (
    <section className="rounded-[28px] border border-line/70 bg-surface/90 p-4 shadow-panel">
      <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.listEyebrow}</p>
          <h3 className="mt-2 text-lg font-bold text-text">{config.collectionLabel}</h3>
          <p className="mt-2 max-w-2xl text-sm text-muted">
            Customer-facing commercial documents for pricing, commitment, and downstream fulfillment planning.
          </p>
        </div>
        {canManage ? (
          <Link to={`${config.routeBase}/new`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-3 py-2 text-sm font-semibold text-white">
            New {config.singularLabel.toLowerCase()}
          </Link>
        ) : null}
      </div>
      <div className="mt-6 grid gap-3 rounded-3xl border border-line/70 bg-page/60 p-3 xl:grid-cols-[1.35fr_0.8fr]">
        <label className="block">
          <span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Search</span>
          <input
            value={searchTerm}
            onChange={(event) => setSearchTerm(event.target.value)}
            placeholder={`Search ${config.collectionLabel.toLowerCase()} by document number or customer`}
            className="w-full rounded-2xl border border-line/70 bg-surface px-2 py-2 text-text outline-none transition focus:border-brand"
          />
        </label>
        <label className="block">
          <span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Status</span>
          <select
            value={statusFilter}
            onChange={(event) => setStatusFilter(event.target.value as "ALL" | SalesDocumentStatus)}
            className="w-full rounded-2xl border border-line/70 bg-surface px-2 py-2 text-text outline-none transition focus:border-brand"
          >
            {salesStatusFilters.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </label>
      </div>
      <div className="mt-6 rounded-2xl border border-line/70 bg-page/60 px-2 py-2 text-sm text-muted">{status}</div>
      {documents.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 {config.collectionLabel.toLowerCase()} 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">Document</th>
                <th className="px-2 py-2">Customer</th>
                <th className="px-2 py-2">Status</th>
                <th className="px-2 py-2">Issue Date</th>
                <th className="px-2 py-2">Value</th>
                <th className="px-2 py-2">Lines</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line/70 bg-surface">
              {documents.map((document) => (
                <tr key={document.id} className="transition hover:bg-page/70">
                  <td className="px-2 py-2">
                    <Link to={`${config.routeBase}/${document.id}`} className="font-semibold text-text hover:text-brand">
                      {document.documentNumber}
                    </Link>
                  </td>
                  <td className="px-2 py-2 text-muted">{document.customerName}</td>
                  <td className="px-2 py-2">
                    <SalesStatusBadge status={document.status} />
                  </td>
                  <td className="px-2 py-2 text-muted">{new Date(document.issueDate).toLocaleDateString()}</td>
                  <td className="px-2 py-2 text-muted">${document.subtotal.toFixed(2)}</td>
                  <td className="px-2 py-2 text-muted">{document.lineCount}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}
