import { type StatusTone } from '@ema-platform/shared';
import { Badge, Group, Text, Tooltip } from '@mantine/core';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import { StatusBadge } from '@ema-platform/ui';
import { seaServiceDays, type MedicalCertificate, type SeaServiceRecord } from '@ema-platform/api';

const RECORD_STATUS_TONES: Record<string, StatusTone> = {
  SUBMITTED: 'info',
  VERIFIED: 'success',
  REJECTED: 'danger',
};

export function fitnessOptions(t: TFunction) {
  return [
    { value: 'FIT', label: t('seaRecords.columns.fitnessOptions.FIT') },
    {
      value: 'FIT_WITH_RESTRICTIONS',
      label: t('seaRecords.columns.fitnessOptions.FIT_WITH_RESTRICTIONS'),
    },
    { value: 'UNFIT', label: t('seaRecords.columns.fitnessOptions.UNFIT') },
  ];
}

export function seaServiceColumns(
  t: TFunction,
  showDate: (date: string) => string,
): AdvancedColumn<SeaServiceRecord>[] {
  return [
    {
      header: t('seaRecords.columns.vessel'),
      cell: ({ row }) => (
        <>
          <Text fw={600} size="sm">
            {row.original.vesselName}
          </Text>
          {row.original.imoNumber && (
            <Text size="xs" c="dimmed">
              {t('seaRecords.columns.imo', { number: row.original.imoNumber })}
            </Text>
          )}
          {(row.original.vesselType || row.original.flagState || row.original.grossTonnage) && (
            <Text size="xs" c="dimmed">
              {[
                row.original.vesselType,
                row.original.flagState,
                row.original.grossTonnage ? `${row.original.grossTonnage} GT` : null,
              ]
                .filter(Boolean)
                .join(' · ')}
            </Text>
          )}
        </>
      ),
    },
    { header: t('seaRecords.columns.rank'), accessorKey: 'rank' },
    {
      header: t('seaRecords.columns.from'),
      accessorKey: 'engagementDate',
      cell: ({ row }) => showDate(row.original.engagementDate),
    },
    {
      header: t('seaRecords.columns.to'),
      accessorKey: 'dischargeDate',
      cell: ({ row }) => showDate(row.original.dischargeDate),
    },
    {
      header: t('seaRecords.columns.days', { defaultValue: 'Days' }),
      align: 'right',
      cell: ({ row }) => (
        <Text size="sm" fw={600}>
          {seaServiceDays(row.original.engagementDate, row.original.dischargeDate) ?? '—'}
        </Text>
      ),
    },
    {
      header: t('common.status'),
      cell: ({ row }) => (
        <Tooltip
          label={row.original.verificationRemark ?? ''}
          disabled={!row.original.verificationRemark}
        >
          <StatusBadge
            tone={RECORD_STATUS_TONES[row.original.status]}
            label={t(`seaRecords.columns.recordStatus.${row.original.status}`, {
              defaultValue: row.original.status,
            })}
          />
        </Tooltip>
      ),
    },
  ];
}

export function medicalColumns(
  t: TFunction,
  showDate: (date: string) => string,
): AdvancedColumn<MedicalCertificate>[] {
  const today = new Date().toISOString().slice(0, 10);
  const options = fitnessOptions(t);
  return [
    {
      header: t('seaRecords.columns.issuer'),
      cell: ({ row }) => (
        <>
          <Text fw={600} size="sm">
            {row.original.issuerName}
          </Text>
          {row.original.certificateNumber && (
            <Text size="xs" c="dimmed">
              {t('seaRecords.columns.certNumber', { number: row.original.certificateNumber })}
            </Text>
          )}
        </>
      ),
    },
    {
      header: t('seaRecords.columns.issued'),
      accessorKey: 'issueDate',
      cell: ({ row }) => showDate(row.original.issueDate),
    },
    {
      header: t('seaRecords.columns.expires'),
      cell: ({ row }) => (
        <Group gap={6} wrap="nowrap">
          {showDate(row.original.expiryDate)}
          {row.original.expiryDate < today && (
            <Badge color="red">{t('seaRecords.columns.expired')}</Badge>
          )}
        </Group>
      ),
    },
    {
      header: t('seaRecords.columns.fitness'),
      cell: ({ row }) =>
        options.find((o) => o.value === row.original.fitnessStatus)?.label ??
        row.original.fitnessStatus,
    },
    {
      header: t('common.status'),
      cell: ({ row }) => (
        <Tooltip
          label={row.original.verificationRemark ?? ''}
          disabled={!row.original.verificationRemark}
        >
          <StatusBadge
            tone={RECORD_STATUS_TONES[row.original.status]}
            label={t(`seaRecords.columns.recordStatus.${row.original.status}`, {
              defaultValue: row.original.status,
            })}
          />
        </Tooltip>
      ),
    },
  ];
}
