import { useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ActionIcon,
  Button,
  Card,
  Center,
  Container,
  Group,
  Loader,
  Stack,
  Select,
  Tabs,
  Text,
} from '@mantine/core';
import { ArrowLeft, Boxes, LayoutGrid, Package, Pencil, Plus } from 'lucide-react';

import { DataTable, type ColumnDef } from '@edr/ui-common';

import { KpiStrip, PageContainer, PageHeader } from '@/components/page';
import {
  CreateYardModal,
  CreateZoneModal,
  InventoryWorkbench,
  WarehouseStatusBadge,
  WarehouseTypeBadge,
  formatCapacity,
  humanizeEnum,
} from '@/components/warehouses';
import { useQuery } from '@tanstack/react-query';

import { api } from '@/services/api';
import type { WarehouseYard, WarehouseZone } from '@/types/warehouse';

export default function WarehouseDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const { data: warehouse, isLoading } = useQuery(
    api.warehouses.getById.queryOptions({
      input: { id: id ?? '' },
      enabled: Boolean(id),
    }),
  );
  const yardsQuery = useQuery(
    api.warehouses.listYards.queryOptions({
      input: { warehouseId: id ?? '' },
      enabled: Boolean(id),
    }),
  );

  const [yardModalOpen, setYardModalOpen] = useState(false);
  const [editingYard, setEditingYard] = useState<WarehouseYard | null>(null);

  const [zoneModalOpen, setZoneModalOpen] = useState(false);
  const [editingZone, setEditingZone] = useState<WarehouseZone | null>(null);
  const [selectedYardId, setSelectedYardId] = useState<string | null>(null);

  const zonesQuery = useQuery(
    api.warehouses.listZones.queryOptions({
      input: { yardId: selectedYardId ?? '' },
      enabled: Boolean(selectedYardId),
    }),
  );

  const inventoryQuery = useQuery(
    api.warehouses.listInventory.queryOptions({
      input: { filter: id ? { warehouseId: id } : undefined },
    }),
  );

  const yards = yardsQuery.data ?? [];
  const yardOptions = useMemo(
    () => yards.map((y) => ({ value: y.id, label: `${y.name} (${y.code})` })),
    [yards],
  );

  const yardColumns = useMemo<ColumnDef<WarehouseYard>[]>(
    () => [
      { id: 'name', header: 'Name', cell: ({ row }) => row.original.name },
      { id: 'code', header: 'Code', cell: ({ row }) => row.original.code },
      { id: 'type', header: 'Type', cell: ({ row }) => humanizeEnum(row.original.type) },
      {
        id: 'weight',
        header: 'Weight (cur / cap)',
        cell: ({ row }) => formatCapacity(row.original.currentWeight, row.original.capacityWeight),
      },
      {
        id: 'containers',
        header: 'Containers (cur / cap)',
        cell: ({ row }) =>
          formatCapacity(row.original.currentContainers, row.original.capacityContainers),
      },
      {
        id: 'status',
        header: 'Status',
        cell: ({ row }) => <WarehouseStatusBadge status={row.original.status} />,
      },
      {
        id: 'actions',
        header: 'Actions',
        meta: { headerClassName: 'text-right', cellClassName: 'text-right' },
        cell: ({ row }) => (
          <ActionIcon
            variant="subtle"
            color="gray"
            onClick={() => {
              setEditingYard(row.original);
              setYardModalOpen(true);
            }}
          >
            <Pencil size={16} />
          </ActionIcon>
        ),
      },
    ],
    [],
  );

  const zoneColumns = useMemo<ColumnDef<WarehouseZone>[]>(
    () => [
      { id: 'name', header: 'Name', cell: ({ row }) => row.original.name },
      { id: 'code', header: 'Code', cell: ({ row }) => row.original.code },
      { id: 'type', header: 'Type', cell: ({ row }) => humanizeEnum(row.original.type) },
      {
        id: 'weight',
        header: 'Weight (cur / cap)',
        cell: ({ row }) => formatCapacity(row.original.currentWeight, row.original.capacityWeight),
      },
      {
        id: 'containers',
        header: 'Containers (cur / cap)',
        cell: ({ row }) =>
          formatCapacity(row.original.currentContainers, row.original.capacityContainers),
      },
      {
        id: 'status',
        header: 'Status',
        cell: ({ row }) => <WarehouseStatusBadge status={row.original.status} />,
      },
      {
        id: 'actions',
        header: 'Actions',
        meta: { headerClassName: 'text-right', cellClassName: 'text-right' },
        cell: ({ row }) => (
          <ActionIcon
            variant="subtle"
            color="gray"
            onClick={() => {
              setEditingZone(row.original);
              setZoneModalOpen(true);
            }}
          >
            <Pencil size={16} />
          </ActionIcon>
        ),
      },
    ],
    [],
  );

  if (isLoading) {
    return (
      <Center mih="60vh">
        <Loader />
      </Center>
    );
  }

  if (!warehouse) {
    return (
      <Container size="sm" py="xl">
        <Stack align="center" gap="md">
          <Text fw={700}>Warehouse not found</Text>
          <Button variant="default" leftSection={<ArrowLeft size={16} />} onClick={() => navigate('/dashboard/warehouses')}>
            Back to warehouses
          </Button>
        </Stack>
      </Container>
    );
  }

  return (
    <PageContainer>
      <PageHeader
        breadcrumbs={[
          { label: 'Warehouses', href: '/dashboard/warehouses' },
          { label: warehouse.name },
        ]}
        backTo="/dashboard/warehouses"
        title={warehouse.name}
        subtitle={`${warehouse.code}${
          warehouse.locationName ? ` · ${warehouse.locationName}` : ''
        }`}
        meta={
          <Group gap="xs" wrap="nowrap">
            <WarehouseTypeBadge type={warehouse.type} />
            <WarehouseStatusBadge status={warehouse.status} />
          </Group>
        }
      />

      <Tabs defaultValue="overview">
        <Tabs.List>
          <Tabs.Tab value="overview" leftSection={<LayoutGrid size={16} />}>
            Overview
          </Tabs.Tab>
          <Tabs.Tab value="yards" leftSection={<Boxes size={16} />}>
            Yards
          </Tabs.Tab>
          <Tabs.Tab value="zones" leftSection={<LayoutGrid size={16} />}>
            Zones
          </Tabs.Tab>
          <Tabs.Tab value="inventory" leftSection={<Package size={16} />}>
            Inventory
          </Tabs.Tab>
        </Tabs.List>

        {/* OVERVIEW */}
        <Tabs.Panel value="overview" pt="lg">
          <KpiStrip
            items={[
              { label: 'Type', value: humanizeEnum(warehouse.type) },
              { label: 'Yards', value: yards.length },
              {
                label: 'Weight (cur / cap)',
                value: formatCapacity(warehouse.currentWeight, warehouse.capacityWeight),
              },
              {
                label: 'Containers (cur / cap)',
                value: formatCapacity(
                  warehouse.currentContainers,
                  warehouse.capacityContainers,
                ),
              },
            ]}
          />
        </Tabs.Panel>

          {/* YARDS */}
          <Tabs.Panel value="yards" pt="lg">
            <Card withBorder radius="md" padding="lg">
              <Stack gap="md">
                <Group justify="space-between">
                  <Text fw={600}>Yards</Text>
                  <Button
                    size="sm"
                    leftSection={<Plus size={16} />}
                    onClick={() => {
                      setEditingYard(null);
                      setYardModalOpen(true);
                    }}
                  >
                    Create Yard
                  </Button>
                </Group>

                <DataTable
                  columns={yardColumns}
                  data={yards}
                  status={
                    yardsQuery.isLoading
                      ? 'loading'
                      : yardsQuery.isError
                        ? 'error'
                        : 'success'
                  }
                  emptyMessage="No yards yet."
                  containerClassName="border-0 shadow-none"
                  error={
                    yardsQuery.isError
                      ? {
                          message: 'Failed to load yards.',
                          onRetry: () => void yardsQuery.refetch(),
                        }
                      : undefined
                  }
                />
              </Stack>
            </Card>
          </Tabs.Panel>

          {/* ZONES */}
          <Tabs.Panel value="zones" pt="lg">
            <Card withBorder radius="md" padding="lg">
              <Stack gap="md">
                <Group justify="space-between" align="flex-end">
                  <Select
                    label="Yard"
                    placeholder="Select a yard"
                    data={yardOptions}
                    value={selectedYardId}
                    onChange={setSelectedYardId}
                    w={280}
                    searchable
                  />
                  <Button
                    size="sm"
                    leftSection={<Plus size={16} />}
                    disabled={!selectedYardId}
                    onClick={() => {
                      setEditingZone(null);
                      setZoneModalOpen(true);
                    }}
                  >
                    Create Zone
                  </Button>
                </Group>

                {!selectedYardId ? (
                  <Text c="dimmed" ta="center" py="lg">
                    Select a yard to view its zones.
                  </Text>
                ) : (
                  <DataTable
                    columns={zoneColumns}
                    data={zonesQuery.data ?? []}
                    status={
                      zonesQuery.isLoading
                        ? 'loading'
                        : zonesQuery.isError
                          ? 'error'
                          : 'success'
                    }
                    emptyMessage="No zones in this yard yet."
                    containerClassName="border-0 shadow-none"
                    error={
                      zonesQuery.isError
                        ? {
                            message: 'Failed to load zones.',
                            onRetry: () => void zonesQuery.refetch(),
                          }
                        : undefined
                    }
                  />
                )}
              </Stack>
            </Card>
          </Tabs.Panel>

          {/* INVENTORY */}
          <Tabs.Panel value="inventory" pt="lg">
            <Card withBorder radius="md" padding="lg">
              <InventoryWorkbench items={inventoryQuery.data ?? []} isLoading={inventoryQuery.isLoading} />
            </Card>
          </Tabs.Panel>
      </Tabs>

      {id && (
        <CreateYardModal
          opened={yardModalOpen}
          onClose={() => setYardModalOpen(false)}
          warehouseId={id}
          yard={editingYard}
        />
      )}
      {selectedYardId && (
        <CreateZoneModal
          opened={zoneModalOpen}
          onClose={() => setZoneModalOpen(false)}
          yardId={selectedYardId}
          zone={editingZone}
        />
      )}
    </PageContainer>
  );
}
