import { Badge, Button, Group, Paper, Radio, Stack, Text, Textarea } from '@mantine/core';
import { IconAlertCircle, IconCheck, IconRefresh } from '@tabler/icons-react';
import type { Bilingual } from '@ema-platform/api';
import type { CandidateQuestion, SaveState } from '../types/exam-attempt';

function SaveIndicator({ state, onRetry }: { state: SaveState; onRetry: () => void }) {
  if (state === 'saving') {
    return <Text fz="xs" c="dimmed">Saving…</Text>;
  }
  if (state === 'saved') {
    return (
      <Group gap={4}>
        <IconCheck size={13} color="var(--mantine-color-teal-6)" />
        <Text fz="xs" c="teal">Saved</Text>
      </Group>
    );
  }
  if (state === 'error') {
    return (
      <Group gap={6}>
        <IconAlertCircle size={13} color="var(--mantine-color-red-6)" />
        <Text fz="xs" c="red">Not saved</Text>
        <Button
          size="compact-xs"
          variant="light"
          color="red"
          leftSection={<IconRefresh size={12} />}
          onClick={onRetry}
        >
          Retry
        </Button>
      </Group>
    );
  }
  return null;
}

/**
 * Renders one question — never the answer key, because the API response
 * this reads from (`CandidateQuestion`/`CandidateOption`) has no such field
 * to render even by mistake.
 */
export function ExamQuestionDisplay({
  question,
  index,
  total,
  localized,
  selectedOptionId,
  answerText,
  saveState,
  disabled,
  onSelectOption,
  onChangeText,
  onRetry,
}: {
  question: CandidateQuestion;
  index: number;
  total: number;
  localized: (value: Bilingual | undefined) => string;
  selectedOptionId: string | null | undefined;
  answerText: string | null | undefined;
  saveState: SaveState;
  disabled: boolean;
  onSelectOption: (optionId: string) => void;
  onChangeText: (text: string) => void;
  onRetry: () => void;
}) {
  return (
    <Paper withBorder radius="md" p="lg">
      <Group justify="space-between" mb="sm">
        <Badge variant="light" color="gray">
          Question {index + 1} of {total} · {question.points} pts
        </Badge>
        <SaveIndicator state={saveState} onRetry={onRetry} />
      </Group>

      <Text fz="md" fw={500} mb="lg">
        {localized(question.title)}
      </Text>

      {question.form === 'CHOICE' ? (
        <Radio.Group
          value={selectedOptionId ?? ''}
          onChange={onSelectOption}
        >
          <Stack gap="sm">
            {question.options
              .slice()
              .sort((a, b) => a.order - b.order)
              .map((option) => (
                <Radio.Card
                  key={option.id}
                  value={option.id}
                  disabled={disabled}
                  p="sm"
                  radius="md"
                >
                  <Group wrap="nowrap" gap="sm">
                    <Radio.Indicator disabled={disabled} />
                    <Text fz="sm">{localized(option.text)}</Text>
                  </Group>
                </Radio.Card>
              ))}
          </Stack>
        </Radio.Group>
      ) : (
        <Textarea
          placeholder="Write your answer"
          minRows={8}
          autosize
          disabled={disabled}
          value={answerText ?? ''}
          onChange={(event) => onChangeText(event.currentTarget.value)}
        />
      )}
    </Paper>
  );
}
