import { type StatusTone } from '@ema-platform/shared';
import { Badge, Text } 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,
  type SeafarerProfileSummary,
  type SeafarerRecordStatus,
} from '@ema-platform/api';

export function ownerName(profile?: SeafarerProfileSummary): string {
  if (!profile) return '—';
  return (
    [profile.firstName, profile.middleName, profile.lastName]
      .filter(Boolean)
      .join(' ') || '—'
  );
}

const STATUS_TONE: Record<SeafarerRecordStatus, StatusTone> = {
  SUBMITTED: 'warning',
  VERIFIED: 'success',
  REJECTED: 'danger',
};

/** Only meaningful now the queue can show ruled records too. */
function statusColumn<T extends { status: SeafarerRecordStatus }>(
  t: TFunction,
): AdvancedColumn<T> {
  return {
    header: t('recordVerification.columns.status', 'Status'),
    label: t('recordVerification.columns.status', 'Status'),
    accessorKey: 'status',
    cell: ({ row }) => (
      <StatusBadge
        tone={STATUS_TONE[row.original.status]}
        label={t(`recordVerification.status.${row.original.status}`, row.original.status)}
        size="sm"
        variant="light"
      />
    ),
  };
}

export function medicalColumns(
  t: TFunction,
  showDate: (date: string) => string,
): AdvancedColumn<MedicalCertificate>[] {
  return [
    {
      header: t('recordVerification.columns.seafarer', 'Seafarer'),
      label: t('recordVerification.columns.seafarer', 'Seafarer'),
      accessorKey: 'profile.firstName',
      cell: ({ row }) => (
        <div>
          <Text size="sm" fw={500}>
            {ownerName(row.original.profile)}
          </Text>
          {row.original.profile?.seafarerNumber && (
            <Text size="xs" c="dimmed" ff="monospace">
              {row.original.profile.seafarerNumber}
            </Text>
          )}
        </div>
      ),
    },
    {
      header: t('recordVerification.columns.issuer', 'Issuer'),
      label: t('recordVerification.columns.issuer', 'Issuer'),
      accessorKey: 'issuerName',
      cell: ({ row }) => (
        <div>
          <Text size="sm">{row.original.issuerName}</Text>
          {row.original.certificateNumber && (
            <Text size="xs" c="dimmed">
              № {row.original.certificateNumber}
            </Text>
          )}
        </div>
      ),
    },
    {
      header: t('recordVerification.columns.validity', 'Validity'),
      label: t('recordVerification.columns.validity', 'Validity'),
      cell: ({ row }) => (
        <Text size="sm">
          {showDate(row.original.issueDate)} → {showDate(row.original.expiryDate)}
        </Text>
      ),
    },
    {
      header: t('recordVerification.columns.fitness', 'Fitness'),
      label: t('recordVerification.columns.fitness', 'Fitness'),
      accessorKey: 'fitnessStatus',
      cell: ({ row }) => (
        <Badge size="sm" variant="light">
          {t(`recordVerification.fitness.${row.original.fitnessStatus}`, row.original.fitnessStatus)}
        </Badge>
      ),
    },
    statusColumn<MedicalCertificate>(t),
  ];
}

export function seaServiceColumns(
  t: TFunction,
  showDate: (date: string) => string,
): AdvancedColumn<SeaServiceRecord>[] {
  return [
    {
      header: t('recordVerification.columns.seafarer', 'Seafarer'),
      label: t('recordVerification.columns.seafarer', 'Seafarer'),
      accessorKey: 'profile.firstName',
      cell: ({ row }) => (
        <div>
          <Text size="sm" fw={500}>
            {ownerName(row.original.profile)}
          </Text>
          {row.original.profile?.seafarerNumber && (
            <Text size="xs" c="dimmed" ff="monospace">
              {row.original.profile.seafarerNumber}
            </Text>
          )}
        </div>
      ),
    },
    {
      header: t('recordVerification.columns.vessel', 'Vessel'),
      label: t('recordVerification.columns.vessel', 'Vessel'),
      accessorKey: 'vesselName',
      cell: ({ row }) => (
        <div>
          <Text size="sm">{row.original.vesselName}</Text>
          {row.original.imoNumber && (
            <Text size="xs" c="dimmed">
              IMO {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>
          )}
        </div>
      ),
    },
    {
      header: t('recordVerification.columns.rank', 'Rank'),
      label: t('recordVerification.columns.rank', 'Rank'),
      accessorKey: 'rank',
      cell: ({ row }) => <Text size="sm">{row.original.rank}</Text>,
    },
    {
      header: t('recordVerification.columns.period', 'Period'),
      label: t('recordVerification.columns.period', 'Period'),
      cell: ({ row }) => (
        <Text size="sm">
          {showDate(row.original.engagementDate)} → {showDate(row.original.dischargeDate)}
        </Text>
      ),
    },
    {
      header: t('recordVerification.columns.days', 'Days'),
      label: t('recordVerification.columns.days', 'Days'),
      align: 'right',
      cell: ({ row }) => (
        <Text size="sm" fw={600}>
          {seaServiceDays(row.original.engagementDate, row.original.dischargeDate) ?? '—'}
        </Text>
      ),
    },
    statusColumn<SeaServiceRecord>(t),
  ];
}
