import { Link } from 'react-router-dom';
import { Badge, Card, Group, SimpleGrid, Table, Text } from '@mantine/core';
import type { ReactNode } from 'react';
import type { VesselReport } from '@ema-platform/api';
import { useDateDisplayer } from '@ema-platform/shared';
import { expiryUrgency, formatNumber } from './report-format';

/**
 * The worklists.
 *
 * Plain Mantine tables rather than `AdvancedTable`: every one of these is
 * already capped server-side by `tableLimit`, so the pagination, search and
 * column-picker that component brings would all be controls over a list that
 * is only ever ten rows of a much longer one. Each card links out to the screen
 * that does own the full list.
 */
function TableCard({
  title,
  subtitle,
  to,
  linkLabel,
  empty,
  head,
  children,
}: {
  title: string;
  subtitle?: string;
  to?: string;
  linkLabel?: string;
  empty: boolean;
  head: string[];
  children: ReactNode;
}) {
  return (
    <Card withBorder radius="md" p="md">
      <Group justify="space-between" mb="xs" wrap="nowrap">
        <div>
          <Text fw={600} size="sm">
            {title}
          </Text>
          {subtitle && (
            <Text size="xs" c="dimmed">
              {subtitle}
            </Text>
          )}
        </div>
        {to && (
          <Text component={Link} to={to} size="xs" c="blue">
            {linkLabel ?? 'View all'}
          </Text>
        )}
      </Group>
      {empty ? (
        <Text size="sm" c="dimmed" py="lg" ta="center">
          Nothing to show.
        </Text>
      ) : (
        <Table highlightOnHover verticalSpacing="xs" fz="sm">
          <Table.Thead>
            <Table.Tr>
              {head.map((column) => (
                <Table.Th key={column}>{column}</Table.Th>
              ))}
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>{children}</Table.Tbody>
        </Table>
      )}
    </Card>
  );
}

export function ReportTables({ report }: { report: VesselReport }) {
  const showDate = useDateDisplayer();
  const { tables, filters } = report;

  return (
    <SimpleGrid cols={{ base: 1, lg: 2 }} spacing="md" mt="md">
      <TableCard
        title="Certificates expiring"
        subtitle={`within ${filters.expiringWithinDays} days`}
        to="/licence-register"
        empty={tables.expiringCertificates.length === 0}
        head={['Vessel', 'Certificate', 'Expires', 'Days']}
      >
        {tables.expiringCertificates.map((row) => (
          <Table.Tr key={row.vesselId}>
            <Table.Td>
              <Text size="sm" fw={500}>
                {row.name}
              </Text>
              <Text size="xs" c="dimmed">
                {row.registrationNumber}
                {row.ownerName ? ` · ${row.ownerName}` : ''}
              </Text>
            </Table.Td>
            <Table.Td>{row.certificateNumber ?? '—'}</Table.Td>
            <Table.Td>{showDate(row.expiryDate)}</Table.Td>
            <Table.Td>
              <Badge
                size="sm"
                variant="light"
                color={expiryUrgency(row.daysToExpiry)}
              >
                {/* 0 is today, and a certificate is valid through its last day. */}
                {row.daysToExpiry === 0
                  ? 'Today'
                  : `${formatNumber(row.daysToExpiry)} d`}
              </Badge>
            </Table.Td>
          </Table.Tr>
        ))}
      </TableCard>

      <TableCard
        title="Recent registrations"
        to="/vessel-registration-queue"
        linkLabel="Open register"
        empty={tables.recentRegistrations.length === 0}
        head={['Vessel', 'Category', 'Flag', 'Registered']}
      >
        {tables.recentRegistrations.map((row) => (
          <Table.Tr key={row.vesselId}>
            <Table.Td>
              <Text size="sm" fw={500}>
                {row.name}
              </Text>
              <Text size="xs" c="dimmed">
                {row.registrationNumber}
                {row.vesselType ? ` · ${row.vesselType}` : ''}
              </Text>
            </Table.Td>
            <Table.Td>
              {row.category === 'SEA_GOING' ? 'Sea-going' : 'Inland'}
            </Table.Td>
            <Table.Td>{row.flagState ?? '—'}</Table.Td>
            <Table.Td>{showDate(row.registeredAt)}</Table.Td>
          </Table.Tr>
        ))}
      </TableCard>

      <TableCard
        title="Applications in the queue"
        subtitle="oldest first"
        to="/licence-review/type/VESSEL_REGISTRATION"
        linkLabel="Open queue"
        empty={tables.pendingApplications.length === 0}
        head={['Application', 'Status', 'Submitted', 'Open']}
      >
        {tables.pendingApplications.map((row) => (
          <Table.Tr key={row.applicationNumber}>
            <Table.Td>
              <Text size="sm" fw={500}>
                {row.applicationNumber}
              </Text>
              <Text size="xs" c="dimmed">
                {row.kind === 'RENEWAL' ? 'Renewal' : 'New'}
                {row.adjustmentRound > 0
                  ? ` · ${row.adjustmentRound} adjustment round${row.adjustmentRound === 1 ? '' : 's'}`
                  : ''}
              </Text>
            </Table.Td>
            <Table.Td>
              <Badge size="sm" variant="light">
                {row.status.replaceAll('_', ' ')}
              </Badge>
            </Table.Td>
            <Table.Td>
              {row.submittedAt ? showDate(row.submittedAt) : '—'}
            </Table.Td>
            <Table.Td>
              <Badge
                size="sm"
                variant="light"
                color={row.daysOpen > 30 ? 'red' : row.daysOpen > 14 ? 'orange' : 'gray'}
              >
                {formatNumber(row.daysOpen)} d
              </Badge>
            </Table.Td>
          </Table.Tr>
        ))}
      </TableCard>

      <TableCard
        title="Recent incidents"
        empty={tables.recentIncidents.length === 0}
        head={['Vessel', 'Occurred', 'Severity', 'Reported by']}
      >
        {tables.recentIncidents.map((row) => (
          <Table.Tr key={row.id}>
            <Table.Td>
              <Text size="sm" fw={500}>
                {row.vesselName}
              </Text>
              <Text size="xs" c="dimmed" lineClamp={1}>
                {row.description}
              </Text>
            </Table.Td>
            <Table.Td>{showDate(row.occurredAt)}</Table.Td>
            <Table.Td>{row.severity ?? '—'}</Table.Td>
            <Table.Td>
              <Badge size="sm" variant="light" color={row.reportedByOfficer ? 'blue' : 'gray'}>
                {row.reportedByOfficer ? 'Officer' : 'Owner'}
              </Badge>
            </Table.Td>
          </Table.Tr>
        ))}
      </TableCard>
    </SimpleGrid>
  );
}
