import { Badge, Button, Text } from '@mantine/core';
import { IconUserCheck } from '@tabler/icons-react';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import { LICENSE_PERMISSIONS, RequirePermission } from '@ema-platform/auth';
import type { AttendanceStatus, ExamRegistration } from '../../types/exam';

const ATTENDANCE_COLOR: Record<AttendanceStatus, string> = {
  REGISTERED: 'gray',
  PRESENT: 'teal',
  LATE: 'yellow',
  ABSENT: 'red',
  WITHDRAWN: 'orange',
  DISQUALIFIED: 'red',
};

export const candidateName = (registration: ExamRegistration) =>
  [
    registration.profile?.firstName,
    registration.profile?.middleName,
    registration.profile?.lastName,
  ]
    .filter(Boolean)
    .join(' ') || registration.profileId.slice(0, 8);

export function examCandidateColumns(
  t: TFunction,
  handlers: { onRecord: (registration: ExamRegistration) => void },
): AdvancedColumn<ExamRegistration>[] {
  return [
    {
      header: t('exam.candidates.admission'),
      cell: ({ row }) => (
        <Text fz="sm" ff="monospace" fw={600}>
          {row.original.admissionNumber}
        </Text>
      ),
    },
    {
      header: t('exam.candidates.name'),
      cell: ({ row }) => <Text fz="sm">{candidateName(row.original)}</Text>,
    },
    {
      header: t('exam.candidates.attempt'),
      cell: ({ row }) => (
        <Badge
          size="sm"
          variant="light"
          color={row.original.kind === 'RETAKE' ? 'orange' : 'blue'}
        >
          {row.original.kind === 'RETAKE'
            ? t('exam.candidates.retake', { n: row.original.attemptNumber })
            : t('exam.candidates.firstSitting')}
        </Badge>
      ),
    },
    {
      header: t('exam.candidates.attendance'),
      cell: ({ row }) => (
        <Badge
          size="sm"
          variant="light"
          color={ATTENDANCE_COLOR[row.original.attendanceStatus] ?? 'gray'}
        >
          {t(`exam.attendance.${row.original.attendanceStatus}`)}
        </Badge>
      ),
    },
    {
      header: t('exam.candidates.remark'),
      cell: ({ row }) => (
        <Text fz="xs" c="dimmed" maw={220} lineClamp={2}>
          {row.original.attendanceRemark ?? '—'}
        </Text>
      ),
    },
    {
      header: '',
      label: t('exam.candidates.record'),
      align: 'right',
      cell: ({ row }) => (
        <RequirePermission
          anyOf={[LICENSE_PERMISSIONS.RECORD_EXAM_ATTENDANCE]}
          hideOnly
        >
          <Button
            size="compact-xs"
            variant="light"
            leftSection={<IconUserCheck size={12} />}
            onClick={() => handlers.onRecord(row.original)}
          >
            {t('exam.candidates.record')}
          </Button>
        </RequirePermission>
      ),
    },
  ];
}
