import { type StatusTone } from '@ema-platform/shared';
import { Badge, Button, Text } from '@mantine/core';
import { IconAlertTriangle } from '@tabler/icons-react';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import { StatusBadge } from '@ema-platform/ui';
import { LICENSE_PERMISSIONS, RequirePermission } from '@ema-platform/auth';
import type { ExamIncident, ExamIncidentStatus } from '../../types/exam';

const STATUS_TONE: Record<ExamIncidentStatus, StatusTone> = {
  OPEN: 'danger',
  UNDER_REVIEW: 'warning',
  RESOLVED: 'success',
  DISMISSED: 'neutral',
};

export function examIncidentColumns(
  t: TFunction,
  showDate: (date: string | null | undefined) => string,
  handlers: { onResolve: (incident: ExamIncident) => void },
): AdvancedColumn<ExamIncident>[] {
  return [
    {
      header: t('exam.incidents.type'),
      cell: ({ row }) => (
        <Badge size="sm" variant="light" color="orange">
          {t(`exam.incidentType.${row.original.type}`)}
        </Badge>
      ),
    },
    {
      header: t('exam.incidents.candidate'),
      cell: ({ row }) => (
        <Text fz="xs">
          {row.original.registration?.admissionNumber ?? t('exam.incidents.wholeRoom')}
        </Text>
      ),
    },
    {
      header: t('exam.incidents.description'),
      cell: ({ row }) => (
        <>
          <Text fz="xs" maw={260} lineClamp={2}>
            {row.original.description}
          </Text>
          {row.original.resolution && (
            <Text fz="xs" c="dimmed" maw={260} lineClamp={2}>
              ⤷ {row.original.resolution}
            </Text>
          )}
        </>
      ),
    },
    {
      header: t('exam.incidents.occurred'),
      cell: ({ row }) => <Text fz="xs">{showDate(row.original.occurredAt)}</Text>,
    },
    {
      header: t('exam.incidents.status'),
      cell: ({ row }) => (
        <StatusBadge
          tone={STATUS_TONE[row.original.status] ?? 'neutral'}
          label={t(`exam.incidentStatus.${row.original.status}`)}
          size="sm"
          variant="light"
        />
      ),
    },
    {
      header: '',
      label: t('exam.incidents.resolve'),
      align: 'right',
      cell: ({ row }) =>
        row.original.status === 'OPEN' || row.original.status === 'UNDER_REVIEW' ? (
          <RequirePermission
            anyOf={[LICENSE_PERMISSIONS.MANAGE_EXAM_INCIDENTS]}
            hideOnly
          >
            <Button
              size="compact-xs"
              variant="light"
              leftSection={<IconAlertTriangle size={12} />}
              onClick={() => handlers.onResolve(row.original)}
            >
              {t('exam.incidents.resolve')}
            </Button>
          </RequirePermission>
        ) : null,
    },
  ];
}
