import type { InventoryItemDetailDto } from "@mrp/shared/dist/inventory/types.js";
import { permissions } 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 { InventoryStatusBadge } from "./InventoryStatusBadge";
import { InventoryTypeBadge } from "./InventoryTypeBadge";

export function InventoryDetailPage() {
  const { token, user } = useAuth();
  const { itemId } = useParams();
  const [item, setItem] = useState<InventoryItemDetailDto | null>(null);
  const [status, setStatus] = useState("Loading inventory item...");

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

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

    api
      .getInventoryItem(token, itemId)
      .then((nextItem) => {
        setItem(nextItem);
        setStatus("Inventory item loaded.");
      })
      .catch((error: unknown) => {
        const message = error instanceof ApiError ? error.message : "Unable to load inventory item.";
        setStatus(message);
      });
  }, [itemId, token]);

  if (!item) {
    return <div className="rounded-[28px] border border-line/70 bg-surface/90 p-6 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-6 shadow-panel 2xl:p-7">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Inventory Detail</p>
            <h3 className="mt-3 text-2xl font-bold text-text">{item.sku}</h3>
            <p className="mt-2 text-base text-text">{item.name}</p>
            <div className="mt-4 flex flex-wrap gap-3">
              <InventoryTypeBadge type={item.type} />
              <InventoryStatusBadge status={item.status} />
            </div>
            <p className="mt-3 text-sm text-muted">Last updated {new Date(item.updatedAt).toLocaleString()}.</p>
          </div>
          <div className="flex flex-wrap gap-3">
            <Link to="/inventory/items" className="inline-flex items-center justify-center rounded-2xl border border-line/70 px-4 py-3 text-sm font-semibold text-text">
              Back to items
            </Link>
            {canManage ? (
              <Link to={`/inventory/items/${item.id}/edit`} className="inline-flex items-center justify-center rounded-2xl bg-brand px-3 py-2 text-sm font-semibold text-white">
                Edit item
              </Link>
            ) : null}
          </div>
        </div>
      </div>
      <div className="grid gap-4 xl:grid-cols-[minmax(0,1.05fr)_minmax(340px,0.95fr)]">
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-6 shadow-panel 2xl:p-7">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Item Definition</p>
          <dl className="mt-5 grid gap-4 xl:grid-cols-2">
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Description</dt>
              <dd className="mt-2 text-sm leading-7 text-text">{item.description || "No description provided."}</dd>
            </div>
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Unit of measure</dt>
              <dd className="mt-2 text-sm text-text">{item.unitOfMeasure}</dd>
            </div>
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Default cost</dt>
              <dd className="mt-2 text-sm text-text">{item.defaultCost == null ? "Not set" : `$${item.defaultCost.toFixed(2)}`}</dd>
            </div>
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Flags</dt>
              <dd className="mt-2 text-sm text-text">
                {item.isSellable ? "Sellable" : "Not sellable"} / {item.isPurchasable ? "Purchasable" : "Not purchasable"}
              </dd>
            </div>
          </dl>
        </article>
        <article className="rounded-[28px] border border-line/70 bg-surface/90 p-6 shadow-panel 2xl:p-7">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Internal Notes</p>
          <p className="mt-4 whitespace-pre-line text-sm leading-7 text-text">{item.notes || "No internal notes recorded for this item yet."}</p>
          <div className="mt-8 rounded-2xl border border-line/70 bg-page/70 px-4 py-4 text-sm text-muted">
            Created {new Date(item.createdAt).toLocaleDateString()}
          </div>
        </article>
      </div>
      <section className="rounded-[28px] border border-line/70 bg-surface/90 p-6 shadow-panel 2xl:p-7">
        <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Bill Of Materials</p>
        <h4 className="mt-3 text-xl font-bold text-text">Component structure</h4>
        {item.bomLines.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 BOM lines are defined for this item 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">Position</th>
                  <th className="px-2 py-2">Component</th>
                  <th className="px-2 py-2">Quantity</th>
                  <th className="px-2 py-2">UOM</th>
                  <th className="px-2 py-2">Notes</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line/70 bg-surface">
                {item.bomLines.map((line) => (
                  <tr key={line.id}>
                    <td className="px-2 py-2 text-muted">{line.position}</td>
                    <td className="px-2 py-2">
                      <div className="font-semibold text-text">{line.componentSku}</div>
                      <div className="mt-1 text-xs text-muted">{line.componentName}</div>
                    </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.notes || "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </section>
  );
}
