import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Card, Center, Loader, Stack, Text } from '@mantine/core';
import { useDebouncedValue } from '@mantine/hooks';
import { Plus } from 'lucide-react';

import { PageContainer, PageHeader } from '@/components/page';
import {
  CreateWarehouseModal,
  WarehouseCardView,
  WarehouseFilters,
  WarehouseTable,
  type WarehouseView,
} from '@/components/warehouses';
import ListControls from '@/components/common/ListControls';
// Generic list footer — already shared by the fleet and train-scheduling lists
// despite the ruleEngine path.
import RuleEngineListFooter from '@/components/ruleEngine/RuleEngineListFooter';
import { useListControls } from '@/hooks/useListControls';
import { useWarehouses } from '@/hooks/useWarehouses';
import type { Warehouse, WarehouseFilter } from '@/types/warehouse';

export default function WarehouseListPage() {
  const navigate = useNavigate();
  const [filter, setFilter] = useState<WarehouseFilter>({});
  const [view, setView] = useState<WarehouseView>('table');
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Warehouse | null>(null);

  const [debouncedSearch] = useDebouncedValue(filter.search, 300);
  const queryFilter = useMemo<WarehouseFilter>(
    () => ({ ...filter, search: debouncedSearch }),
    [filter, debouncedSearch],
  );

  const { data, isLoading, isError } = useWarehouses(queryFilter);
  const warehouses = data ?? [];

  // Search stays with WarehouseFilters — it is server-side and debounced, so
  // re-doing it client-side here would be a regression. This adds only the date
  // range + pagination, shared by both the table and card views.
  const controls = useListControls(warehouses, { dateKey: 'createdAt' });

  const openCreate = () => {
    setEditing(null);
    setModalOpen(true);
  };
  const openEdit = (warehouse: Warehouse) => {
    setEditing(warehouse);
    setModalOpen(true);
  };
  const openDetail = (warehouse: Warehouse) => navigate(`/dashboard/warehouses/${warehouse.id}`);

  return (
    <PageContainer>
      <PageHeader
        title="Warehouses"
        subtitle="Manage warehouses, yards and zones."
        action={
          <Button leftSection={<Plus size={16} />} onClick={openCreate}>
            Create Warehouse
          </Button>
        }
      />

      <Card>
        <Stack gap="md">
          <WarehouseFilters filter={filter} onChange={setFilter} view={view} onViewChange={setView} />

          <ListControls
            showSearch={false}
            search=""
            onSearchChange={() => {}}
            dateFrom={controls.dateFrom}
            onDateFromChange={controls.setDateFrom}
            dateTo={controls.dateTo}
            onDateToChange={controls.setDateTo}
            dateLabel="Created"
            hasFilters={controls.hasFilters}
            onReset={controls.reset}
          />

          {isLoading ? (
            <Center py="xl">
              <Loader />
            </Center>
          ) : isError ? (
            <Text c="red" ta="center" py="xl">
              Failed to load warehouses.
            </Text>
          ) : (
            <>
              {view === 'table' ? (
                <WarehouseTable warehouses={controls.pagedRows} onView={openDetail} onEdit={openEdit} />
              ) : (
                <WarehouseCardView warehouses={controls.pagedRows} onView={openDetail} onEdit={openEdit} />
              )}
              <RuleEngineListFooter
                pagination={controls.pagination}
                pageCount={controls.pageCount}
                totalCount={controls.totalCount}
                itemLabel="warehouses"
                onPaginationChange={controls.setPagination}
              />
            </>
          )}
        </Stack>
      </Card>

      <CreateWarehouseModal opened={modalOpen} onClose={() => setModalOpen(false)} warehouse={editing} />
    </PageContainer>
  );
}
