import { FormEvent, useEffect, useMemo, useState } from "react";

import { portalRuntimeConfig } from "../config/runtime";
import {
  addInventoryStock,
  createInventoryWarehouse,
  createInventoryWarehouseSession,
  fetchInventoryWarehouseDetail,
  fetchInventoryWarehouseSessionDetail,
  fetchInventoryWarehouseSessions,
  fetchInventoryWarehouses,
  searchInventoryProducts,
  type InventoryProductOption,
  type InventorySession,
  type InventorySessionDetailResponse,
  type InventoryWarehouse,
  type InventoryWarehouseDetailItem,
  type InventoryWarehouseDetailResponse,
} from "../lib/api";

type InventoryViewMode = "latest" | "history" | "edit";

function formatQuantity(value: number): string {
  if (!Number.isFinite(value)) {
    return "0";
  }
  const rounded = Math.round(value * 100) / 100;
  return new Intl.NumberFormat("it-IT", {
    minimumFractionDigits: Number.isInteger(rounded) ? 0 : 2,
    maximumFractionDigits: 2,
  }).format(rounded);
}

function formatDate(value?: string | null): string {
  if (!value) {
    return "Non disponibile";
  }
  const parsed = new Date(`${value}T00:00:00`);
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }
  return new Intl.DateTimeFormat("it-IT", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).format(parsed);
}

function formatDateTime(value?: string | null): string {
  if (!value) {
    return "Non disponibile";
  }
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return value;
  }
  return new Intl.DateTimeFormat("it-IT", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(parsed);
}

function latestMondayIsoDate(): string {
  const now = new Date();
  const mondayOffset = (now.getDay() + 6) % 7;
  now.setDate(now.getDate() - mondayOffset);
  const local = new Date(now.getTime() - now.getTimezoneOffset() * 60_000);
  return local.toISOString().slice(0, 10);
}

function buildProductOptionLabel(option: InventoryProductOption): string {
  return [option.product_name, option.supplier_name, option.lot_code].filter(Boolean).join(" · ");
}

function buildSessionLabel(session: InventorySession): string {
  return `${formatDate(session.inventory_date)} · ${formatQuantity(session.total_equivalent_units)} unita`;
}

function normalizeInventorySearchValue(value: string): string {
  return value
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .trim();
}

function filterInventoryItems(items: InventoryWarehouseDetailItem[], query: string): InventoryWarehouseDetailItem[] {
  const normalizedQuery = normalizeInventorySearchValue(query);
  if (!normalizedQuery) {
    return items;
  }
  return items.filter((item) => {
    const haystack = [
      item.product_name,
      item.supplier_name,
      ...item.lots.map((lot) => lot.lot_code || ""),
    ]
      .join(" ")
      .trim();
    return normalizeInventorySearchValue(haystack).includes(normalizedQuery);
  });
}

function InventoryItemsList({
  items,
  emptyTitle,
  emptyDescription,
}: {
  items: InventoryWarehouseDetailItem[];
  emptyTitle: string;
  emptyDescription: string;
}) {
  if (!items.length) {
    return (
      <div className="empty-state">
        <strong>{emptyTitle}</strong>
        <p>{emptyDescription}</p>
      </div>
    );
  }

  return (
    <div className="inventory-item-list">
      {items.map((item) => (
        <article key={item.id} className="inventory-item-card">
          <div className="inventory-item-head">
            <div className="inventory-item-identity">
              <strong>{item.product_name}</strong>
              <span>{item.supplier_name}</span>
            </div>
            <div className="inventory-item-total">
              <strong>{formatQuantity(item.total_equivalent_units)}</strong>
              <span>totale presente</span>
            </div>
          </div>
          <div className="inventory-lot-list">
            {item.lots.map((lot) => (
              <div key={lot.id} className="inventory-lot-chip">
                <strong>{lot.lot_code || "lotto non indicato"}</strong>
                <span>
                  {formatQuantity(lot.quantity)} presenti
                  {lot.units_per_pack ? ` · ${formatQuantity(lot.units_per_pack)} per pack` : ""}
                </span>
                <small>{formatQuantity(lot.equivalent_units)} unita equivalenti</small>
              </div>
            ))}
          </div>
        </article>
      ))}
    </div>
  );
}

export function InventoryPage() {
  const [warehouses, setWarehouses] = useState<InventoryWarehouse[]>([]);
  const [selectedWarehouseId, setSelectedWarehouseId] = useState("");
  const [warehouseDetail, setWarehouseDetail] = useState<InventoryWarehouseDetailResponse | null>(null);
  const [sessions, setSessions] = useState<InventorySession[]>([]);
  const [viewMode, setViewMode] = useState<InventoryViewMode>("latest");
  const [viewedSessionId, setViewedSessionId] = useState("");
  const [viewedSessionDetail, setViewedSessionDetail] = useState<InventorySessionDetailResponse | null>(null);
  const [warehouseName, setWarehouseName] = useState("");
  const [inventoryDate, setInventoryDate] = useState(latestMondayIsoDate());
  const [productQuery, setProductQuery] = useState("");
  const [productResults, setProductResults] = useState<InventoryProductOption[]>([]);
  const [latestSearchQuery, setLatestSearchQuery] = useState("");
  const [historySearchQuery, setHistorySearchQuery] = useState("");
  const [draftSearchQuery, setDraftSearchQuery] = useState("");
  const [selectedProduct, setSelectedProduct] = useState<InventoryProductOption | null>(null);
  const [quantity, setQuantity] = useState("0");
  const [catalogAvailable, setCatalogAvailable] = useState(true);
  const [loading, setLoading] = useState(true);
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [loadingSessions, setLoadingSessions] = useState(false);
  const [loadingViewedSession, setLoadingViewedSession] = useState(false);
  const [searchingProducts, setSearchingProducts] = useState(false);
  const [creatingWarehouse, setCreatingWarehouse] = useState(false);
  const [savingInventory, setSavingInventory] = useState(false);
  const [savingStock, setSavingStock] = useState(false);
  const [productSearchOpen, setProductSearchOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [flash, setFlash] = useState<string | null>(null);

  const selectedWarehouse = warehouses.find((item) => item.id === selectedWarehouseId) ?? null;
  const currentItems = warehouseDetail?.items ?? [];
  const latestSavedSession = sessions[0] ?? null;
  const viewedItems = viewedSessionDetail?.items ?? [];
  const latestSessionDetail =
    latestSavedSession && viewedSessionDetail?.session?.id === latestSavedSession.id ? viewedSessionDetail : null;
  const loadingLatestSessionDetail = Boolean(latestSavedSession) && (!latestSessionDetail || loadingViewedSession);
  const filteredHistoryItems = useMemo(() => filterInventoryItems(viewedItems, historySearchQuery), [viewedItems, historySearchQuery]);
  const filteredCurrentItems = useMemo(() => filterInventoryItems(currentItems, draftSearchQuery), [currentItems, draftSearchQuery]);

  const selectedProductState = useMemo(() => {
    if (!selectedProduct) {
      return {
        lotQuantity: null as number | null,
        productTotal: null as number | null,
      };
    }
    const currentItem = currentItems.find(
      (entry) => entry.product_name === selectedProduct.product_name && entry.supplier_name === selectedProduct.supplier_name
    );
    const currentLot = currentItem?.lots.find((entry) => entry.lot_code === selectedProduct.lot_code) ?? null;
    return {
      lotQuantity: currentLot?.quantity ?? null,
      productTotal: currentItem?.total_equivalent_units ?? null,
    };
  }, [currentItems, selectedProduct]);

  const parsedQuantity = Number(quantity);
  const canSubmitStock =
    Boolean(selectedWarehouseId && selectedProduct) &&
    Number.isFinite(parsedQuantity) &&
    parsedQuantity >= 0 &&
    !(selectedProduct?.requires_units_per_pack && !selectedProduct?.units_per_pack && parsedQuantity > 0);

  async function loadWarehouses(preferredWarehouseId?: string) {
    const response = await fetchInventoryWarehouses(portalRuntimeConfig.apiHubBaseUrl);
    setWarehouses(response.warehouses);
    const nextWarehouseId =
      (preferredWarehouseId && response.warehouses.some((item) => item.id === preferredWarehouseId) && preferredWarehouseId) ||
      (selectedWarehouseId && response.warehouses.some((item) => item.id === selectedWarehouseId) && selectedWarehouseId) ||
      response.warehouses[0]?.id ||
      "";
    setSelectedWarehouseId(nextWarehouseId);
    return nextWarehouseId;
  }

  async function loadWarehouseDetail(warehouseId: string) {
    const response = await fetchInventoryWarehouseDetail(portalRuntimeConfig.apiHubBaseUrl, warehouseId);
    setWarehouseDetail(response);
    return response;
  }

  async function loadWarehouseSessions(warehouseId: string, preferredViewedSessionId?: string) {
    const response = await fetchInventoryWarehouseSessions(portalRuntimeConfig.apiHubBaseUrl, warehouseId);
    setSessions(response.sessions);
    const nextViewedSessionId =
      (preferredViewedSessionId && response.sessions.some((item) => item.id === preferredViewedSessionId) && preferredViewedSessionId) ||
      response.sessions[0]?.id ||
      "";
    setViewedSessionId(nextViewedSessionId);
    return response.sessions;
  }

  useEffect(() => {
    let cancelled = false;

    async function bootstrap() {
      try {
        setLoading(true);
        setError(null);
        await loadWarehouses();
      } catch (loadError) {
        if (!cancelled) {
          setError(loadError instanceof Error ? loadError.message : "Inventario non disponibile.");
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }

    void bootstrap();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    let cancelled = false;

    async function loadWarehouseContext() {
      if (!selectedWarehouseId) {
        setWarehouseDetail(null);
        setSessions([]);
        setViewedSessionId("");
        setViewedSessionDetail(null);
        return;
      }
      try {
        setLoadingDetail(true);
        setLoadingSessions(true);
        setError(null);
        const loadedSessions = await loadWarehouseSessions(selectedWarehouseId);
        await loadWarehouseDetail(selectedWarehouseId);
        if (!cancelled) {
          setViewMode(loadedSessions.length ? "latest" : "edit");
        }
      } catch (loadError) {
        if (!cancelled) {
          setError(loadError instanceof Error ? loadError.message : "Magazzino non disponibile.");
        }
      } finally {
        if (!cancelled) {
          setLoadingDetail(false);
          setLoadingSessions(false);
        }
      }
    }

    void loadWarehouseContext();
    return () => {
      cancelled = true;
    };
  }, [selectedWarehouseId]);

  useEffect(() => {
    let cancelled = false;

    async function loadViewedSession() {
      if (!selectedWarehouseId || !viewedSessionId) {
        setViewedSessionDetail(null);
        return;
      }
      try {
        setLoadingViewedSession(true);
        const response = await fetchInventoryWarehouseSessionDetail(
          portalRuntimeConfig.apiHubBaseUrl,
          selectedWarehouseId,
          viewedSessionId
        );
        if (!cancelled) {
          setViewedSessionDetail(response);
        }
      } catch (loadError) {
        if (!cancelled) {
          setError(loadError instanceof Error ? loadError.message : "Storico inventario non disponibile.");
        }
      } finally {
        if (!cancelled) {
          setLoadingViewedSession(false);
        }
      }
    }

    void loadViewedSession();
    return () => {
      cancelled = true;
    };
  }, [selectedWarehouseId, viewedSessionId]);

  useEffect(() => {
    let cancelled = false;
    if (!productSearchOpen) {
      setProductResults([]);
      return;
    }

    const handle = window.setTimeout(async () => {
      try {
        setSearchingProducts(true);
        const response = await searchInventoryProducts(portalRuntimeConfig.apiHubBaseUrl, productQuery, 18);
        if (cancelled) {
          return;
        }
        setCatalogAvailable(response.catalog_available);
        setProductResults(response.items);
      } catch (searchError) {
        if (!cancelled) {
          setError(searchError instanceof Error ? searchError.message : "Ricerca prodotti non disponibile.");
        }
      } finally {
        if (!cancelled) {
          setSearchingProducts(false);
        }
      }
    }, 180);

    return () => {
      cancelled = true;
      window.clearTimeout(handle);
    };
  }, [productQuery, productSearchOpen]);

  useEffect(() => {
    if (!selectedProduct) {
      return;
    }
    setQuantity(selectedProductState.lotQuantity != null ? String(selectedProductState.lotQuantity) : "0");
  }, [selectedProduct?.id, selectedProductState.lotQuantity]);

  useEffect(() => {
    setLatestSearchQuery("");
    setHistorySearchQuery("");
    setDraftSearchQuery("");
    setViewedSessionDetail(null);
  }, [selectedWarehouseId]);

  useEffect(() => {
    if (viewMode !== "latest" || !latestSavedSession) {
      return;
    }
    if (viewedSessionId !== latestSavedSession.id) {
      setViewedSessionId(latestSavedSession.id);
    }
  }, [viewMode, latestSavedSession?.id, viewedSessionId]);

  async function handleCreateWarehouse(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const name = warehouseName.trim();
    if (!name) {
      setError("Dammi un nome per il nuovo magazzino.");
      return;
    }

    try {
      setCreatingWarehouse(true);
      setError(null);
      setFlash(null);
      const warehouse = await createInventoryWarehouse(portalRuntimeConfig.apiHubBaseUrl, { name });
      await loadWarehouses(warehouse.id);
      setWarehouseName("");
      setViewMode("edit");
      setFlash(`Magazzino ${warehouse.name} creato.`);
    } catch (createError) {
      setError(createError instanceof Error ? createError.message : "Creazione magazzino non riuscita.");
    } finally {
      setCreatingWarehouse(false);
    }
  }

  async function handleSaveInventory(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!selectedWarehouseId) {
      setError("Seleziona prima il magazzino.");
      return;
    }

    try {
      setSavingInventory(true);
      setError(null);
      setFlash(null);
      const response = await createInventoryWarehouseSession(portalRuntimeConfig.apiHubBaseUrl, selectedWarehouseId, {
        inventory_date: inventoryDate || null,
      });
      await Promise.all([
        loadWarehouses(selectedWarehouseId),
        loadWarehouseDetail(selectedWarehouseId),
        loadWarehouseSessions(selectedWarehouseId, response.session.id),
      ]);
      setViewMode("latest");
      setFlash(
        response.replaced_existing
          ? `Inventario del ${formatDate(response.session.inventory_date)} aggiornato per ${response.session.warehouse_name}.`
          : `Inventario del ${formatDate(response.session.inventory_date)} salvato per ${response.session.warehouse_name}.`
      );
    } catch (saveError) {
      setError(saveError instanceof Error ? saveError.message : "Salvataggio inventario non riuscito.");
    } finally {
      setSavingInventory(false);
    }
  }

  async function handleSetCount(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!selectedWarehouseId || !selectedProduct) {
      setError("Seleziona prima un prodotto dal catalogo.");
      return;
    }
    if (!Number.isFinite(parsedQuantity) || parsedQuantity < 0) {
      setError("Quantita non valida.");
      return;
    }

    try {
      setSavingStock(true);
      setError(null);
      setFlash(null);
      const response = await addInventoryStock(portalRuntimeConfig.apiHubBaseUrl, selectedWarehouseId, {
        product_id: selectedProduct.id,
        quantity: parsedQuantity,
        operation: "set",
      });
      setWarehouseDetail(response);
      await loadWarehouses(selectedWarehouseId);
      setProductQuery("");
      setProductResults([]);
      setSelectedProduct(null);
      setProductSearchOpen(false);
      setQuantity("0");
      setFlash(`Conteggio aggiornato per ${response.warehouse.name}.`);
    } catch (saveError) {
      setError(saveError instanceof Error ? saveError.message : "Aggiornamento conteggio non riuscito.");
    } finally {
      setSavingStock(false);
    }
  }

  function handleProductSelect(option: InventoryProductOption) {
    setSelectedProduct(option);
    setProductQuery(buildProductOptionLabel(option));
    setProductSearchOpen(false);
    setProductResults([]);
    setFlash(null);
    setError(null);
  }

  if (loading) {
    return (
      <section className="panel narrow-panel stack-md">
        <h2 className="page-title">Inventario</h2>
        <p className="muted-copy">Carico...</p>
      </section>
    );
  }

  return (
    <section className="stack-lg">
      <div className="page-head">
        <h1 className="page-heading">Inventario</h1>
      </div>

      {error ? <p className="auth-error">{error}</p> : null}
      {flash ? (
        <div className="callout">
          <strong>Inventario</strong>
          {flash}
        </div>
      ) : null}

      <div className="inventory-layout">
        <section className="panel stack-md inventory-sidebar-panel">
          <h3>Magazzini</h3>
          <form className="mock-form inventory-create-form inventory-create-inline" onSubmit={handleCreateWarehouse}>
            <label className="field">
              <span>Nuovo magazzino</span>
              <input
                type="text"
                value={warehouseName}
                onChange={(event) => setWarehouseName(event.target.value)}
                placeholder="Nome magazzino"
              />
            </label>
            <button type="submit" className="button-primary" disabled={creatingWarehouse}>
              {creatingWarehouse ? "Creo..." : "Crea"}
            </button>
          </form>

          {warehouses.length === 0 ? (
            <div className="empty-state">
              <strong>Nessun magazzino creato</strong>
              <p>Crea il primo magazzino.</p>
            </div>
          ) : (
            <div className="inventory-warehouse-list">
              {warehouses.map((warehouse) => (
                <button
                  key={warehouse.id}
                  type="button"
                  className={`inventory-warehouse-card${warehouse.id === selectedWarehouseId ? " is-active" : ""}`}
                  onClick={() => {
                    setSelectedWarehouseId(warehouse.id);
                    setViewMode("latest");
                  }}
                >
                  <strong>{warehouse.name}</strong>
                  <span>
                    {warehouse.latest_inventory_date
                      ? formatDate(warehouse.latest_inventory_date)
                      : "Mai salvato"}
                  </span>
                </button>
              ))}
            </div>
          )}
        </section>

        <section className="panel stack-md inventory-main-panel">
          {!selectedWarehouse ? (
            <div className="empty-state">
              <strong>Seleziona un magazzino</strong>
              <p>Aprine uno dalla lista.</p>
            </div>
          ) : (
            <>
              <h3>{selectedWarehouse.name}</h3>

              <div className="inventory-mode-actions">
                <button
                  type="button"
                  className={`button-secondary${viewMode === "latest" ? " is-active" : ""}`}
                  onClick={() => {
                    if (latestSavedSession) {
                      setViewedSessionId(latestSavedSession.id);
                    }
                    setViewMode("latest");
                  }}
                >
                  Ultimo salvato
                </button>
                <button
                  type="button"
                  className={`button-secondary${viewMode === "history" ? " is-active" : ""}`}
                  onClick={() => setViewMode("history")}
                >
                  Storico
                </button>
                <button
                  type="button"
                  className={`button-secondary${viewMode === "edit" ? " is-active" : ""}`}
                  onClick={() => setViewMode("edit")}
                >
                  Nuovo inventario
                </button>
              </div>

              {viewMode === "latest" ? (
                latestSavedSession ? (
                  <>
                    <div className="inventory-section-head">
                      <strong>{formatDate(latestSavedSession.inventory_date)}</strong>
                      <label className="field inventory-inline-filter">
                        <span>Cerca prodotto</span>
                        <input
                          type="text"
                          value={latestSearchQuery}
                          onChange={(event) => setLatestSearchQuery(event.target.value)}
                          placeholder="Nome, fornitore o lotto"
                        />
                      </label>
                    </div>
                    {loadingLatestSessionDetail ? (
                      <p className="muted-copy">Carico inventario...</p>
                    ) : (
                      <InventoryItemsList
                        items={filterInventoryItems(latestSessionDetail?.items ?? [], latestSearchQuery)}
                        emptyTitle="Inventario senza righe"
                        emptyDescription={
                          latestSearchQuery
                            ? "Non trovo prodotti compatibili con questa ricerca nell'ultimo inventario."
                            : "Questo inventario non contiene prodotti salvati."
                        }
                      />
                    )}
                  </>
                ) : (
                  <div className="empty-state">
                    <strong>Nessun inventario salvato</strong>
                    <p>Usa Nuovo inventario.</p>
                  </div>
                )
              ) : null}

              {viewMode === "history" ? (
                loadingSessions ? (
                  <p className="muted-copy">Carico storico...</p>
                ) : sessions.length === 0 ? (
                  <div className="empty-state">
                    <strong>Nessuno storico disponibile</strong>
                    <p>Salva il primo inventario.</p>
                  </div>
                ) : (
                  <>
                    <div className="inventory-history-layout">
                      <div className="inventory-history-column">
                        <div className="inventory-snapshot-list">
                          {sessions.map((session) => (
                            <button
                              key={session.id}
                              type="button"
                              className={`inventory-snapshot-card inventory-session-button${session.id === viewedSessionId ? " is-active" : ""}`}
                              onClick={() => setViewedSessionId(session.id)}
                            >
                              <strong>{buildSessionLabel(session)}</strong>
                              <span>{session.total_products} prodotti</span>
                              <small>Salvato {formatDateTime(session.created_at)}</small>
                            </button>
                          ))}
                        </div>
                      </div>
                      <div className="inventory-history-column">
                        {loadingViewedSession ? (
                          <p className="muted-copy">Carico inventario...</p>
                        ) : viewedSessionDetail?.session ? (
                          <>
                            <div className="inventory-section-head">
                              <strong>{formatDate(viewedSessionDetail.session.inventory_date)}</strong>
                              <label className="field inventory-inline-filter">
                                <span>Cerca prodotto</span>
                                <input
                                  type="text"
                                  value={historySearchQuery}
                                  onChange={(event) => setHistorySearchQuery(event.target.value)}
                                  placeholder="Nome, fornitore o lotto"
                                />
                              </label>
                            </div>
                            <InventoryItemsList
                              items={filteredHistoryItems}
                              emptyTitle="Inventario senza righe"
                              emptyDescription={
                                historySearchQuery
                                  ? "Non trovo prodotti compatibili con questa ricerca in questa data."
                                  : "Questo inventario non contiene prodotti salvati."
                              }
                            />
                          </>
                        ) : (
                          <div className="empty-state">
                            <strong>Seleziona una data</strong>
                            <p>Apri uno storico.</p>
                          </div>
                        )}
                      </div>
                    </div>
                  </>
                )
              ) : null}

              {viewMode === "edit" ? (
                <>
                  <form className="mock-form inventory-snapshot-form" onSubmit={handleSaveInventory}>
                    <label className="field">
                      <span>Data inventario</span>
                      <input type="date" value={inventoryDate} onChange={(event) => setInventoryDate(event.target.value)} />
                    </label>
                    <button type="submit" className="button-primary" disabled={savingInventory}>
                      {savingInventory ? "Salvo..." : "Salva inventario"}
                    </button>
                  </form>

                  <form className="mock-form inventory-stock-form" onSubmit={handleSetCount}>
                    <div className="inventory-stock-grid">
                      <label className="field inventory-product-search">
                        <span>Prodotto</span>
                        <input
                          type="text"
                          value={productQuery}
                          onFocus={() => setProductSearchOpen(true)}
                          onBlur={() => window.setTimeout(() => setProductSearchOpen(false), 120)}
                          onChange={(event) => {
                            setProductQuery(event.target.value);
                            setSelectedProduct(null);
                            setProductSearchOpen(true);
                          }}
                          placeholder="Cerca prodotto, fornitore o lotto"
                        />
                        {productSearchOpen ? (
                          <div className="inventory-product-results">
                            {!catalogAvailable ? (
                              <div className="inventory-product-empty">Catalogo prodotti non disponibile in questo tenant.</div>
                            ) : searchingProducts ? (
                              <div className="inventory-product-empty">Sto cercando nel catalogo prodotti...</div>
                            ) : productResults.length === 0 ? (
                              <div className="inventory-product-empty">Non trovo varianti compatibili con questa ricerca.</div>
                            ) : (
                              productResults.map((option) => (
                                <button
                                  key={option.id}
                                  type="button"
                                  className="inventory-product-option"
                                  onMouseDown={(event) => event.preventDefault()}
                                  onClick={() => handleProductSelect(option)}
                                >
                                  <strong>{option.product_name}</strong>
                                  <span>{[option.supplier_name, option.lot_code].filter(Boolean).join(" · ")}</span>
                                  <small>
                                    {option.units_per_pack
                                      ? `${formatQuantity(option.units_per_pack)} unita per pack`
                                      : option.requires_units_per_pack
                                        ? "Serve unita per pack nel catalogo"
                                        : "Lotto singolo"}
                                  </small>
                                </button>
                              ))
                            )}
                          </div>
                        ) : null}
                      </label>

                      <label className="field">
                        <span>Quantita effettiva presente</span>
                        <input
                          type="number"
                          min="0"
                          step="0.01"
                          value={quantity}
                          onChange={(event) => setQuantity(event.target.value)}
                          placeholder="0"
                        />
                      </label>

                      <div className="inventory-stock-submit">
                        <button type="submit" className="button-primary" disabled={!canSubmitStock || savingStock}>
                          {savingStock ? "Salvo..." : "Imposta quantita"}
                        </button>
                      </div>
                    </div>

                    {selectedProduct ? (
                      <div className="inventory-selected-product">
                        <strong>{buildProductOptionLabel(selectedProduct)}</strong>
                        <span>
                          {selectedProduct.units_per_pack
                            ? `Unita per pack salvate: ${formatQuantity(selectedProduct.units_per_pack)}`
                            : selectedProduct.requires_units_per_pack
                              ? "Questa variante richiede il dato unita per pack prima di poterla contare correttamente."
                              : "Variante unitaria pronta per il conteggio."}
                        </span>
                        <small>
                          {selectedProductState.lotQuantity != null
                            ? `Attualmente impostato: ${formatQuantity(selectedProductState.lotQuantity)} · totale prodotto: ${formatQuantity(selectedProductState.productTotal ?? 0)}`
                            : "Questo lotto non e ancora presente nel conteggio corrente del magazzino."}
                        </small>
                      </div>
                    ) : null}
                  </form>

                  <div className="inventory-section-head">
                    <strong>Conteggio</strong>
                    <label className="field inventory-inline-filter">
                      <span>Cerca prodotto</span>
                      <input
                        type="text"
                        value={draftSearchQuery}
                        onChange={(event) => setDraftSearchQuery(event.target.value)}
                        placeholder="Nome, fornitore o lotto"
                      />
                    </label>
                  </div>

                  {loadingDetail ? (
                    <p className="muted-copy">Sto leggendo il conteggio corrente di questo magazzino.</p>
                  ) : (
                    <InventoryItemsList
                      items={filteredCurrentItems}
                      emptyTitle="Conteggio corrente vuoto"
                      emptyDescription={
                        draftSearchQuery
                          ? "Non trovo prodotti compatibili con questa ricerca nel conteggio corrente."
                          : "Inizia a impostare le quantita effettive presenti per preparare il prossimo inventario."
                      }
                    />
                  )}
                </>
              ) : null}
            </>
          )}
        </section>
      </div>
    </section>
  );
}
