import { Card, Group, Loader, Stack, Text, ThemeIcon } from '@mantine/core';
import { Hourglass } from 'lucide-react';
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';

import { useWarehouseDwellStats } from '@/hooks/useWarehouses';
import { formatDays } from './options';

/** Green → amber → red as items age. Aligned with the zone-occupancy heat scale. */
const BUCKET_COLORS = ['#12b886', '#40c057', '#f08c00', '#fa5252'];

/**
 * Dwell time of items still in the warehouse: the average, plus how the current
 * stock is spread across aging buckets (0–3 / 4–7 / 8–14 / 15+ days).
 */
export function DwellAgingCard() {
  const { data, isLoading } = useWarehouseDwellStats();
  const buckets = data?.buckets ?? [];
  const hasItems = (data?.inWarehouseCount ?? 0) > 0;

  return (
    <Card withBorder radius="lg" padding="lg" h="100%">
      <Group gap="sm" mb="md">
        <ThemeIcon size="lg" radius="md" color="grape" variant="light">
          <Hourglass size={20} />
        </ThemeIcon>
        <div>
          <Text fw={700}>Dwell time &amp; aging</Text>
          <Text size="xs" c="dimmed">
            How long current stock has been held
          </Text>
        </div>
      </Group>

      {isLoading ? (
        <Group justify="center" h={220}>
          <Loader />
        </Group>
      ) : (
        <Group align="stretch" gap="lg" wrap="nowrap">
          <Stack gap={2} justify="center" style={{ minWidth: 110 }}>
            <Text size="xs" c="dimmed" tt="uppercase" fw={700}>
              Avg dwell
            </Text>
            <Text fw={800} fz={30} lh={1.1}>
              {hasItems ? formatDays(data?.avgDwellDays) : '—'}
            </Text>
            <Text size="xs" c="dimmed">
              {data?.inWarehouseCount ?? 0} item{(data?.inWarehouseCount ?? 0) === 1 ? '' : 's'} in warehouse
            </Text>
          </Stack>

          <div style={{ flex: 1, minWidth: 0 }}>
            {hasItems ? (
              <ResponsiveContainer width="100%" height={200}>
                <BarChart
                  data={buckets}
                  layout="vertical"
                  margin={{ top: 4, right: 16, left: 8, bottom: 0 }}
                >
                  <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="var(--mantine-color-gray-2)" />
                  <XAxis type="number" allowDecimals={false} tick={{ fontSize: 12 }} />
                  <YAxis type="category" dataKey="label" width={72} tick={{ fontSize: 12 }} />
                  <Tooltip cursor={{ fill: 'var(--mantine-color-gray-1)' }} />
                  <Bar dataKey="count" name="Items" radius={[0, 6, 6, 0]}>
                    {buckets.map((b, i) => (
                      <Cell key={b.key} fill={BUCKET_COLORS[i] ?? '#868e96'} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <Group justify="center" align="center" h={200}>
                <Text c="dimmed" size="sm">
                  No items currently in the warehouse.
                </Text>
              </Group>
            )}
          </div>
        </Group>
      )}
    </Card>
  );
}
