import { useNavigate } from 'react-router-dom';
import { Badge, Card, Center, Divider, Group, Loader, SimpleGrid, Stack, Text, ThemeIcon } from '@mantine/core';
import {
  ClipboardCheck,
  ClipboardList,
  ShieldCheck,
  PackageCheck,
  PackagePlus,
  PackageSearch,
  CircleCheck,
  Send,
  Truck,
  Warehouse as WarehouseIcon,
  Boxes,
  Layers,
} from 'lucide-react';

import { PageContainer, PageHeader } from '@/components/page';
import {
  AccrualDashboard,
  CycleTimeCard,
  DwellAgingCard,
  GateThroughputCard,
  WarehouseDashboardCharts,
  WarehouseOpsKpiStrip,
  ZoneOccupancyHeatmap,
} from '@/components/warehouses';
import { useWarehouseDashboard } from '@/hooks/useWarehouses';
import type { WarehouseDashboard } from '@/types/warehouse';

function SectionTitle({ children }: { children: React.ReactNode }) {
  return (
    <Text fw={700} fz="sm" tt="uppercase" c="edr-muted" style={{ letterSpacing: 0.4 }}>
      {children}
    </Text>
  );
}

interface Metric {
  key: keyof WarehouseDashboard;
  label: string;
  icon: React.ReactNode;
  /** Route to navigate to when the card is clicked. */
  to: string;
  theme: string;
}

const ORANGE = 'rgb(241, 147, 23)';
const GREEN = '#084b21';

const METRICS: Metric[] = [
  { key: 'totalWarehouses', label: 'Total Warehouses', icon: <WarehouseIcon size={22} />, to: '/dashboard/warehouses', theme: ORANGE },
  { key: 'totalInventory', label: 'Total Inventory', icon: <Boxes size={22} />, to: '/dashboard/warehouse-inventory', theme: GREEN },
  { key: 'receivedToday', label: 'Received Today', icon: <PackagePlus size={22} />, to: '/dashboard/warehouse-inventory?status=RECEIVED', theme: ORANGE },
  { key: 'awaitingInspection', label: 'Awaiting Inspection', icon: <ClipboardList size={22} />, to: '/dashboard/warehouse-inventory?status=RECEIVED', theme: GREEN },
  { key: 'inspected', label: 'Inspected', icon: <ShieldCheck size={22} />, to: '/dashboard/warehouse-inventory', theme: ORANGE },
  { key: 'stored', label: 'Stored', icon: <Layers size={22} />, to: '/dashboard/warehouse-inventory?status=STORED', theme: GREEN },
  { key: 'reserved', label: 'Reserved', icon: <ClipboardCheck size={22} />, to: '/dashboard/warehouse-inventory?status=RESERVED', theme: ORANGE },
  { key: 'readyForLoading', label: 'Ready For Loading', icon: <PackageCheck size={22} />, to: '/dashboard/loading-queue', theme: GREEN },
  { key: 'loaded', label: 'Loaded', icon: <Truck size={22} />, to: '/dashboard/loaded-inventory', theme: ORANGE },
  { key: 'dispatched', label: 'Dispatched', icon: <Send size={22} />, to: '/dashboard/dispatch-queue', theme: GREEN },
  { key: 'readyForPickup', label: 'Ready For Pickup', icon: <PackageSearch size={22} />, to: '/dashboard/warehouse-inventory?status=READY_FOR_PICKUP', theme: ORANGE },
  { key: 'delivered', label: 'Delivered', icon: <CircleCheck size={22} />, to: '/dashboard/warehouse-inventory?status=DELIVERED', theme: GREEN },
];

export default function WarehouseDashboardPage() {
  const navigate = useNavigate();
  const { data, isError, isLoading } = useWarehouseDashboard();

  return (
    <PageContainer>
      <PageHeader
        title="Warehouse Dashboard"
        subtitle="Live overview of warehouse capacity and inventory lifecycle."
        action={
          <Badge
            color="edr-green"
            variant="light"
            size="lg"
            leftSection={
              <span
                style={{
                  display: 'inline-block',
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  background: 'var(--mantine-color-edr-green-6)',
                }}
              />
            }
          >
            Live · updates every 60s
          </Badge>
        }
      />

      {isLoading ? (
        <Center py="xl">
          <Loader />
        </Center>
      ) : isError ? (
        <Center py="xl">
          <Text c="red">Failed to load warehouse dashboard.</Text>
        </Center>
      ) : (
        <Stack gap="xl">
          {/* Needs attention — live ops counters (received today, pending
              inspection, trucks on-site, items aging > 7 days). */}
          <Stack gap="sm">
            <SectionTitle>Needs attention</SectionTitle>
            <WarehouseOpsKpiStrip />
          </Stack>

          <Divider />

          <SimpleGrid cols={{ base: 1, xs: 2, md: 4 }} spacing="md">
            {METRICS.map((metric) => (
              <Card
                key={metric.key}
                padding="lg"
                onClick={() => navigate(metric.to)}
                className="cursor-pointer transition-[transform,border-color] duration-150 hover:-translate-y-0.5 hover:border-edr-primary!"
              >
                <Group justify="space-between" align="flex-start" wrap="nowrap">
                  <div>
                    <Text size="xs" c="edr-muted" tt="uppercase" fw={700} style={{ letterSpacing: 0.4 }}>
                      {metric.label}
                    </Text>
                    <Text fw={800} fz={32} mt={8} c="edr-text" lh={1.1}>
                      {data ? data[metric.key] : 0}
                    </Text>
                  </div>
                  <ThemeIcon
                    variant="light"
                    size={46}
                    radius="md"
                    style={{ backgroundColor: `${metric.theme}1a`, color: metric.theme }}
                  >
                    {metric.icon}
                  </ThemeIcon>
                </Group>
              </Card>
            ))}
          </SimpleGrid>

          <Stack gap="sm">
            <SectionTitle>Flow</SectionTitle>
            <WarehouseDashboardCharts data={data} />
          </Stack>

          <Stack gap="sm">
            <SectionTitle>Performance</SectionTitle>
            <SimpleGrid cols={{ base: 1, lg: 2, xl: 3 }} spacing="md">
              <DwellAgingCard />
              <CycleTimeCard />
              <GateThroughputCard />
            </SimpleGrid>
          </Stack>

          <Stack gap="sm">
            <SectionTitle>Zone capacity</SectionTitle>
            <ZoneOccupancyHeatmap />
          </Stack>

          <Stack gap="sm">
            <SectionTitle>Demurrage &amp; storage exceptions</SectionTitle>
            <AccrualDashboard />
          </Stack>
        </Stack>
      )}
    </PageContainer>
  );
}
