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

import { formatDate } from "../utils/formatters";
import {
  warehouseReceiptListOptions,
  warehouseSupplierListOptions,
  type WarehouseReceipt,
} from "../lib/queries/warehouse";
import {
  Button,
  Card,
  DataTable,
  Pagination,
  TextField,
  Select,
  DateField,
  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",
  CANCELLED: "error",
};

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

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

  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [supplierId, setSupplierId] = useState<number | "">("");
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");
  const debouncedSearch = useDebounce(search, 300);

  const { data: suppliersData } = useQuery(
    warehouseSupplierListOptions({ perPage: 100 }),
  );
  const suppliers = suppliersData?.data ?? [];

  const { items, pagination, isPending, isFetching } =
    usePaginatedQuery<WarehouseReceipt>(
      warehouseReceiptListOptions({
        search: debouncedSearch || undefined,
        page,
        perPage: PER_PAGE,
        status: statusFilter || undefined,
        supplier_id: supplierId ? Number(supplierId) : undefined,
        date_from: dateFrom || undefined,
        date_to: dateTo || undefined,
      }),
    );

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

  const canOperate = hasPermission("warehouse.operate");

  const resetFilters = () => {
    setSearch("");
    setStatusFilter("");
    setSupplierId("");
    setDateFrom("");
    setDateTo("");
    setPage(1);
  };

  const hasActiveFilters = !!(statusFilter || supplierId || dateFrom || dateTo);

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

  const total = pagination?.total ?? items.length;
  const subtitle = `${total} ${
    total === 1 ? "doklad" : total >= 2 && total <= 4 ? "doklady" : "dokladů"
  }`;

  const columns: DataColumn<WarehouseReceipt>[] = [
    {
      key: "receipt_number",
      header: "Číslo dokladu",
      width: "15%",
      mono: true,
      bold: true,
      render: (r) => r.receipt_number || "—",
    },
    {
      key: "supplier",
      header: "Dodavatel",
      width: "22%",
      render: (r) => r.supplier?.name || "—",
    },
    {
      key: "status",
      header: "Stav",
      width: "13%",
      render: (r) => (
        <StatusChip
          label={STATUS_LABEL[r.status] ?? r.status}
          color={STATUS_COLOR[r.status] ?? "default"}
        />
      ),
    },
    {
      key: "delivery_note_number",
      header: "Dodací list",
      width: "18%",
      mono: true,
      render: (r) => r.delivery_note_number || "—",
    },
    {
      key: "created_at",
      header: "Vytvořeno",
      width: "18%",
      mono: true,
      render: (r) => formatDate(r.created_at),
    },
    {
      key: "items_count",
      header: "Položek",
      width: "14%",
      mono: true,
      render: (r) => String(r._count?.items ?? 0),
    },
  ];

  return (
    <PageEnter>
      <PageHeader
        title="Příjmové doklady"
        subtitle={subtitle}
        actions={
          canOperate ? (
            <Button
              startIcon={PlusIcon}
              onClick={() => navigate("/warehouse/receipts/new")}
            >
              Nový doklad
            </Button>
          ) : undefined
        }
      />

      <FilterBar>
        <Box sx={{ flex: "1 1 320px" }}>
          <TextField
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            placeholder="Hledat podle čísla dokladu..."
            fullWidth
          />
        </Box>
        <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" },
              { value: "CANCELLED", label: "Zrušeno" },
            ]}
          />
        </Box>
        {suppliers.length > 0 && (
          <Box sx={{ flex: "0 0 220px" }}>
            <Select
              value={supplierId === "" ? "" : String(supplierId)}
              onChange={(val) => {
                setSupplierId(val === "" ? "" : Number(val));
                setPage(1);
              }}
              options={[
                { value: "", label: "Všichni dodavatelé" },
                ...suppliers.map((s) => ({
                  value: String(s.id),
                  label: s.name,
                })),
              ]}
            />
          </Box>
        )}
        <Box sx={{ flex: "0 0 150px" }}>
          <DateField
            value={dateFrom}
            onChange={(val) => {
              setDateFrom(val);
              setPage(1);
            }}
            label="Od"
          />
        </Box>
        <Box sx={{ flex: "0 0 150px" }}>
          <DateField
            value={dateTo}
            onChange={(val) => {
              setDateTo(val);
              setPage(1);
            }}
            label="Do"
          />
        </Box>
        {hasActiveFilters && (
          <Button variant="outlined" color="inherit" onClick={resetFilters}>
            Zrušit filtry
          </Button>
        )}
      </FilterBar>

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