import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Button,
  Modal,
  Paper,
  CircularProgress,
} from '@mui/material';
import {
  Quiz as QuizIcon,
  ShoppingBag,
  CheckCircle,
  Error
} from '@mui/icons-material';
import { useAuth } from '../context/AuthContext';
import { apiService } from '../services/api';

interface DeepLinkHandlerProps {
  onActionComplete?: () => void;
}

export const DeepLinkHandler: React.FC<DeepLinkHandlerProps> = ({ onActionComplete }) => {
  const { deepLinkAction, clearDeepLinkAction, updateUser } = useAuth();
  const navigate = useNavigate();
  const [processing, setProcessing] = useState(false);
  const [result, setResult] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (deepLinkAction) {
      handleDeepLinkAction();
    }
  }, [deepLinkAction]);

  const handleDeepLinkAction = async () => {
    if (!deepLinkAction) return;

    setProcessing(true);
    setError(null);

    try {
      switch (deepLinkAction.type) {
        case 'reward':
          await handleRewardAction(deepLinkAction.value);
          break;
        case 'quiz':
          await handleQuizAction(deepLinkAction.value);
          break;
        case 'shop':
          await handleShopAction();
          break;
        default:
          setError('Неизвестный тип действия');
      }
    } catch (err) {
      console.error('Deep link action error:', err);
      setError('Произошла ошибка при обработке действия');
    } finally {
      setProcessing(false);
    }
  };

  const handleRewardAction = async (value: string) => {
    const stars = parseInt(value);
    if (isNaN(stars) || stars <= 0) {
      setError('Некорректное количество звезд');
      return;
    }

    try {
      const response = await apiService.validateQR(`reward:${stars}`);
      if (response.success && response.data) {
        setResult({
          type: 'reward',
          value: stars,
          message: response.data.message || `Вы получили ${stars} ⭐!`
        });

        // Update user balance
        const userResponse = await apiService.getCurrentUser();
        if (userResponse.success && userResponse.data) {
          updateUser(userResponse.data);
        }
      } else {
        setError(response.message || 'Не удалось начислить звезды');
      }
    } catch (err) {
      setError('Ошибка при обработке награды');
    }
  };

  const handleQuizAction = async (quizId: string) => {
    const id = parseInt(quizId);
    if (isNaN(id)) {
      setError('Некорректный ID викторины');
      return;
    }

    setResult({
      type: 'quiz',
      value: id,
      message: 'Викторина найдена! Готовы начать?'
    });
  };

  const handleShopAction = async () => {
    setResult({
      type: 'shop',
      value: '',
      message: 'Переход в магазин призов'
    });
  };

  const handleClose = () => {
    clearDeepLinkAction();
    setResult(null);
    setError(null);
    onActionComplete?.();
  };

  const handleGoToQuiz = () => {
    clearDeepLinkAction();
    setResult(null);
    navigate(`/quiz/${result.value}`);
  };

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

  if (!deepLinkAction) {
    return null;
  }

  return (
    <>
      {/* Processing Modal */}
      <Modal
        open={processing}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Paper
          sx={{
            backgroundColor: '#1a1a1a',
            border: '1px solid #333',
            borderRadius: 2,
            p: 4,
            textAlign: 'center',
          }}
        >
          <CircularProgress sx={{ color: '#FFD700', mb: 2 }} />
          <Typography sx={{ color: '#ffffff' }}>
            Обработка действия...
          </Typography>
        </Paper>
      </Modal>

      {/* Result Modal */}
      <Modal
        open={!!result || !!error}
        onClose={handleClose}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Paper
          sx={{
            backgroundColor: '#1a1a1a',
            border: '1px solid #333',
            borderRadius: 2,
            p: 4,
            maxWidth: 400,
            width: '90%',
            textAlign: 'center',
          }}
        >
          {error ? (
            <>
              <Error sx={{ fontSize: 64, color: '#f44336', mb: 2 }} />
              <Typography
                variant="h6"
                sx={{
                  color: '#f44336',
                  fontWeight: 'bold',
                  mb: 2,
                }}
              >
                Ошибка
              </Typography>
              <Typography
                variant="body1"
                sx={{ color: '#ffffff', mb: 3 }}
              >
                {error}
              </Typography>
              <Button
                fullWidth
                variant="contained"
                onClick={handleClose}
                sx={{
                  backgroundColor: '#f44336',
                  color: '#ffffff',
                }}
              >
                Закрыть
              </Button>
            </>
          ) : result?.type === 'reward' && (
            <>
              <CheckCircle sx={{ fontSize: 64, color: '#4CAF50', mb: 2 }} />
              <Typography
                variant="h6"
                sx={{
                  color: '#4CAF50',
                  fontWeight: 'bold',
                  mb: 2,
                }}
              >
                Награда получена!
              </Typography>
              <Typography
                variant="body1"
                sx={{ color: '#ffffff', mb: 1 }}
              >
                Вы получили {result.value} ⭐
              </Typography>
              <Typography
                variant="body2"
                sx={{ color: '#888', mb: 3 }}
              >
                {result.message}
              </Typography>
              <Button
                fullWidth
                variant="contained"
                onClick={handleClose}
                sx={{
                  backgroundColor: '#4CAF50',
                  color: '#ffffff',
                }}
              >
                Отлично!
              </Button>
            </>
          )}

          {result?.type === 'quiz' && (
            <>
              <QuizIcon sx={{ fontSize: 64, color: '#FFD700', mb: 2 }} />
              <Typography
                variant="h6"
                sx={{
                  color: '#FFD700',
                  fontWeight: 'bold',
                  mb: 2,
                }}
              >
                Викторина найдена!
              </Typography>
              <Typography
                variant="body1"
                sx={{ color: '#ffffff', mb: 1 }}
              >
                {result.message}
              </Typography>
              <Typography
                variant="body2"
                sx={{ color: '#888', mb: 3 }}
              >
                Готовы пройти викторину?
              </Typography>
              <Box sx={{ display: 'flex', gap: 2 }}>
                <Button
                  fullWidth
                  variant="outlined"
                  onClick={handleClose}
                  sx={{
                    borderColor: '#333',
                    color: '#ffffff',
                  }}
                >
                  Позже
                </Button>
                <Button
                  fullWidth
                  variant="contained"
                  onClick={handleGoToQuiz}
                  sx={{
                    backgroundColor: '#FFD700',
                    color: '#000000',
                  }}
                >
                  Начать
                </Button>
              </Box>
            </>
          )}

          {result?.type === 'shop' && (
            <>
              <ShoppingBag sx={{ fontSize: 64, color: '#FF9800', mb: 2 }} />
              <Typography
                variant="h6"
                sx={{
                  color: '#FF9800',
                  fontWeight: 'bold',
                  mb: 2,
                }}
              >
                Магазин призов
              </Typography>
              <Typography
                variant="body1"
                sx={{ color: '#ffffff', mb: 3 }}
              >
                {result.message}
              </Typography>
              <Button
                fullWidth
                variant="contained"
                onClick={handleGoToShop}
                sx={{
                  backgroundColor: '#FF9800',
                  color: '#ffffff',
                }}
              >
                В магазин
              </Button>
            </>
          )}
        </Paper>
      </Modal>
    </>
  );
};