import { Badge, Box, Group, Progress, Text } from '@mantine/core';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import {
  STATUS_COLORS,
  STATUS_PROGRESS,
  applicantOrCompanyName,
  localized,
  type ApplicationKind,
  type LicenseApplication,
  type LicenseStatus,
} from '@ema-platform/api';

const KIND_LABEL: Record<ApplicationKind, string> = {
  NEW: 'applications.table.kindNew',
  RENEWAL: 'applications.table.kindRenewal',
  REISSUE: 'applications.table.kindReissue',
};

const KIND_COLOR: Record<ApplicationKind, string> = {
  NEW: 'blue',
  RENEWAL: 'teal',
  REISSUE: 'orange',
};

export function applicationColumns(
  t: TFunction,
  deps: {
    language: string;
    showDate: (date: string) => string;
    statusLabel: (status: LicenseStatus) => string;
    /** Status as the applicant should read it — the exam leg resolves to the
     *  stage the registration and attempt actually record. */
    applicationStatusLabel: (app: LicenseApplication) => string;
  },
): AdvancedColumn<LicenseApplication>[] {
  return [
    {
      header: t('applications.table.licence'),
      cell: ({ row }) => (
        <Box>
          <Group gap={6} wrap="nowrap">
            <Text size="sm" fw={600}>
              {localized(row.original.licenseType?.name, deps.language) || '—'}
            </Text>
            {row.original.kind !== 'NEW' && (
              <Badge size="xs" variant="light" color={KIND_COLOR[row.original.kind]}>
                {t(KIND_LABEL[row.original.kind])}
              </Badge>
            )}
          </Group>
          <Text size="xs" c="dimmed">
            {row.original.applicationNumber}
          </Text>
        </Box>
      ),
    },
    {
      header: t('applications.table.applicant'),
      cell: ({ row }) => <Text size="sm">{applicantOrCompanyName(row.original) ?? '—'}</Text>,
    },
    {
      header: t('common.status'),
      cell: ({ row }) => (
        <Badge color={STATUS_COLORS[row.original.status]} variant="light">
          {deps.applicationStatusLabel(row.original)}
        </Badge>
      ),
    },
    {
      header: t('applications.table.progress'),
      size: 140,
      cell: ({ row }) => (
        <Progress
          value={STATUS_PROGRESS[row.original.status]}
          color={STATUS_COLORS[row.original.status]}
          size="sm"
          radius="xl"
        />
      ),
    },
    {
      header: t('common.date'),
      cell: ({ row }) => (
        <Text size="sm" c="dimmed">
          {row.original.submittedAt
            ? deps.showDate(row.original.submittedAt)
            : t('applications.card.notFiled')}
        </Text>
      ),
    },
  ];
}
