import { Badge, Group, Paper, SimpleGrid, Text, Title } from '@mantine/core';
import { IconClipboardCheck } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { useGetExamStateForApplicationQuery, type ExamState } from '@ema-platform/api';

/**
 * What the candidate's examination actually shows, on the officer's screen.
 *
 * The detail page used to read the application status alone, so a candidate
 * who had registered, been marked present, sat the paper and had a PASSED mark
 * published still appeared to be awaiting an exam — and the officer was still
 * offered "Schedule exam" and "Record exam result" for work already done. The
 * state here is derived server-side (ExamStateService) from the registration,
 * the attempt and the published mark, so this panel and the applicant's portal
 * cannot disagree.
 */
const STATE_COLOR: Record<ExamState, string> = {
  NOT_REGISTERED: 'gray',
  REGISTERED: 'cyan',
  ATTENDANCE_CONFIRMED: 'indigo',
  NOT_SITTING: 'orange',
  IN_PROGRESS: 'blue',
  UNDER_EVALUATION: 'yellow',
  PASSED: 'teal',
  FAILED: 'red',
};

function Row({ label, value }: { label: string; value?: string | null }) {
  return (
    <div>
      <Text fz="xs" c="dimmed">
        {label}
      </Text>
      <Text fz="sm">{value || '—'}</Text>
    </div>
  );
}

export function ExamStatePanel({ applicationId }: { applicationId: string }) {
  const { t, i18n } = useTranslation();
  const locale = i18n.language as 'en' | 'am';
  // Polled: attendance is recorded by an invigilator, and a paper is marked
  // and published, while the officer has this page open.
  const { data, isLoading } = useGetExamStateForApplicationQuery(applicationId, {
    pollingInterval: 30_000,
    refetchOnFocus: true,
  });

  if (isLoading || !data) return null;

  const settled = data.outcome !== null;

  return (
    <Paper withBorder radius="lg" p="lg">
      <Group justify="space-between" mb="md">
        <Group gap="xs">
          <IconClipboardCheck size={17} />
          <Title order={5}>{t('review.exam.title', 'Examination')}</Title>
        </Group>
        <Badge color={STATE_COLOR[data.state]} variant="light">
          {t(`review.exam.state.${data.state}`, data.state)}
        </Badge>
      </Group>

      <SimpleGrid cols={{ base: 1, sm: 3 }} spacing="md">
        <Row
          label={t('review.exam.session', 'Session')}
          value={data.examTitle?.[locale] ?? data.examTitle?.en}
        />
        <Row label={t('review.exam.date', 'Exam date')} value={data.examDate} />
        <Row
          label={t('review.exam.admission', 'Admission number')}
          value={data.admissionNumber}
        />
        {settled && (
          <>
            <Row
              label={t('review.exam.score', 'Score')}
              value={data.score === null ? null : String(data.score)}
            />
            <Row
              label={t('review.exam.outcome', 'Outcome')}
              value={t(`review.exam.state.${data.outcome}`, data.outcome ?? '')}
            />
            {/* Says where the mark came from, so nobody re-enters one the
                engine already produced. */}
            <Row
              label={t('review.exam.source', 'Result source')}
              value={
                data.autoGraded
                  ? t('review.exam.sourceEngine', 'Exam engine')
                  : t('review.exam.sourceExaminer', 'Examiner')
              }
            />
          </>
        )}
      </SimpleGrid>
    </Paper>
  );
}
