import React, { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Button,
  CircularProgress,
} from '@mui/material';
import { EmojiEvents, Star, Home } from '@mui/icons-material';

interface ResultData {
  score: number;
  total_questions: number;
  stars_earned: number;
  correct_answers: number;
}

interface LocationState {
  result: ResultData;
  quizTitle: string;
}

export const QuizResultPage: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();

  const state = location.state as LocationState;

  useEffect(() => {
    if (!state) {
      navigate('/home');
      return;
    }
  }, [state, navigate]);

  const handleGoHome = () => {
    navigate('/home');
  };

  const handleGoToShop = () => {
    navigate('/shop');
  };

  if (!state) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <CircularProgress sx={{ color: '#FFD700' }} />
      </Box>
    );
  }

  const { result, quizTitle } = state;
  const percentage = result.total_questions > 0
    ? Math.round((result.correct_answers / result.total_questions) * 100)
    : 0;

  return (
    <Box>
      {/* Result Header */}
      <Box sx={{ textAlign: 'center', mb: 4 }}>
        <Typography
          variant="h4"
          sx={{
            color: '#FFD700',
            fontWeight: 'bold',
            mb: 2,
          }}
        >
          🎉 Викторина завершена!
        </Typography>
        <Typography
          variant="h6"
          sx={{
            color: '#ffffff',
            mb: 1,
          }}
        >
          {quizTitle}
        </Typography>
      </Box>

      {/* Result Card */}
      <Card
        sx={{
          backgroundColor: 'linear-gradient(135deg, rgba(255, 215, 0, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%)',
          border: '2px solid #FFD700',
          borderRadius: 2,
          mb: 4,
          position: 'relative',
          overflow: 'hidden',
        }}
      >
        <CardContent sx={{ p: 4 }}>
          {/* Score Circle */}
          <Box
            sx={{
              width: 120,
              height: 120,
              borderRadius: '50%',
              backgroundColor: '#FFD700',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              margin: '0 auto 3',
              border: '4px solid #ffffff',
              boxShadow: '0 0 20px rgba(255, 215, 0, 0.5)',
            }}
          >
            <Typography
              variant="h3"
              sx={{
                color: '#000000',
                fontWeight: 'bold',
              }}
            >
              {percentage}%
            </Typography>
          </Box>

          {/* Score Details */}
          <Box sx={{ textAlign: 'center', mb: 3 }}>
            <Typography
              variant="h6"
              sx={{
                color: '#ffffff',
                mb: 1,
              }}
            >
              {result.correct_answers} из {result.total_questions} правильных ответов
            </Typography>
            <Typography
              variant="body1"
              sx={{ color: '#888' }}
            >
              Набрано очков: {result.score}
            </Typography>
          </Box>

          {/* Stars Earned */}
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 1,
              backgroundColor: 'rgba(255, 215, 0, 0.2)',
              p: 2,
              borderRadius: 1,
              border: '1px solid #FFD700',
            }}
          >
            <Star sx={{ color: '#FFD700', fontSize: 24 }} />
            <Typography
              variant="h5"
              sx={{
                color: '#FFD700',
                fontWeight: 'bold',
              }}
            >
              +{result.stars_earned} ⭐ начислено!
            </Typography>
          </Box>
        </CardContent>
      </Card>

      {/* Performance Message */}
      <Card
        sx={{
          backgroundColor: '#1a1a1a',
          border: '1px solid #333',
          borderRadius: 2,
          mb: 4,
        }}
      >
        <CardContent sx={{ p: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
            <EmojiEvents
              sx={{
                color: percentage >= 80 ? '#FFD700' : percentage >= 60 ? '#4CAF50' : '#FF9800',
                fontSize: 32,
              }}
            />
            <Typography
              variant="h6"
              sx={{
                color: '#ffffff',
                fontWeight: 'bold',
              }}
            >
              {percentage >= 80
                ? 'Отличный результат! 🏆'
                : percentage >= 60
                ? 'Хорошая работа! 👍'
                : 'Продолжайте тренироваться! 💪'}
            </Typography>
          </Box>
          <Typography
            variant="body1"
            sx={{ color: '#888' }}
          >
            {percentage >= 80
              ? 'Вы настоящий знаток! Продолжайте в том же духе.'
              : percentage >= 60
              ? 'Неплохой результат! С каждым разом будет лучше.'
              : 'Практика делает мастера! Попробуйте еще раз.'}
          </Typography>
        </CardContent>
      </Card>

      {/* Action Buttons */}
      <Box sx={{ display: 'flex', gap: 2, flexDirection: 'column' }}>
        <Button
          fullWidth
          variant="contained"
          onClick={handleGoToShop}
          startIcon={<Star />}
          sx={{
            backgroundColor: '#FFD700',
            color: '#000000',
            fontWeight: 'bold',
            '&:hover': {
              backgroundColor: '#FFC700',
            },
          }}
        >
          В магазин за призами
        </Button>
        <Button
          fullWidth
          variant="outlined"
          onClick={handleGoHome}
          startIcon={<Home />}
          sx={{
            borderColor: '#333',
            color: '#ffffff',
            '&:hover': {
              borderColor: '#FFD700',
              color: '#FFD700',
            },
          }}
        >
          К викторинам
        </Button>
      </Box>

      </Box>
  );
};