import type { InventoryItemDetailDto, InventoryTransactionInput, WarehouseLocationOptionDto } 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 { emptyInventoryTransactionInput, inventoryTransactionOptions } from "./config";
import { InventoryAttachmentsPanel } from "./InventoryAttachmentsPanel";
import { InventoryStatusBadge } from "./InventoryStatusBadge";
import { InventoryTransactionTypeBadge } from "./InventoryTransactionTypeBadge";
import { InventoryTypeBadge } from "./InventoryTypeBadge";

export function InventoryDetailPage() {
  const { token, user } = useAuth();
  const { itemId } = useParams();
  const [item, setItem] = useState<InventoryItemDetailDto | null>(null);
  const [locationOptions, setLocationOptions] = useState<WarehouseLocationOptionDto[]>([]);
  const [transactionForm, setTransactionForm] = useState<InventoryTransactionInput>(emptyInventoryTransactionInput);
  const [transactionStatus, setTransactionStatus] = useState("Record receipts, issues, and adjustments against this item.");
  const [isSavingTransaction, setIsSavingTransaction] = useState(false);
  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);
      });

    api
      .getWarehouseLocationOptions(token)
      .then((options) => {
        setLocationOptions(options);
        setTransactionForm((current) => {
          if (current.locationId) {
            return current;
          }

          const firstOption = options[0];
          return firstOption
            ? {
                ...current,
                warehouseId: firstOption.warehouseId,
                locationId: firstOption.locationId,
              }
            : current;
        });
      })
      .catch(() => setLocationOptions([]));
  }, [itemId, token]);

  function updateTransactionField<Key extends keyof InventoryTransactionInput>(key: Key, value: InventoryTransactionInput[Key]) {
    setTransactionForm((current) => ({ ...current, [key]: value }));
  }

  async function handleTransactionSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!token || !itemId) {
      return;
    }

    setIsSavingTransaction(true);
    setTransactionStatus("Saving stock transaction...");

    try {
      const nextItem = await api.createInventoryTransaction(token, itemId, transactionForm);
      setItem(nextItem);
      setTransactionStatus("Stock transaction recorded.");
      setTransactionForm((current) => ({
        ...emptyInventoryTransactionInput,
        transactionType: current.transactionType,
        warehouseId: current.warehouseId,
        locationId: current.locationId,
      }));
    } catch (error: unknown) {
      const message = error instanceof ApiError ? error.message : "Unable to save stock transaction.";
      setTransactionStatus(message);
    } finally {
      setIsSavingTransaction(false);
    }
  }

  if (!item) {
  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">Inventory Detail</p>
            <h3 className="mt-2 text-xl font-bold text-text">{item.sku}</h3>
            <p className="mt-1 text-sm 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-2 py-2 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>
      <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">On Hand</p>
          <div className="mt-2 text-base font-bold text-text">{item.onHandQuantity}</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">Stock Locations</p>
          <div className="mt-2 text-base font-bold text-text">{item.stockBalances.length}</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">Transactions</p>
          <div className="mt-2 text-base font-bold text-text">{item.recentTransactions.length}</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">BOM Lines</p>
          <div className="mt-2 text-base font-bold text-text">{item.bomLines.length}</div>
        </article>
      </section>
      <div className="grid gap-3 xl:grid-cols-[minmax(0,1.05fr)_minmax(340px,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">Item Definition</p>
          <dl className="mt-5 grid gap-3 xl:grid-cols-2">
            <div>
              <dt className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Description</dt>
              <dd className="mt-1 text-sm leading-6 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">Default price</dt>
              <dd className="mt-2 text-sm text-text">{item.defaultPrice == null ? "Not set" : `$${item.defaultPrice.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-4 shadow-panel 2xl:p-5">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-muted">Internal Notes</p>
          <p className="mt-3 whitespace-pre-line text-sm leading-6 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-2 py-2 text-sm text-muted">
            Created {new Date(item.createdAt).toLocaleDateString()}
          </div>
          <div className="mt-4 rounded-2xl border border-line/70 bg-page/70 px-2 py-2">
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted">Current stock by location</p>
            {item.stockBalances.length === 0 ? (
              <p className="mt-2 text-sm text-muted">No stock has been posted for this item yet.</p>
            ) : (
              <div className="mt-3 space-y-2">
                {item.stockBalances.map((balance) => (
                  <div key={balance.locationId} className="flex items-center justify-between rounded-2xl border border-line/70 bg-surface px-2 py-2 text-sm">
                    <div className="min-w-0">
                      <div className="font-semibold text-text">
                        {balance.warehouseCode} / {balance.locationCode}
                      </div>
                      <div className="text-xs text-muted">
                        {balance.warehouseName} · {balance.locationName}
                      </div>
                    </div>
                    <div className="shrink-0 font-semibold text-text">{balance.quantityOnHand}</div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </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">Bill Of Materials</p>
        <h4 className="mt-2 text-lg 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 className="grid gap-3 2xl:grid-cols-[minmax(360px,0.82fr)_minmax(0,1.18fr)]">
        {canManage ? (
          <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">Stock Transactions</p>
            <h4 className="mt-2 text-lg font-bold text-text">Record movement</h4>
            <p className="mt-2 text-sm text-muted">Post receipts, issues, and adjustments to update on-hand inventory.</p>
            <form className="mt-5 space-y-4" onSubmit={handleTransactionSubmit}>
              <div className="grid gap-3 xl:grid-cols-2">
                <label className="block">
                  <span className="mb-2 block text-sm font-semibold text-text">Transaction type</span>
                  <select
                    value={transactionForm.transactionType}
                    onChange={(event) => updateTransactionField("transactionType", event.target.value as InventoryTransactionInput["transactionType"])}
                    className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand"
                  >
                    {inventoryTransactionOptions.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-semibold text-text">Quantity</span>
                  <input
                    type="number"
                    min={1}
                    step={1}
                    value={transactionForm.quantity}
                    onChange={(event) => updateTransactionField("quantity", Number.parseInt(event.target.value, 10) || 0)}
                    className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand"
                  />
                </label>
              </div>
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Stock location</span>
                <select
                  value={transactionForm.locationId}
                  onChange={(event) => {
                    const nextLocation = locationOptions.find((option) => option.locationId === event.target.value);
                    updateTransactionField("locationId", event.target.value);
                    if (nextLocation) {
                      updateTransactionField("warehouseId", nextLocation.warehouseId);
                    }
                  }}
                  className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand"
                >
                  {locationOptions.map((option) => (
                    <option key={option.locationId} value={option.locationId}>
                      {option.warehouseCode} / {option.locationCode}
                    </option>
                  ))}
                </select>
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Reference</span>
                <input
                  value={transactionForm.reference}
                  onChange={(event) => updateTransactionField("reference", event.target.value)}
                  placeholder="PO, WO, adjustment note, etc."
                  className="w-full rounded-2xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand"
                />
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-semibold text-text">Notes</span>
                <textarea
                  value={transactionForm.notes}
                  onChange={(event) => updateTransactionField("notes", event.target.value)}
                  rows={3}
                  className="w-full rounded-3xl border border-line/70 bg-page px-2 py-2 text-text outline-none transition focus:border-brand"
                />
              </label>
              <div className="flex flex-col gap-3 rounded-2xl border border-line/70 bg-page/70 px-2 py-2 sm:flex-row sm:items-center sm:justify-between">
                <span className="min-w-0 text-sm text-muted">{transactionStatus}</span>
                <button
                  type="submit"
                  disabled={isSavingTransaction || locationOptions.length === 0}
                  className="rounded-2xl bg-brand px-2 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60"
                >
                  {isSavingTransaction ? "Posting..." : "Post transaction"}
                </button>
              </div>
            </form>
          </article>
        ) : null}
        <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">Stock History</p>
          <h4 className="mt-2 text-lg font-bold text-text">Recent movements</h4>
          {item.recentTransactions.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 stock transactions have been recorded for this item yet.
            </div>
          ) : (
            <div className="mt-6 space-y-3">
              {item.recentTransactions.map((transaction) => (
                <article key={transaction.id} className="rounded-3xl border border-line/70 bg-page/60 p-3">
                  <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                    <div>
                      <div className="flex flex-wrap items-center gap-2">
                        <InventoryTransactionTypeBadge type={transaction.transactionType} />
                        <span className={`text-sm font-semibold ${transaction.signedQuantity >= 0 ? "text-emerald-700 dark:text-emerald-300" : "text-rose-700 dark:text-rose-300"}`}>
                          {transaction.signedQuantity >= 0 ? "+" : ""}
                          {transaction.signedQuantity}
                        </span>
                      </div>
                      <div className="mt-2 text-sm font-semibold text-text">
                        {transaction.warehouseCode} / {transaction.locationCode}
                      </div>
                      <div className="text-xs text-muted">
                        {transaction.warehouseName} · {transaction.locationName}
                      </div>
                      {transaction.reference ? <div className="mt-2 text-xs text-muted">Ref: {transaction.reference}</div> : null}
                      {transaction.notes ? <p className="mt-2 whitespace-pre-line text-sm leading-6 text-text">{transaction.notes}</p> : null}
                    </div>
                    <div className="text-sm text-muted lg:text-right">
                      <div>{new Date(transaction.createdAt).toLocaleString()}</div>
                      <div className="mt-1">{transaction.createdByName}</div>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          )}
        </article>
      </section>
      <InventoryAttachmentsPanel itemId={item.id} />
    </section>
  );
}
