import { useNavigate } from 'react-router-dom';
import {Badge, Card, Center, Container, Grid, Group, Loader, SimpleGrid, Stack, Text} from '@mantine/core';
import { IconChevronRight } from '@tabler/icons-react';
import { AdvancedTable, PageHeader, PageLoader, useServerTable } from '@ema-platform/ui';
import {
  STATUS_COLORS,
  STATUS_LABELS,
  useGetAssignedToMeQuery,
  useGetQueueQuery,
  type LicenseStatus,
} from '@ema-platform/api';
import { logisticsHeadDashboardColumns } from './columns';

/**
 * 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();
  const table = useServerTable();

  if (queue.isLoading || mine.isLoading) {
    return <PageLoader label="Loading Dashboard…" height={400} />;
  }

  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);

  const paged = table.paginate(recent);

  return (
    <Container size="xl" py="md">
      <PageHeader
        title="Logistics overview"
        subtitle="Licence applications currently in the department."
      />

      <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>
            <AdvancedTable
              tableName="Most recent"
              columns={logisticsHeadDashboardColumns}
              data={paged.rows}
              itemCount={paged.itemCount}
              pageIndex={paged.pageIndex}
              onPageChange={table.setPageIndex}
              pageSize={table.pageSize}
              refresh={() => {
                queue.refetch();
                mine.refetch();
              }}
              emptyText="No licence applications yet."
              onRowClick={(app) => navigate(`/licence-review/${app.id}`)}
            />
          </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;
