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

import { formatDate } from "../utils/formatters";
import {
  warehouseInventoryListOptions,
  type WarehouseInventorySession,
} from "../lib/queries/warehouse";
import {
  Button,
  Card,
  DataTable,
  Pagination,
  Select,
  StatusChip,
  PageHeader,
  PageEnter,
  FilterBar,
  EmptyState,
  LoadingState,
  type DataColumn,
} from "../ui";

const PER_PAGE = 20;

const STATUS_COLOR: Record<
  string,
  "warning" | "success" | "error" | "info" | "default"
> = {
  DRAFT: "warning",
  CONFIRMED: "success",
};

const STATUS_LABEL: Record<string, string> = {
  DRAFT: "Návrh",
  CONFIRMED: "Potvrzeno",
};

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 WarehouseInventory() {
  const { hasPermission } = useAuth();
  const navigate = useNavigate();

  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<string>("");

  const { items, pagination, isPending, isFetching } =
    usePaginatedQuery<WarehouseInventorySession>(
      warehouseInventoryListOptions({
        page,
        perPage: PER_PAGE,
        status: statusFilter || undefined,
      }),
    );

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

  const resetFilters = () => {
    setStatusFilter("");
    setPage(1);
  };

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

  const total = pagination?.total ?? items.length;
  const subtitle = `${total} ${
    total === 1
      ? "inventura"
      : total >= 2 && total <= 4
        ? "inventury"
        : "inventur"
  }`;

  const columns: DataColumn<WarehouseInventorySession>[] = [
    {
      key: "session_number",
      header: "Číslo inventury",
      width: "30%",
      mono: true,
      bold: true,
      render: (s) => s.session_number || "—",
    },
    {
      key: "status",
      header: "Stav",
      width: "20%",
      render: (s) => (
        <StatusChip
          label={STATUS_LABEL[s.status] ?? s.status}
          color={STATUS_COLOR[s.status] ?? "default"}
        />
      ),
    },
    {
      key: "created_at",
      header: "Vytvořeno",
      width: "30%",
      mono: true,
      render: (s) => formatDate(s.created_at),
    },
    {
      key: "items",
      header: "Položky",
      width: "20%",
      mono: true,
      render: (s) => String(s.items?.length ?? 0),
    },
  ];

  return (
    <PageEnter>
      <PageHeader
        title="Inventury"
        subtitle={subtitle}
        actions={
          <Button
            startIcon={PlusIcon}
            onClick={() => navigate("/warehouse/inventory/new")}
          >
            Nová inventura
          </Button>
        }
      />

      <FilterBar>
        <Box sx={{ flex: "0 0 160px" }}>
          <Select
            value={statusFilter}
            onChange={(val) => {
              setStatusFilter(val);
              setPage(1);
            }}
            options={[
              { value: "", label: "Všechny stavy" },
              { value: "DRAFT", label: "Návrh" },
              { value: "CONFIRMED", label: "Potvrzeno" },
            ]}
          />
        </Box>
        {statusFilter && (
          <Button variant="outlined" color="inherit" onClick={resetFilters}>
            Zrušit filtry
          </Button>
        )}
      </FilterBar>

      <Card sx={{ opacity: isFetching ? 0.6 : 1, transition: "opacity .2s" }}>
        <DataTable<WarehouseInventorySession>
          columns={columns}
          rows={items}
          rowKey={(s) => s.id}
          onRowClick={(s) => navigate(`/warehouse/inventory/${s.id}`)}
          empty={
            statusFilter ? (
              <EmptyState title="Žádné inventury pro zadaný filtr." />
            ) : (
              <EmptyState
                title="Zatím nejsou žádné inventury."
                action={
                  <Button
                    startIcon={PlusIcon}
                    onClick={() => navigate("/warehouse/inventory/new")}
                  >
                    Vytvořit první inventuru
                  </Button>
                }
              />
            )
          }
        />
        <Pagination
          page={page}
          pageCount={pagination?.total_pages ?? 1}
          onChange={setPage}
        />
      </Card>
    </PageEnter>
  );
}
