import { permissions } from "@mrp/shared";
import type { InventoryItemStatus, InventoryItemSummaryDto, InventoryItemType } from "@mrp/shared/dist/inventory/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 { inventoryStatusFilters, inventoryTypeFilters } from "./config";
import { InventoryStatusBadge } from "./InventoryStatusBadge";
import { InventoryTypeBadge } from "./InventoryTypeBadge";

export function InventoryListPage() {
  const { token, user } = useAuth();
  const [items, setItems] = useState<InventoryItemSummaryDto[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | InventoryItemStatus>("ALL");
  const [typeFilter, setTypeFilter] = useState<"ALL" | InventoryItemType>("ALL");
  const [status, setStatus] = useState("Loading inventory items...");

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

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

    api
      .getInventoryItems(token, {
        q: searchTerm.trim() || undefined,
        status: statusFilter === "ALL" ? undefined : statusFilter,
        type: typeFilter === "ALL" ? undefined : typeFilter,
      })
      .then((nextItems) => {
        setItems(nextItems);
        setStatus(`${nextItems.length} item(s) matched the current filters.`);
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load inventory items.";
        setStatus(message);
      });
  }, [searchTerm, statusFilter, token, typeFilter]);

  return (
    <section className="rounded-[20px] 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">Inventory</p>
          <h3 className="mt-2 text-lg font-bold text-text">Item Master</h3>
          <p className="mt-2 max-w-2xl text-sm text-muted">
            Core item and BOM definitions for purchased parts, manufactured items, assemblies, and service SKUs.
          </p>
        </div>
        {canManage ? (
          <Link to="/inventory/items/new" className="inline-flex items-center justify-center rounded-2xl bg-brand px-3 py-2 text-sm font-semibold text-white">
            New item
          </Link>
        ) : null}
      </div>
      <div className="mt-6 grid gap-3 rounded-[18px] border border-line/70 bg-page/60 p-3 xl:grid-cols-[1.3fr_0.8fr_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 by SKU, item name, or description"
              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" | InventoryItemStatus)}
              className="w-full rounded-2xl border border-line/70 bg-surface px-2 py-2 text-text outline-none transition focus:border-brand"
          >
            {inventoryStatusFilters.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </label>
        <label className="block">
          <span className="mb-2 block text-xs font-semibold uppercase tracking-[0.16em] text-muted">Type</span>
          <select
            value={typeFilter}
            onChange={(event) => setTypeFilter(event.target.value as "ALL" | InventoryItemType)}
              className="w-full rounded-2xl border border-line/70 bg-surface px-2 py-2 text-text outline-none transition focus:border-brand"
          >
            {inventoryTypeFilters.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>
      {items.length === 0 ? (
        <div className="mt-6 rounded-[18px] border border-dashed border-line/70 bg-page/60 px-4 py-8 text-center text-sm text-muted">
          No inventory 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">Type</th>
                <th className="px-2 py-2">Status</th>
                <th className="px-2 py-2">UOM</th>
                <th className="px-2 py-2">Qty</th>
                <th className="px-2 py-2">BOM</th>
                <th className="px-2 py-2">Updated</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-line/70 bg-surface">
              {items.map((item) => (
                <tr key={item.id} className="transition hover:bg-page/70">
                  <td className="px-2 py-2">
                    <Link to={`/inventory/items/${item.id}`} className="font-semibold text-text hover:text-brand">
                      {item.sku}
                    </Link>
                    <div className="mt-1 text-xs text-muted">{item.name}</div>
                  </td>
                  <td className="px-2 py-2">
                    <InventoryTypeBadge type={item.type} />
                  </td>
                  <td className="px-2 py-2">
                    <InventoryStatusBadge status={item.status} />
                  </td>
                  <td className="px-2 py-2 text-muted">{item.unitOfMeasure}</td>
                  <td className="px-2 py-2 text-xs text-muted">
                    <div>Total {item.onHandQuantity}</div>
                    <div>Available {item.availableQuantity}</div>
                  </td>
                  <td className="px-2 py-2 text-muted">{item.bomLineCount} lines</td>
                  <td className="px-2 py-2 text-muted">{new Date(item.updatedAt).toLocaleDateString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}

