import { useNavigate } from 'react-router-dom';
import {
  Badge,
  Card,
  Center,
  Container,
  Grid,
  Group,
  Loader,
  SimpleGrid,
  Stack,
  Table,
  Text,
  Title,
} from '@mantine/core';
import { IconChevronRight } from '@tabler/icons-react';
import {
  STATUS_COLORS,
  STATUS_LABELS,
  useGetAssignedToMeQuery,
  useGetQueueQuery,
  type LicenseStatus,
} from '@ema-platform/api';

/**
 * Logistics department overview.
 *
 * Every figure is derived from the licence applications actually in the
 * system. This previously summed six hardcoded arrays, so the department head
 * saw counts for applications that had never been filed.
 */
export function LogisticsHeadDashboardPage() {
  const navigate = useNavigate();
  const queue = useGetQueueQuery();
  const mine = useGetAssignedToMeQuery();

  if (queue.isLoading || mine.isLoading) {
    return (
      <Center h={300}>
        <Loader />
      </Center>
    );
  }

  const unclaimed = queue.data?.items ?? [];
  const inProgress = mine.data?.items ?? [];
  const all = [...unclaimed, ...inProgress];

  const byStatus = all.reduce<Record<string, number>>((acc, app) => {
    acc[app.status] = (acc[app.status] ?? 0) + 1;
    return acc;
  }, {});

  const stats = [
    { label: 'Awaiting claim', value: unclaimed.length, color: 'blue' },
    { label: 'In progress', value: inProgress.length, color: 'indigo' },
    {
      label: 'Awaiting payment',
      value: byStatus['PAYMENT_PENDING'] ?? 0,
      color: 'yellow',
    },
    {
      label: 'Needs applicant action',
      value: byStatus['RESUBMIT_REQUIRED'] ?? 0,
      color: 'orange',
    },
  ];

  const recent = [...all]
    .sort((a, b) =>
      (b.submittedAt ?? b.createdAt).localeCompare(a.submittedAt ?? a.createdAt),
    )
    .slice(0, 8);

  return (
    <Container size="xl" py="md">
      <Title order={3} mb="xs">
        Logistics overview
      </Title>
      <Text size="sm" c="dimmed" mb="lg">
        Licence applications currently in the department.
      </Text>

      <SimpleGrid cols={{ base: 1, sm: 2, md: 4 }} mb="xl">
        {stats.map((stat) => (
          <Card withBorder key={stat.label} padding="md" radius="md">
            <Text size="xs" c="dimmed" tt="uppercase" fw={600}>
              {stat.label}
            </Text>
            <Text fz={32} fw={700} c={stat.color} lh={1.2}>
              {stat.value}
            </Text>
          </Card>
        ))}
      </SimpleGrid>

      <Grid>
        <Grid.Col span={{ base: 12, md: 7 }}>
          <Card withBorder padding={0} radius="md">
            <Group justify="space-between" p="md" pb="xs">
              <Text fw={600} size="sm">
                Most recent
              </Text>
              <Text
                size="xs"
                c="blue"
                style={{ cursor: 'pointer' }}
                onClick={() => navigate('/licence-review')}
              >
                View all <IconChevronRight size={11} style={{ verticalAlign: -1 }} />
              </Text>
            </Group>
            {recent.length === 0 ? (
              <Center py="xl">
                <Text size="sm" c="dimmed">
                  No licence applications yet.
                </Text>
              </Center>
            ) : (
              <Table highlightOnHover>
                <Table.Thead>
                  <Table.Tr>
                    <Table.Th>Number</Table.Th>
                    <Table.Th>Company</Table.Th>
                    <Table.Th>Status</Table.Th>
                  </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                  {recent.map((app) => (
                    <Table.Tr
                      key={app.id}
                      style={{ cursor: 'pointer' }}
                      onClick={() => navigate(`/licence-review/${app.id}`)}
                    >
                      <Table.Td>
                        <Text size="sm" fw={500}>
                          {app.applicationNumber}
                        </Text>
                      </Table.Td>
                      <Table.Td>
                        <Text size="sm">{app.companyName ?? '—'}</Text>
                      </Table.Td>
                      <Table.Td>
                        <Badge
                          size="sm"
                          variant="light"
                          color={STATUS_COLORS[app.status as LicenseStatus]}
                        >
                          {STATUS_LABELS[app.status as LicenseStatus]}
                        </Badge>
                      </Table.Td>
                    </Table.Tr>
                  ))}
                </Table.Tbody>
              </Table>
            )}
          </Card>
        </Grid.Col>

        <Grid.Col span={{ base: 12, md: 5 }}>
          <Card withBorder padding="md" radius="md">
            <Text fw={600} size="sm" mb="sm">
              By status
            </Text>
            {Object.keys(byStatus).length === 0 ? (
              <Text size="sm" c="dimmed">
                Nothing in the pipeline.
              </Text>
            ) : (
              <Stack gap="xs">
                {Object.entries(byStatus)
                  .sort((a, b) => b[1] - a[1])
                  .map(([status, count]) => (
                    <Group key={status} justify="space-between">
                      <Badge
                        variant="light"
                        color={STATUS_COLORS[status as LicenseStatus]}
                      >
                        {STATUS_LABELS[status as LicenseStatus] ?? status}
                      </Badge>
                      <Text size="sm" fw={600}>
                        {count}
                      </Text>
                    </Group>
                  ))}
              </Stack>
            )}
          </Card>
        </Grid.Col>
      </Grid>
    </Container>
  );
}

export default LogisticsHeadDashboardPage;
