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 { useQuery } from '@tanstack/react-query';

import { api } from '@/services/api';
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 } = useQuery(
    api.warehouses.list.queryOptions({ input: { filter: queryFilter } }),
  );
  const warehouses = data ?? [];

  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} />

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

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