import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { Alert, Button, Center, Group, Loader, Modal, Stack, Text } from '@mantine/core';
import { IconAlertCircle, IconSend } from '@tabler/icons-react';
import { useLocalized } from '@ema-platform/api';
import { useDateDisplayer } from '@ema-platform/shared';
import { useExamAttempt } from '../../hooks/useExamAttempt';
import { ExamInstructions } from '../../components/ExamInstructions';
import { ExamTimer } from '../../components/ExamTimer';
import { ExamQuestionNav } from '../../components/ExamQuestionNav';
import { ExamQuestionDisplay } from '../../components/ExamQuestionDisplay';
import { ExamCompletion } from '../../components/ExamCompletion';

/**
 * The candidate exam-taking screen (Phase 4). Route: `/exams/:examId/take`.
 *
 * All state/API orchestration lives in `useExamAttempt` — this component is
 * the view: pick which of loading/not-started/taking/completed/error to
 * render. Every write it triggers (start, save, submit) is re-checked by the
 * backend regardless of what this screen currently shows; nothing here is
 * the actual security boundary.
 */
export function ExamAttemptPage() {
  const { examId } = useParams<{ examId: string }>();
  const localized = useLocalized();
  const showDate = useDateDisplayer();
  const [confirmOpened, setConfirmOpened] = useState(false);

  const {
    viewState,
    errorMessage,
    registration,
    session,
    currentIndex,
    answers,
    saveStates,
    answeredIds,
    remainingSeconds,
    starting,
    submitting,
    start,
    selectOption,
    changeText,
    goTo,
    retry,
    submit,
  } = useExamAttempt(examId);

  if (viewState === 'loading') {
    return (
      <Center py="xl">
        <Loader />
      </Center>
    );
  }

  if (viewState === 'error') {
    return (
      <Alert icon={<IconAlertCircle size={16} />} color="red" maw={600} mx="auto" mt="xl">
        {errorMessage}
      </Alert>
    );
  }

  if (viewState === 'not-started') {
    if (!registration) return null; // guarded by 'error' above, appeases TS
    return (
      <ExamInstructions
        registration={registration}
        localized={localized}
        showDate={showDate}
        starting={starting}
        onStart={start}
      />
    );
  }

  if (viewState === 'completed' && session) {
    return (
      <ExamCompletion status={session.attempt.status} submittedAt={session.attempt.submittedAt} />
    );
  }

  if (!session) return null; // 'taking' always has a session by construction

  const question = session.questions[currentIndex];
  const answer = answers[question.id];

  return (
    <Stack maw={1000} mx="auto" gap="md">
      <Group justify="space-between" wrap="nowrap">
        <Text fw={600}>{localized(registration?.exam?.title) || 'Examination in progress'}</Text>
        <ExamTimer remainingSeconds={remainingSeconds} />
      </Group>

      <Group align="flex-start" gap="md" wrap="wrap-reverse">
        <div style={{ flex: 1, minWidth: 280 }}>
          <ExamQuestionDisplay
            question={question}
            index={currentIndex}
            total={session.questions.length}
            localized={localized}
            selectedOptionId={answer?.selectedOptionId}
            answerText={answer?.answerText}
            saveState={saveStates[question.id] ?? 'idle'}
            disabled={remainingSeconds <= 0}
            onSelectOption={(optionId) => selectOption(question.id, optionId)}
            onChangeText={(text) => changeText(question.id, text)}
            onRetry={() => retry(question.id)}
          />

          <Group justify="space-between" mt="md">
            <Button
              variant="default"
              disabled={currentIndex === 0}
              onClick={() => goTo(currentIndex - 1)}
            >
              Previous
            </Button>
            {currentIndex < session.questions.length - 1 ? (
              <Button onClick={() => goTo(currentIndex + 1)}>Next</Button>
            ) : (
              <Button
                color="teal"
                leftSection={<IconSend size={15} />}
                onClick={() => setConfirmOpened(true)}
              >
                Submit exam
              </Button>
            )}
          </Group>
        </div>

        <div style={{ width: 220, flexShrink: 0 }}>
          <ExamQuestionNav
            questions={session.questions}
            currentIndex={currentIndex}
            answeredIds={answeredIds}
            disabled={remainingSeconds <= 0}
            onJump={goTo}
          />
          <Button
            fullWidth
            mt="sm"
            variant="light"
            color="teal"
            leftSection={<IconSend size={15} />}
            onClick={() => setConfirmOpened(true)}
          >
            Submit exam
          </Button>
        </div>
      </Group>

      <Modal
        opened={confirmOpened}
        onClose={() => setConfirmOpened(false)}
        title="Submit this exam?"
        radius="lg"
      >
        <Stack>
          <Text size="sm">
            {answeredIds.size} of {session.questions.length} questions answered. Once submitted,
            answers cannot be changed.
          </Text>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setConfirmOpened(false)}>
              Keep working
            </Button>
            <Button
              color="teal"
              loading={submitting}
              onClick={async () => {
                await submit();
                setConfirmOpened(false);
              }}
            >
              Submit
            </Button>
          </Group>
        </Stack>
      </Modal>
    </Stack>
  );
}

export default ExamAttemptPage;
