"use client";

import { useDeferredValue, useEffect, useMemo, useState } from "react";
import { ArrowDown, ArrowUp, Edit3, Plus, Trash2 } from "lucide-react";

import type { EquipmentCategory, EquipmentItem, EquipmentStatus } from "@rental/shared";

import {
  createCategoryRequest,
  createItemRequest,
  deleteCategoryRequest,
  deleteItemRequest,
  getCategoriesRequest,
  getItemsRequest,
  updateCategoryRequest,
  updateItemRequest
} from "../../lib/api";
import { formatPriceInput, parsePriceInput } from "../../lib/booking-pricing";
import {
  moveCategoryInPreferences,
  moveItemInPreferences,
  sortCategoriesByPreference,
  sortItemsByPreference
} from "../../lib/user-ordering";
import { useSessionContext } from "../layout/session-provider";
import { useUserPreferences } from "../layout/user-preferences-provider";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Card } from "../ui/card";
import { Input, Textarea } from "../ui/input";
import { Modal } from "../ui/modal";

type CategoryDraft = {
  id?: string;
  name: string;
};

type ItemUnitDraft = {
  id?: string;
  serialNumber: string;
  assetTag: string;
};

type ItemDraft = {
  id?: string;
  categoryId: string;
  name: string;
  quantity: string;
  units: ItemUnitDraft[];
  suggestedDayRate: string;
  status: "active" | "service" | "retired";
  notes: string;
  isVisibleOnTimeline: boolean;
};

type InlineEditableField = "serialNumber" | "assetTag";

type InlineEditState = {
  itemId: string;
  field: InlineEditableField;
  value: string;
};

const MODEL_SUFFIX_PATTERN = /\s+(?:[A-Z](?:\d{1,3})?|#\d{1,3})$/i;
const MAX_ITEM_QUANTITY = 200;

const blankCategory: CategoryDraft = { name: "" };

const createBlankUnitDraft = (): ItemUnitDraft => ({
  serialNumber: "",
  assetTag: ""
});

const blankItem = (categoryId = ""): ItemDraft => ({
  categoryId,
  name: "",
  quantity: "1",
  units: [createBlankUnitDraft()],
  suggestedDayRate: "",
  status: "active",
  notes: "",
  isVisibleOnTimeline: true
});

const statusCycle: EquipmentStatus[] = ["active", "service", "retired"];

const statusLabelByValue: Record<EquipmentStatus, string> = {
  active: "Aktywny",
  service: "Serwis",
  retired: "Wyłączony"
};

const statusToneByValue: Record<EquipmentStatus, "success" | "warning" | "neutral"> = {
  active: "success",
  service: "warning",
  retired: "neutral"
};

const getModelBaseName = (name: string) => {
  const trimmed = name.trim();
  const withoutSuffix = trimmed.replace(MODEL_SUFFIX_PATTERN, "").trim();

  return withoutSuffix || trimmed;
};

const getModelGroupKey = (categoryId: string, name: string) => `${categoryId}::${getModelBaseName(name).toLowerCase()}`;

const expandUnits = (units: ItemUnitDraft[], targetCount: number) => {
  if (targetCount <= units.length) {
    return units;
  }

  return [...units, ...Array.from({ length: targetCount - units.length }, () => createBlankUnitDraft())];
};

const parseItemQuantity = (value: string) => {
  const parsed = Number.parseInt(value, 10);

  if (!Number.isFinite(parsed)) {
    return null;
  }

  return Math.min(Math.max(parsed, 1), MAX_ITEM_QUANTITY);
};

const formatUnitIndex = (index: number) => `#${String(index + 1).padStart(2, "0")}`;

const buildItemName = (baseName: string, index: number, totalUnits: number) => {
  const normalizedBaseName = baseName.trim();

  if (totalUnits <= 1) {
    return normalizedBaseName;
  }

  return `${normalizedBaseName} ${formatUnitIndex(index)}`;
};

export const EquipmentAdminPage = () => {
  const { session } = useSessionContext();
  const { preferences, ready: preferencesReady, saving: preferencesSaving, updatePreferences } = useUserPreferences();
  const [categories, setCategories] = useState<EquipmentCategory[]>([]);
  const [items, setItems] = useState<EquipmentItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<"all" | "active" | "service" | "retired">("all");
  const [includeInactive, setIncludeInactive] = useState(true);
  const [categoryDraft, setCategoryDraft] = useState<CategoryDraft | null>(null);
  const [itemDraft, setItemDraft] = useState<ItemDraft | null>(null);
  const [inlineEdit, setInlineEdit] = useState<InlineEditState | null>(null);
  const [quickSavingItemId, setQuickSavingItemId] = useState<string | null>(null);

  const deferredSearch = useDeferredValue(search);
  const parsedSuggestedDayRate = parsePriceInput(itemDraft?.suggestedDayRate ?? "");

  const isAdmin = session?.user.role === "admin";
  const canEditItems = session?.user.role === "admin" || session?.user.role === "operator";
  const canReorderView = Boolean(session?.user.id) && preferencesReady && !preferencesSaving;
  const sortedCategories = useMemo(() => sortCategoriesByPreference(categories, preferences), [categories, preferences]);
  const sortedItems = useMemo(() => sortItemsByPreference(items, preferences), [items, preferences]);
  const itemsByModelKey = useMemo(() => {
    const groups = new Map<string, EquipmentItem[]>();

    for (const item of items) {
      const key = getModelGroupKey(item.categoryId, item.name);
      const group = groups.get(key) ?? [];
      group.push(item);
      groups.set(key, group);
    }

    for (const group of groups.values()) {
      group.sort((left, right) => left.name.localeCompare(right.name, "pl"));
    }

    return groups;
  }, [items]);
  const draftQuantity = parseItemQuantity(itemDraft?.quantity ?? "") ?? 0;
  const visibleDraftUnits = itemDraft ? itemDraft.units.slice(0, draftQuantity) : [];
  const existingDraftUnitCount = itemDraft?.units.filter((unit) => Boolean(unit.id)).length ?? 0;
  const reducingExistingQuantity = itemDraft ? draftQuantity < existingDraftUnitCount : false;
  const quantityNeedsAdmin = reducingExistingQuantity && !isAdmin;

  const submitQuickItemUpdate = async (itemId: string, payload: Record<string, unknown>, fallbackMessage: string) => {
    if (!session) {
      return;
    }

    setQuickSavingItemId(itemId);
    setError(null);

    try {
      await updateItemRequest(session, itemId, payload);
      setInlineEdit((current) => (current?.itemId === itemId ? null : current));
      await refresh();
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : fallbackMessage);
    } finally {
      setQuickSavingItemId(null);
    }
  };

  const cycleItemStatus = async (item: EquipmentItem) => {
    const currentIndex = statusCycle.indexOf(item.status);
    const nextStatus = statusCycle[(currentIndex + 1) % statusCycle.length];

    await submitQuickItemUpdate(item.id, { status: nextStatus }, "Nie udało się zmienić statusu urządzenia");
  };

  const moveItemToCategory = async (item: EquipmentItem, categoryId: string) => {
    if (!categoryId || categoryId === item.categoryId) {
      return;
    }

    await submitQuickItemUpdate(item.id, { categoryId }, "Nie udało się przenieść urządzenia do innej grupy");
  };

  const startInlineEdit = (item: EquipmentItem, field: InlineEditableField) => {
    if (!canEditItems || saving || Boolean(quickSavingItemId)) {
      return;
    }

    setInlineEdit({
      itemId: item.id,
      field,
      value: field === "serialNumber" ? item.serialNumber ?? "" : item.assetTag ?? ""
    });
  };

  const submitInlineEdit = async (item: EquipmentItem, field: InlineEditableField, value: string) => {
    await submitQuickItemUpdate(
      item.id,
      field === "serialNumber" ? { serialNumber: value } : { assetTag: value },
      `Nie udało się zapisać pola ${field === "serialNumber" ? "S/N" : "TAG"}`
    );
  };

  const renderInlineCell = (item: EquipmentItem, field: InlineEditableField) => {
    const isEditing = inlineEdit?.itemId === item.id && inlineEdit.field === field;

    if (isEditing) {
      return (
        <Input
          autoFocus
          className="h-8 rounded-xl px-3 py-1.5"
          disabled={quickSavingItemId === item.id}
          value={inlineEdit.value}
          onBlur={() =>
            setInlineEdit((current) =>
              current?.itemId === item.id && current.field === field ? null : current
            )
          }
          onChange={(event) =>
            setInlineEdit((current) =>
              current?.itemId === item.id && current.field === field
                ? { ...current, value: event.target.value }
                : current
            )
          }
          onKeyDown={(event) => {
            if (event.key === "Enter") {
              event.preventDefault();
              void submitInlineEdit(item, field, event.currentTarget.value);
            }

            if (event.key === "Escape") {
              event.preventDefault();
              setInlineEdit((current) =>
                current?.itemId === item.id && current.field === field ? null : current
              );
            }
          }}
        />
      );
    }

    return (
      <button
        className="w-full rounded-xl px-2 py-1.5 text-left text-sm text-muted transition hover:bg-[#f7f2ea] disabled:cursor-default disabled:hover:bg-transparent"
        disabled={!canEditItems || saving || Boolean(quickSavingItemId)}
        onDoubleClick={() => startInlineEdit(item, field)}
        title={canEditItems ? `Dwuklik, aby edytować pole ${field === "serialNumber" ? "S/N" : "TAG"}` : undefined}
        type="button"
      >
        <span className="block truncate">{field === "serialNumber" ? item.serialNumber || "—" : item.assetTag || "—"}</span>
      </button>
    );
  };

  const refresh = async () => {
    if (!session) {
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const [nextCategories, nextItems] = await Promise.all([
        getCategoriesRequest(session),
        getItemsRequest(session, {
          includeInactive,
          search: deferredSearch,
          status: statusFilter
        })
      ]);

      setCategories(nextCategories);
      setItems(nextItems);
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Nie udało się pobrać sprzętu");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void refresh();
  }, [deferredSearch, includeInactive, session, statusFilter]);

  const moveCategory = async (categoryId: string, direction: -1 | 1) => {
    if (!canReorderView) {
      return;
    }

    setError(null);

    try {
      const nextPreferences = moveCategoryInPreferences(categories, preferences, categoryId, direction);
      await updatePreferences({ equipmentCategoryOrder: nextPreferences.equipmentCategoryOrder });
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Nie udało się zapisać kolejności typów sprzętu");
    }
  };

  const moveItem = async (itemId: string, direction: -1 | 1) => {
    if (!canReorderView) {
      return;
    }

    setError(null);

    try {
      const nextPreferences = moveItemInPreferences(items, preferences, itemId, direction);
      await updatePreferences({ equipmentItemOrder: nextPreferences.equipmentItemOrder });
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Nie udało się zapisać kolejności urządzeń");
    }
  };

  const openItemDraft = (item?: EquipmentItem) => {
    if (!item) {
      setItemDraft(blankItem(categories[0]?.id ?? ""));
      return;
    }

    const modelGroup = itemsByModelKey.get(getModelGroupKey(item.categoryId, item.name)) ?? [item];

    setItemDraft({
      id: item.id,
      categoryId: item.categoryId,
      name: getModelBaseName(item.name),
      quantity: String(modelGroup.length),
      units: modelGroup.map((groupItem) => ({
        id: groupItem.id,
        serialNumber: groupItem.serialNumber ?? "",
        assetTag: groupItem.assetTag ?? ""
      })),
      suggestedDayRate: formatPriceInput(item.suggestedDayRate),
      status: item.status,
      notes: item.notes ?? "",
      isVisibleOnTimeline: item.isVisibleOnTimeline
    });
  };

  const updateDraftQuantity = (value: string) => {
    const digitsOnly = value.replace(/[^\d]/g, "");

    setItemDraft((current) => {
      if (!current) {
        return current;
      }

      if (digitsOnly === "") {
        return {
          ...current,
          quantity: ""
        };
      }

      const nextQuantity = parseItemQuantity(digitsOnly);

      if (!nextQuantity) {
        return current;
      }

      return {
        ...current,
        quantity: String(nextQuantity),
        units: expandUnits(current.units, nextQuantity)
      };
    });
  };

  const updateDraftUnit = (index: number, field: keyof ItemUnitDraft, value: string) => {
    setItemDraft((current) => {
      if (!current) {
        return current;
      }

      return {
        ...current,
        units: current.units.map((unit, unitIndex) =>
          unitIndex === index
            ? {
                ...unit,
                [field]: value
              }
            : unit
        )
      };
    });
  };

  const saveItemDraft = async () => {
    if (!session || !itemDraft || parsedSuggestedDayRate === null) {
      return;
    }

    const quantity = parseItemQuantity(itemDraft.quantity);

    if (!quantity || quantityNeedsAdmin) {
      return;
    }

    const baseName = itemDraft.name.trim();

    if (!baseName) {
      return;
    }

    const activeUnits = itemDraft.units.slice(0, quantity);
    const removedUnits = itemDraft.units.slice(quantity).filter((unit) => Boolean(unit.id));

    setSaving(true);
    setError(null);

    try {
      if (removedUnits.length > 0) {
        for (const unit of removedUnits) {
          if (unit.id) {
            await deleteItemRequest(session, unit.id);
          }
        }
      }

      for (const [index, unit] of activeUnits.entries()) {
        const payload = {
          categoryId: itemDraft.categoryId,
          name: buildItemName(baseName, index, activeUnits.length),
          serialNumber: unit.serialNumber.trim(),
          assetTag: unit.assetTag.trim(),
          suggestedDayRate: parsedSuggestedDayRate,
          status: itemDraft.status,
          notes: itemDraft.notes.trim(),
          isVisibleOnTimeline: itemDraft.isVisibleOnTimeline
        };

        if (unit.id) {
          await updateItemRequest(session, unit.id, payload);
          continue;
        }

        await createItemRequest(session, payload);
      }

      setItemDraft(null);
      await refresh();
    } catch (requestError) {
      setError(requestError instanceof Error ? requestError.message : "Nie udało się zapisać urządzeń");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-5">
      <Card className="p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <p className="text-xs uppercase tracking-[0.22em] text-muted">Administracja</p>
            <h2 className="mt-1 text-2xl font-semibold text-ink">Zarządzanie sprzętem</h2>
          </div>
          <div className="flex flex-wrap gap-2">
            {isAdmin ? (
              <Button onClick={() => setCategoryDraft(blankCategory)}>
                <Plus className="h-4 w-4" />
                Nowy typ
              </Button>
            ) : null}
            {canEditItems ? (
              <Button variant="secondary" onClick={() => openItemDraft()}>
                <Plus className="h-4 w-4" />
                Nowe urządzenie
              </Button>
            ) : null}
          </div>
        </div>
      </Card>

      <div className="grid gap-5 xl:grid-cols-[0.95fr_1.4fr]">
        <Card className="p-5">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs uppercase tracking-[0.2em] text-muted">Typy sprzętu</p>
              <h3 className="mt-2 text-lg font-semibold text-ink">{categories.length} kategorii</h3>
            </div>
            <Badge tone="accent">Kategorie</Badge>
          </div>

          {loading ? <p className="mt-4 text-sm text-muted">Ładowanie...</p> : null}
          {error ? <p className="mt-4 rounded-2xl bg-[#f8d9d3] px-4 py-3 text-sm text-[#8d2f20]">{error}</p> : null}

          <div className="mt-5 space-y-3">
            {sortedCategories.map((category, categoryIndex) => (
              <div key={category.id} className="rounded-2xl border border-line bg-white px-3 py-2.5">
                <div className="flex items-center justify-between gap-3">
                  <div className="min-w-0">
                    <p className="truncate text-sm font-semibold text-ink">
                      {category.name}
                      <span className="ml-2 text-xs font-medium text-muted">
                        {category.itemCount} szt. • {category.activeItemCount} aktywnych
                      </span>
                    </p>
                  </div>
                  {isAdmin ? (
                    <div className="flex flex-nowrap gap-2">
                      <Button
                        className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                        disabled={!canReorderView || categoryIndex === 0}
                        title="Przesuń typ wyżej"
                        variant="ghost"
                        onClick={() => void moveCategory(category.id, -1)}
                      >
                        <ArrowUp className="h-4 w-4" />
                      </Button>
                      <Button
                        className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                        disabled={!canReorderView || categoryIndex === sortedCategories.length - 1}
                        title="Przesuń typ niżej"
                        variant="ghost"
                        onClick={() => void moveCategory(category.id, 1)}
                      >
                        <ArrowDown className="h-4 w-4" />
                      </Button>
                      <Button
                        className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                        variant="ghost"
                        onClick={() => setCategoryDraft({ id: category.id, name: category.name })}
                      >
                        <Edit3 className="h-4 w-4" />
                      </Button>
                      <Button
                        className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                        variant="ghost"
                        onClick={async () => {
                          if (!session || !window.confirm(`Usunąć kategorię "${category.name}"?`)) {
                            return;
                          }

                          try {
                            await deleteCategoryRequest(session, category.id);
                            await refresh();
                          } catch (requestError) {
                            setError(requestError instanceof Error ? requestError.message : "Nie udało się usunąć kategorii");
                          }
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  ) : null}
                </div>
              </div>
            ))}
          </div>
        </Card>

        <Card className="p-5">
          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
              <div>
                <p className="text-xs uppercase tracking-[0.2em] text-muted">Egzemplarze</p>
                <h3 className="mt-2 text-lg font-semibold text-ink">{items.length} urządzeń</h3>
              </div>
              <div className="grid gap-3 sm:grid-cols-3">
                <label className="block space-y-2">
                  <span className="text-xs uppercase tracking-[0.18em] text-muted">Szukaj</span>
                  <Input
                    className="h-[45px] py-0"
                    value={search}
                    onChange={(event) => setSearch(event.target.value)}
                    placeholder="Nazwa, S/N lub TAG"
                  />
                </label>
                <label className="block space-y-2">
                  <span className="text-xs uppercase tracking-[0.18em] text-muted">Status</span>
                  <select
                    className="h-[45px] w-full rounded-2xl border border-line bg-white px-4 py-0 text-sm text-ink outline-none focus:border-accent"
                    value={statusFilter}
                    onChange={(event) => setStatusFilter(event.target.value as typeof statusFilter)}
                  >
                    <option value="all">Wszystkie</option>
                    <option value="active">Aktywne</option>
                    <option value="service">Serwis</option>
                    <option value="retired">Wyłączone</option>
                  </select>
                </label>
                <label className="mt-0 flex h-[45px] items-center gap-3 rounded-2xl border border-line bg-white px-4 py-0 sm:mt-[26px]">
                  <input
                    checked={includeInactive}
                    onChange={(event) => setIncludeInactive(event.target.checked)}
                    type="checkbox"
                  />
                  <span className="text-sm text-ink">Pokaż nieaktywne</span>
                </label>
              </div>
            </div>

            <p className="text-xs text-muted">
              Kliknij status, aby przełączać Aktywny / Serwis / Wyłączony. Dwuklik w polu S/N albo TAG uruchamia edycję inline,
              zapis następuje po Enter. Edycja modelu pozwala zmienić ilość sztuk i wpisać seryjne oraz TAG-i dla wielu egzemplarzy naraz.
            </p>

            <div className="overflow-hidden rounded-[28px] border border-line">
              <div className="hidden grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,0.7fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_88px] gap-2 border-b border-line bg-[#f5efe5] px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:grid">
                <div>Urządzenie</div>
                <div>Kategoria</div>
                <div>Stawka</div>
                <div>S/N</div>
                <div>TAG</div>
                <div>Status</div>
                <div></div>
              </div>

              {sortedItems.map((item) => {
                const siblingItems = sortedItems.filter((candidate) => candidate.categoryId === item.categoryId);
                const siblingIndex = siblingItems.findIndex((candidate) => candidate.id === item.id);

                return (
                  <div
                    key={item.id}
                    className="grid gap-3 border-b border-line/60 bg-white px-4 py-3 lg:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,0.7fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_88px] lg:items-center lg:gap-2 lg:py-2"
                  >
                    <div className="min-w-0">
                      <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Urządzenie</p>
                      <div className="flex min-w-0 items-center gap-2">
                        <p className="truncate text-sm font-semibold text-ink">{item.name}</p>
                        {item.notes ? <p className="truncate text-xs text-muted">{item.notes}</p> : null}
                      </div>
                    </div>
                    <div className="flex items-center justify-between gap-3 lg:block">
                      <span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Kategoria</span>
                      {canEditItems ? (
                        <select
                          className="h-8 w-full rounded-xl border border-line bg-white px-3 py-0 text-sm text-ink outline-none focus:border-accent"
                          disabled={saving || Boolean(quickSavingItemId)}
                          value={item.categoryId}
                          onChange={(event) => void moveItemToCategory(item, event.target.value)}
                        >
                          {categories.map((category) => (
                            <option key={category.id} value={category.id}>
                              {category.name}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <div className="text-right text-sm text-muted lg:text-left">{item.categoryName}</div>
                      )}
                    </div>
                    <div className="flex items-center justify-between gap-3 lg:block">
                      <span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Stawka sugerowana</span>
                      <div className="text-right text-sm text-muted lg:text-left">
                        {item.suggestedDayRate !== null ? `${formatPriceInput(item.suggestedDayRate)} / dzień` : "—"}
                      </div>
                    </div>
                    <div>
                      <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">S/N</p>
                      {renderInlineCell(item, "serialNumber")}
                    </div>
                    <div>
                      <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">TAG</p>
                      {renderInlineCell(item, "assetTag")}
                    </div>
                    <div>
                      <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Status</p>
                      <button
                        className="rounded-full"
                        disabled={!canEditItems || saving || Boolean(quickSavingItemId)}
                        onClick={() => void cycleItemStatus(item)}
                        title={canEditItems ? "Kliknij, aby przełączyć status urządzenia" : undefined}
                        type="button"
                      >
                        <Badge tone={statusToneByValue[item.status]}>{statusLabelByValue[item.status]}</Badge>
                      </button>
                    </div>
                    <div className="min-w-[76px]">
                      <p className="mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted lg:hidden">Akcje</p>
                      <div className="flex flex-nowrap items-center justify-start gap-1 lg:justify-end">
                        <Button
                          className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                          disabled={!canReorderView || siblingIndex <= 0}
                          title="Przesuń urządzenie wyżej"
                          variant="ghost"
                          onClick={() => void moveItem(item.id, -1)}
                        >
                          <ArrowUp className="h-4 w-4" />
                        </Button>
                        <Button
                          className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                          disabled={!canReorderView || siblingIndex === -1 || siblingIndex >= siblingItems.length - 1}
                          title="Przesuń urządzenie niżej"
                          variant="ghost"
                          onClick={() => void moveItem(item.id, 1)}
                        >
                          <ArrowDown className="h-4 w-4" />
                        </Button>
                        {canEditItems ? (
                          <Button
                            className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                            variant="ghost"
                            onClick={() => openItemDraft(item)}
                          >
                            <Edit3 className="h-4 w-4" />
                          </Button>
                        ) : null}
                        {isAdmin ? (
                          <Button
                            className="h-8 w-8 shrink-0 rounded-xl p-0 text-ink hover:bg-[#f2ece1]"
                            variant="ghost"
                            onClick={async () => {
                              if (!session || !window.confirm(`Usunąć urządzenie "${item.name}"?`)) {
                                return;
                              }

                              try {
                                await deleteItemRequest(session, item.id);
                                await refresh();
                              } catch (requestError) {
                                setError(requestError instanceof Error ? requestError.message : "Nie udało się usunąć urządzenia");
                              }
                            }}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        ) : null}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </Card>
      </div>

      <Modal
        open={Boolean(categoryDraft)}
        onClose={() => setCategoryDraft(null)}
        title={categoryDraft?.id ? "Edytuj typ sprzętu" : "Dodaj typ sprzętu"}
        footer={
          <>
            <Button variant="ghost" onClick={() => setCategoryDraft(null)}>
              Anuluj
            </Button>
            <Button
              disabled={saving || !categoryDraft?.name.trim()}
              onClick={async () => {
                if (!session || !categoryDraft) {
                  return;
                }

                setSaving(true);

                try {
                  if (categoryDraft.id) {
                    await updateCategoryRequest(session, categoryDraft.id, { name: categoryDraft.name });
                  } else {
                    await createCategoryRequest(session, { name: categoryDraft.name });
                  }

                  setCategoryDraft(null);
                  await refresh();
                } catch (requestError) {
                  setError(requestError instanceof Error ? requestError.message : "Nie udało się zapisać kategorii");
                } finally {
                  setSaving(false);
                }
              }}
            >
              {saving ? "Zapisywanie..." : "Zapisz"}
            </Button>
          </>
        }
      >
        <label className="block space-y-2">
          <span className="text-sm font-medium text-ink">Nazwa typu</span>
          <Input
            value={categoryDraft?.name ?? ""}
            onChange={(event) => setCategoryDraft((current) => (current ? { ...current, name: event.target.value } : current))}
          />
        </label>
      </Modal>

      <Modal
        open={Boolean(itemDraft)}
        onClose={() => setItemDraft(null)}
        title={itemDraft?.id ? "Edytuj model i ilość sztuk" : "Dodaj model urządzenia"}
        footer={
          <>
            <Button variant="ghost" onClick={() => setItemDraft(null)}>
              Anuluj
            </Button>
            <Button
              disabled={
                saving ||
                !itemDraft?.name.trim() ||
                !itemDraft?.categoryId ||
                parsedSuggestedDayRate === null ||
                !draftQuantity ||
                quantityNeedsAdmin
              }
              onClick={() => void saveItemDraft()}
            >
              {saving ? "Zapisywanie..." : "Zapisz"}
            </Button>
          </>
        }
      >
        <div className="grid gap-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="block space-y-2 sm:col-span-2">
              <span className="text-sm font-medium text-ink">Typ sprzętu</span>
              <select
                className="w-full rounded-2xl border border-line bg-white px-4 py-2.5 text-sm text-ink outline-none focus:border-accent"
                value={itemDraft?.categoryId ?? ""}
                onChange={(event) =>
                  setItemDraft((current) => (current ? { ...current, categoryId: event.target.value } : current))
                }
              >
                <option value="">Wybierz kategorię</option>
                {categories.map((category) => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-medium text-ink">Model urządzenia</span>
              <Input
                value={itemDraft?.name ?? ""}
                onChange={(event) => setItemDraft((current) => (current ? { ...current, name: event.target.value } : current))}
                placeholder='Np. Laptop 14"'
              />
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-medium text-ink">Ilość sztuk</span>
              <Input
                inputMode="numeric"
                value={itemDraft?.quantity ?? ""}
                onChange={(event) => updateDraftQuantity(event.target.value)}
                placeholder="1"
              />
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-medium text-ink">Sugerowana stawka dzienna</span>
              <Input
                inputMode="decimal"
                value={itemDraft?.suggestedDayRate ?? ""}
                onChange={(event) =>
                  setItemDraft((current) => (current ? { ...current, suggestedDayRate: event.target.value } : current))
                }
                placeholder="Np. 150,00"
              />
            </label>

            <label className="block space-y-2">
              <span className="text-sm font-medium text-ink">Status egzemplarzy</span>
              <select
                className="w-full rounded-2xl border border-line bg-white px-4 py-2.5 text-sm text-ink outline-none focus:border-accent"
                value={itemDraft?.status ?? "active"}
                onChange={(event) =>
                  setItemDraft((current) =>
                    current ? { ...current, status: event.target.value as ItemDraft["status"] } : current
                  )
                }
              >
                <option value="active">Aktywne</option>
                <option value="service">W serwisie</option>
                <option value="retired">Wyłączone</option>
              </select>
            </label>
          </div>

          <label className="flex items-center gap-3 rounded-2xl border border-line bg-white px-4 py-3">
            <input
              checked={itemDraft?.isVisibleOnTimeline ?? true}
              onChange={(event) =>
                setItemDraft((current) =>
                  current ? { ...current, isVisibleOnTimeline: event.target.checked } : current
                )
              }
              type="checkbox"
            />
            <span className="text-sm font-medium text-ink">Widoczne na timeline</span>
          </label>

          {itemDraft && parsedSuggestedDayRate === null ? (
            <div className="rounded-2xl bg-[#f8d9d3] px-4 py-3 text-sm text-[#8d2f20]">
              Sugerowana stawka dzienna jest wymagana i musi być dodatnią liczbą, np. `150` albo `150,50`.
            </div>
          ) : null}

          {quantityNeedsAdmin ? (
            <div className="rounded-2xl bg-[#f6e1cf] px-4 py-3 text-sm text-[#8f5b1f]">
              Zmniejszanie ilości istniejącego modelu usuwa nadmiarowe egzemplarze, więc wymaga konta admina.
            </div>
          ) : null}

          <label className="block space-y-2">
            <span className="text-sm font-medium text-ink">Notatka</span>
            <Textarea
              value={itemDraft?.notes ?? ""}
              onChange={(event) => setItemDraft((current) => (current ? { ...current, notes: event.target.value } : current))}
            />
          </label>

          <div className="space-y-3 rounded-2xl border border-line bg-[#fbf8f2] p-4">
            <div className="flex items-center justify-between gap-3">
              <div>
                <p className="text-sm font-semibold text-ink">Egzemplarze modelu</p>
                <p className="text-xs text-muted">
                  System utworzy nazwy w formacie `Model #01`, `Model #02` itd. Tutaj wpisujesz tylko `S/N` i `TAG`.
                </p>
              </div>
              <Badge tone="neutral">{draftQuantity || 0} szt.</Badge>
            </div>

            <div className="space-y-2">
              <div className="hidden grid-cols-[88px_minmax(0,1fr)_minmax(0,1fr)] gap-2 px-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted sm:grid">
                <div>Egzemplarz</div>
                <div>S/N</div>
                <div>TAG</div>
              </div>

              {visibleDraftUnits.map((unit, index) => (
                <div
                  key={unit.id ?? `draft-unit-${index}`}
                  className="grid gap-2 rounded-2xl border border-line bg-white px-3 py-3 sm:grid-cols-[88px_minmax(0,1fr)_minmax(0,1fr)] sm:items-center"
                >
                  <div>
                    <p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted sm:hidden">Egzemplarz</p>
                    <p className="text-sm font-semibold text-ink">{formatUnitIndex(index)}</p>
                  </div>
                  <label className="block space-y-1 sm:space-y-0">
                    <span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted sm:hidden">S/N</span>
                    <Input
                      value={unit.serialNumber}
                      onChange={(event) => updateDraftUnit(index, "serialNumber", event.target.value)}
                      placeholder="Numer seryjny"
                    />
                  </label>
                  <label className="block space-y-1 sm:space-y-0">
                    <span className="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted sm:hidden">TAG</span>
                    <Input
                      value={unit.assetTag}
                      onChange={(event) => updateDraftUnit(index, "assetTag", event.target.value)}
                      placeholder="TAG wewnętrzny"
                    />
                  </label>
                </div>
              ))}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};
