import { Badge, Card, Group, Loader, Progress, SimpleGrid, Stack, Text } from '@mantine/core';
import { LayoutGrid } from 'lucide-react';

import { useZoneOccupancy } from '@/hooks/useWarehouses';
import type { ZoneOccupancy } from '@/types/warehouse';

/** Green < 60%, amber 60–85%, red > 85%. */
function tone(pct: number | null): { color: string; label: string } {
  if (pct == null) return { color: 'gray', label: 'No capacity set' };
  if (pct > 85) return { color: 'red', label: 'Full' };
  if (pct >= 60) return { color: 'orange', label: 'Filling' };
  return { color: 'teal', label: 'Space' };
}

function capacityLabel(z: ZoneOccupancy): string {
  if (z.capacityContainers && z.capacityContainers > 0) {
    return `${z.usedItems} / ${z.capacityContainers} items`;
  }
  if (z.capacityWeight && z.capacityWeight > 0) {
    return `${z.usedItems} item(s) · ${z.usedWeight.toLocaleString()} kg`;
  }
  return `${z.usedItems} item(s)`;
}

interface ZoneOccupancyHeatmapProps {
  /** Scope to one yard; omit for all zones. */
  yardId?: string;
}

/**
 * Occupancy heatmap: one tile per zone, coloured by how full it is. Occupancy is
 * container-count based (unit-consistent); weight is shown as context only.
 */
export function ZoneOccupancyHeatmap({ yardId }: ZoneOccupancyHeatmapProps) {
  const { data: zones = [], isLoading } = useZoneOccupancy(yardId);

  if (isLoading) {
    return (
      <Group justify="center" py="lg">
        <Loader size="sm" />
      </Group>
    );
  }

  if (zones.length === 0) {
    return (
      <Text c="dimmed" ta="center" py="lg" size="sm">
        No active zones to show occupancy for.
      </Text>
    );
  }

  return (
    <Stack gap="sm">
      <Group gap="xs">
        <LayoutGrid size={16} />
        <Text fw={600} size="sm">
          Zone occupancy
        </Text>
        <Text size="xs" c="dimmed">
          ({zones.length} zone{zones.length !== 1 ? 's' : ''})
        </Text>
      </Group>

      <SimpleGrid cols={{ base: 1, xs: 2, sm: 3, lg: 4 }} spacing="sm">
        {zones.map((z) => {
          const t = tone(z.occupancyPct);
          const pct = z.occupancyPct ?? 0;
          return (
            <Card key={z.id} withBorder radius="md" padding="sm">
              <Stack gap={6}>
                <Group justify="space-between" wrap="nowrap" gap="xs">
                  <Text fw={600} size="sm" truncate title={z.name}>
                    {z.name}
                  </Text>
                  <Badge color={t.color} variant="light" size="sm">
                    {z.occupancyPct == null ? '—' : `${Math.round(pct)}%`}
                  </Badge>
                </Group>
                <Progress value={Math.min(pct, 100)} color={t.color} size="lg" radius="sm" />
                <Group justify="space-between" gap="xs">
                  <Text size="xs" c="dimmed">
                    {capacityLabel(z)}
                  </Text>
                  <Text size="xs" c={t.color === 'gray' ? 'dimmed' : t.color}>
                    {t.label}
                  </Text>
                </Group>
              </Stack>
            </Card>
          );
        })}
      </SimpleGrid>
    </Stack>
  );
}
