import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  CircularProgress,
  MenuItem,
  Stack,
  TextField,
  Typography,
} from '@mui/material';
import AssessmentIcon from '@mui/icons-material/Assessment';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import TableChartIcon from '@mui/icons-material/TableChart';

import { examRepository } from '../../services/exam/examRepository';
import type { BatchResultsResponse, ExamTemplate, MarkingBatch } from '../../types/exam.types';

interface ResultsWidgetProps {
  classId: string;
  className?: string;
}

function averageFromResults(results: BatchResultsResponse | null) {
  const totals = (results?.results ?? [])
    .map((row) => row.total)
    .filter((value): value is number => typeof value === 'number');
  if (!totals.length) return null;
  return totals.reduce((sum, value) => sum + value, 0) / totals.length;
}

const ResultsWidget: React.FC<ResultsWidgetProps> = ({ classId, className }) => {
  const navigate = useNavigate();
  const [templates, setTemplates] = useState<ExamTemplate[]>([]);
  const [batches, setBatches] = useState<MarkingBatch[]>([]);
  const [latestResults, setLatestResults] = useState<BatchResultsResponse | null>(null);
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [nextTemplates, nextBatches] = await Promise.all([
        examRepository.listTemplates(),
        examRepository.listBatches(),
      ]);
      const classBatches = nextBatches
        .filter((batch) => batch.class_id === classId)
        .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
      setTemplates(nextTemplates);
      setSelectedTemplateId((current) => current || nextTemplates[0]?.id || '');
      setBatches(classBatches);
      setLatestResults(classBatches[0] ? await examRepository.getBatchResults(classBatches[0].id) : null);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setLoading(false);
    }
  }, [classId]);

  useEffect(() => {
    void load();
  }, [load]);

  const latestBatch = batches[0] ?? null;
  const average = useMemo(() => averageFromResults(latestResults), [latestResults]);
  const absent = latestResults?.results.filter((row) => row.status === 'absent' && row.total === null).length ?? 0;

  const createBatch = async () => {
    if (!selectedTemplateId) return;
    setCreating(true);
    setError(null);
    try {
      const template = templates.find((item) => item.id === selectedTemplateId);
      const created = await examRepository.createBatch({
        template_id: selectedTemplateId,
        class_id: classId,
        title: `${className || 'Class'} · ${template?.title || 'Exam'}`,
      });
      navigate(`/exam-marker/${created.id}/mark`);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setCreating(false);
    }
  };

  return (
    <Card variant="outlined" sx={{ mb: 2 }}>
      <CardContent>
        <Stack spacing={2}>
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 1, flexWrap: 'wrap' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <AssessmentIcon color="primary" />
              <Box>
                <Typography variant="h6">Assessment results</Typography>
                <Typography variant="caption" color="text.secondary">Last exam summary for this class</Typography>
              </Box>
            </Box>
            {loading && <CircularProgress size={22} />}
          </Box>

          {error && <Alert severity="warning" onClose={() => setError(null)}>{error}</Alert>}

          {latestBatch ? (
            <Stack spacing={1.5}>
              <Box>
                <Typography variant="body2" fontWeight={700}>{latestBatch.title || 'Exam batch'}</Typography>
                <Typography variant="caption" color="text.secondary">
                  {new Date(latestBatch.created_at).toLocaleDateString('en-GB')}
                </Typography>
              </Box>
              <Stack direction="row" spacing={1} flexWrap="wrap" useFlexGap>
                <Chip size="small" color="primary" label={`Average ${average === null ? '—' : average.toFixed(1)}`} />
                <Chip size="small" variant="outlined" label={`${latestResults?.results.length ?? 0} students`} />
                <Chip size="small" color="warning" variant="outlined" label={`${absent} absent`} />
              </Stack>
              <Stack direction="row" spacing={1}>
                <Button size="small" variant="contained" startIcon={<TableChartIcon />} onClick={() => navigate(`/exam-marker/${latestBatch.id}/results`)}>
                  View results
                </Button>
                <Button size="small" variant="outlined" onClick={() => navigate(`/exam-marker/${latestBatch.id}/mark`)}>
                  Continue marking
                </Button>
              </Stack>
            </Stack>
          ) : !loading ? (
            <Typography variant="body2" color="text.secondary">
              No exam batches have been created for this class yet.
            </Typography>
          ) : null}

          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} alignItems={{ xs: 'stretch', sm: 'center' }}>
            <TextField
              select
              size="small"
              label="Template"
              value={selectedTemplateId}
              onChange={(e) => setSelectedTemplateId(e.target.value)}
              disabled={!templates.length || creating}
              sx={{ minWidth: 260 }}
            >
              {templates.map((template) => (
                <MenuItem key={template.id} value={template.id}>{template.title}</MenuItem>
              ))}
            </TextField>
            <Button
              variant="outlined"
              startIcon={<PlayArrowIcon />}
              onClick={createBatch}
              disabled={!selectedTemplateId || creating}
            >
              {creating ? 'Creating…' : 'Create marking batch'}
            </Button>
          </Stack>
        </Stack>
      </CardContent>
    </Card>
  );
};

export default ResultsWidget;
