import { Badge, Group, NumberInput, Text, TextInput } from '@mantine/core';
import type { TFunction } from 'i18next';
import type { AdvancedColumn } from '@ema-platform/ui';
import type { GradingSheetQuestion, QuestionBrief } from '../../../exam/types/exam';

export function recordResultColumns(
  t: TFunction,
  locale: 'en' | 'am',
  handlers: {
    scores: Record<string, number>;
    questionRemarks: Record<string, string>;
    onScoreChange: (questionId: string, value: number) => void;
    onRemarkChange: (questionId: string, value: string) => void;
    /** The candidate's own answer + auto-score, when available (empty for
     *  an OFFLINE candidate or one who hasn't sat an online attempt). */
    answersByQuestion: Map<string, GradingSheetQuestion>;
  },
): AdvancedColumn<QuestionBrief>[] {
  return [
    {
      header: t('result.recordModal.question'),
      cell: ({ row }) => (
        <Text fz="sm" maw={250} lineClamp={2}>
          {row.original.title[locale]}
        </Text>
      ),
    },
    {
      header: t('result.recordModal.candidateAnswer'),
      cell: ({ row }) => {
        const answer = handlers.answersByQuestion.get(row.original.id);
        if (!answer || (!answer.answerText && !answer.selectedOptionText)) {
          return <Text fz="xs" c="dimmed">{t('result.recordModal.noAnswer')}</Text>;
        }
        return (
          <Text fz="sm" maw={220} lineClamp={3}>
            {answer.selectedOptionText?.[locale] ?? answer.answerText}
          </Text>
        );
      },
    },
    {
      header: t('result.recordModal.maxPoints'),
      cell: ({ row }) => (
        <Text fz="sm" fw={600}>
          {row.original.points}
        </Text>
      ),
    },
    {
      header: t('result.recordModal.score'),
      cell: ({ row }) => {
        const autoGraded = handlers.answersByQuestion.get(row.original.id)?.autoScore != null;
        return (
          <Group gap={4} wrap="nowrap">
            <NumberInput
              value={handlers.scores[row.original.id] ?? 0}
              onChange={(v) => handlers.onScoreChange(row.original.id, Number(v))}
              min={0}
              max={row.original.points}
              size="xs"
              style={{ width: 80 }}
            />
            {autoGraded && (
              <Badge size="xs" variant="light" color="teal">
                {t('result.recordModal.autoGraded')}
              </Badge>
            )}
          </Group>
        );
      },
    },
    {
      header: t('result.recordModal.remark'),
      cell: ({ row }) => (
        <TextInput
          placeholder={t('result.recordModal.remarkOptional')}
          value={handlers.questionRemarks[row.original.id] ?? ''}
          onChange={(e) => handlers.onRemarkChange(row.original.id, e.currentTarget.value)}
          size="xs"
          style={{ minWidth: 160 }}
        />
      ),
    },
  ];
}
