import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import Box from "@mui/material/Box";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import useTableSort from "../hooks/useTableSort";
import useDebounce from "../hooks/useDebounce";
import { usePaginatedQuery } from "../hooks/usePaginatedQuery";

import { formatCurrency, czechPlural } from "../utils/formatters";
import {
  warehouseItemListOptions,
  warehouseCategoryListOptions,
  type WarehouseItem,
} from "../lib/queries/warehouse";
import {
  Button,
  Card,
  DataTable,
  Pagination,
  TextField,
  Select,
  StatusChip,
  PageHeader,
  PageEnter,
  FilterBar,
  EmptyState,
  LoadingState,
  type DataColumn,
} from "../ui";

const PER_PAGE = 20;

const PlusIcon = (
  <svg
    width="20"
    height="20"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
  >
    <line x1="12" y1="5" x2="12" y2="19" />
    <line x1="5" y1="12" x2="19" y2="12" />
  </svg>
);

export default function WarehouseItems() {
  const { hasPermission } = useAuth();
  const navigate = useNavigate();

  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [categoryId, setCategoryId] = useState<number | "">("");
  const debouncedSearch = useDebounce(search, 300);

  const { sort, order, handleSort } = useTableSort("item_number");

  const { data: categories = [] } = useQuery(warehouseCategoryListOptions());

  const { items, pagination, isPending, isFetching } =
    usePaginatedQuery<WarehouseItem>(
      warehouseItemListOptions({
        search: debouncedSearch || undefined,
        page,
        perPage: PER_PAGE,
        sort,
        order,
        category_id: categoryId ? Number(categoryId) : undefined,
      }),
    );

  if (!hasPermission("warehouse.view")) return <Forbidden />;

  const canManage = hasPermission("warehouse.manage");

  if (isPending) {
    return <LoadingState />;
  }

  const total = pagination?.total ?? items.length;
  const subtitle = `${total} ${czechPlural(total, "položka", "položky", "položek")}`;

  const columns: DataColumn<WarehouseItem>[] = [
    {
      key: "item_number",
      header: "Číslo",
      width: "10%",
      sortKey: "item_number",
      mono: true,
      render: (i) => i.item_number || "—",
    },
    {
      key: "name",
      header: "Název",
      width: "24%",
      sortKey: "name",
      bold: true,
      render: (i) => i.name,
    },
    {
      key: "category",
      header: "Kategorie",
      width: "14%",
      render: (i) => i.category?.name || "—",
    },
    {
      key: "unit",
      header: "Jednotka",
      width: "9%",
      render: (i) => i.unit,
    },
    {
      key: "total_quantity",
      header: "Množství",
      width: "10%",
      sortKey: "total_quantity",
      mono: true,
      render: (i) => String(i.total_quantity ?? 0),
    },
    {
      key: "available_quantity",
      header: "K dispozici",
      width: "10%",
      mono: true,
      render: (i) => String(i.available_quantity ?? 0),
    },
    {
      key: "stock_value",
      header: "Hodnota",
      width: "12%",
      sortKey: "stock_value",
      mono: true,
      render: (i) =>
        i.stock_value != null
          ? formatCurrency(i.stock_value, "CZK")
          : "0,00 Kč",
    },
    {
      key: "status",
      header: "Stav",
      width: "11%",
      render: (i) =>
        i.below_minimum ? (
          <StatusChip label="Pod min." color="error" />
        ) : i.is_active ? (
          <StatusChip label="OK" color="success" />
        ) : (
          <StatusChip label="Neaktivní" color="default" />
        ),
    },
  ];

  return (
    <PageEnter>
      <PageHeader
        title="Skladové položky"
        subtitle={subtitle}
        actions={
          canManage ? (
            <Button
              startIcon={PlusIcon}
              onClick={() => navigate("/warehouse/items/new")}
            >
              Přidat položku
            </Button>
          ) : undefined
        }
      />

      <FilterBar>
        <Box sx={{ flex: "1 1 320px" }}>
          <TextField
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            placeholder="Hledat podle názvu nebo čísla položky..."
            fullWidth
          />
        </Box>
        {categories.length > 0 && (
          <Box sx={{ flex: "0 0 220px" }}>
            <Select
              value={categoryId === "" ? "" : String(categoryId)}
              onChange={(val) => {
                setCategoryId(val === "" ? "" : Number(val));
                setPage(1);
              }}
              options={[
                { value: "", label: "Všechny kategorie" },
                ...categories.map((cat) => ({
                  value: String(cat.id),
                  label: cat.name,
                })),
              ]}
            />
          </Box>
        )}
      </FilterBar>

      <Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
        <DataTable<WarehouseItem>
          columns={columns}
          rows={items}
          rowKey={(i) => i.id}
          rowInactive={(i) => !i.is_active}
          onRowClick={(i) => navigate(`/warehouse/items/${i.id}`)}
          sortBy={sort}
          sortDir={order}
          onSort={handleSort}
          empty={
            search || categoryId ? (
              <EmptyState title="Žádné položky pro zadaný filtr." />
            ) : (
              <EmptyState
                title="Zatím nejsou žádné skladové položky."
                action={
                  canManage ? (
                    <Button
                      startIcon={PlusIcon}
                      onClick={() => navigate("/warehouse/items/new")}
                    >
                      Přidat první položku
                    </Button>
                  ) : undefined
                }
              />
            )
          }
        />
        <Pagination
          page={page}
          pageCount={pagination?.total_pages ?? 1}
          onChange={setPage}
        />
      </Card>
    </PageEnter>
  );
}
