import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Button,
  CircularProgress,
  Alert,
  Modal,
  Paper,
  Card,
  CardContent,
} from '@mui/material';
import { QrCodeScanner, Close, CheckCircle, Error } from '@mui/icons-material';
import { Html5Qrcode } from 'html5-qrcode';
import { apiService } from '../services/api';

interface QRResult {
  type: string;
  value: any;
  message: string;
  quizData?: any;
}

export const QRScannerPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [scanning, setScanning] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<QRResult | null>(null);
  const [showResult, setShowResult] = useState(false);
  const scannerRef = useRef<Html5Qrcode | null>(null);

  useEffect(() => {
    return () => {
      if (scannerRef.current) {
        try {
          scannerRef.current.clear();
        } catch (err) {
          console.error('Error clearing scanner:', err);
        }
      }
    };
  }, []);

  const startScanning = async () => {
    if (scannerRef.current) {
      try {
        await scannerRef.current.clear();
      } catch (err) {
        console.error('Error clearing scanner:', err);
      }
    }

    setScanning(true);
    setError(null);

    try {
      const scanner = new Html5Qrcode('qr-reader');
      scannerRef.current = scanner;

      const config = {
        fps: 10,
        qrbox: { width: 250, height: 250 },
      };

      await scanner.start(
        { facingMode: 'environment' },
        config,
        async (decodedText: string) => {
          await handleQRScan(decodedText);
        },
        (_errorMessage: string) => {
          // Handle scan errors silently
        }
      );
    } catch (err) {
      console.error('Error starting scanner:', err);
      setError('Не удалось получить доступ к камере. Пожалуйста, проверьте разрешения.');
      setScanning(false);
    }
  };

  const stopScanning = async () => {
    if (scannerRef.current) {
      try {
        await scannerRef.current.clear();
      } catch (err) {
        console.error('Error stopping scanner:', err);
      }
    }
    setScanning(false);
  };

  const handleQRScan = async (decodedText: string) => {
    await stopScanning();
    setLoading(true);
    setError(null);

    try {
      const response = await apiService.validateQR(decodedText);
      if (response.success && response.data) {
        // Transform backend response types to frontend format
        const transformedData: any = {
          type: response.data.type.toLowerCase(), // Convert "REWARD" -> "reward", "OPEN_QUIZ" -> "open_quiz"
        };

        // Handle different response structures
        if (response.data.type === 'REWARD') {
          transformedData.value = response.data.data.amount;
          transformedData.message = `Вы получили ${response.data.data.amount} ⭐`;
        } else if (response.data.type === 'OPEN_QUIZ') {
          transformedData.value = response.data.data.id;
          transformedData.message = `Викторина: ${response.data.data.title}`;
          transformedData.quizData = response.data.data; // Store full quiz data
        } else if (response.data.type === 'SHOP_ACTION') {
          transformedData.value = response.data.data.action;
          transformedData.message = `Магазин: ${response.data.data.action}`;
        }

        setResult(transformedData);
        setShowResult(true);
      } else {
        setError(response.message || 'Недействительный QR-код');
      }
    } catch (err) {
      console.error('Error validating QR:', err);
      setError('Произошла ошибка при проверке QR-кода');
    } finally {
      setLoading(false);
    }
  };

  const handleResultClose = () => {
    setShowResult(false);
    setResult(null);
    navigate('/home');
  };

  const handleGoToQuiz = (quizId: number) => {
    setShowResult(false);
    setResult(null);
    navigate(`/quiz/${quizId}`);
  };

  return (
    <Box>
      {/* Header */}
      <Box sx={{ textAlign: 'center', mb: 4 }}>
        <Typography
          variant="h4"
          sx={{
            color: '#FFD700',
            fontWeight: 'bold',
            mb: 2,
          }}
        >
          📷 QR-сканер
        </Typography>
        <Typography
          variant="body1"
          sx={{ color: '#888' }}
        >
          Наведите камеру на QR-код для сканирования
        </Typography>
      </Box>

      {/* Scanner Container */}
      <Box sx={{ position: 'relative', mb: 4 }}>
        <div id="qr-reader" style={{ width: '100%', height: '300px' }} />

        {scanning && (
          <Box
            sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              pointerEvents: 'none',
            }}
          >
            <Box
              sx={{
                width: 250,
                height: 250,
                border: '2px solid #FFD700',
                borderRadius: 2,
                position: 'relative',
              }}
            >
              <Box
                sx={{
                  position: 'absolute',
                  top: -2,
                  left: -2,
                  width: 20,
                  height: 20,
                  borderTop: '3px solid #FFD700',
                  borderLeft: '3px solid #FFD700',
                }}
              />
              <Box
                sx={{
                  position: 'absolute',
                  top: -2,
                  right: -2,
                  width: 20,
                  height: 20,
                  borderTop: '3px solid #FFD700',
                  borderRight: '3px solid #FFD700',
                }}
              />
              <Box
                sx={{
                  position: 'absolute',
                  bottom: -2,
                  left: -2,
                  width: 20,
                  height: 20,
                  borderBottom: '3px solid #FFD700',
                  borderLeft: '3px solid #FFD700',
                }}
              />
              <Box
                sx={{
                  position: 'absolute',
                  bottom: -2,
                  right: -2,
                  width: 20,
                  height: 20,
                  borderBottom: '3px solid #FFD700',
                  borderRight: '3px solid #FFD700',
                }}
              />
            </Box>
          </Box>
        )}
      </Box>

      {/* Controls */}
      <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
        {!scanning ? (
          <Button
            variant="contained"
            onClick={startScanning}
            startIcon={<QrCodeScanner />}
            disabled={loading}
            sx={{
              backgroundColor: '#FFD700',
              color: '#000000',
              fontWeight: 'bold',
              '&:hover': {
                backgroundColor: '#FFC700',
              },
            }}
          >
            {loading ? <CircularProgress size={20} /> : 'Начать сканирование'}
          </Button>
        ) : (
          <Button
            variant="outlined"
            onClick={stopScanning}
            startIcon={<Close />}
            sx={{
              borderColor: '#f44336',
              color: '#f44336',
              '&:hover': {
                borderColor: '#f44336',
                backgroundColor: 'rgba(244, 67, 54, 0.1)',
              },
            }}
          >
            Остановить
          </Button>
        )}
      </Box>

      {/* Error Display */}
      {error && (
        <Alert
          severity="error"
          sx={{
            mt: 4,
            backgroundColor: 'rgba(244, 67, 54, 0.1)',
            color: '#ffffff',
            border: '1px solid #f44336',
          }}
        >
          {error}
        </Alert>
      )}

      {/* Instructions */}
      <Card
        sx={{
          backgroundColor: '#1a1a1a',
          border: '1px solid #333',
          borderRadius: 2,
          mt: 4,
        }}
      >
        <CardContent sx={{ p: 3 }}>
          <Typography
            variant="h6"
            sx={{
              color: '#ffffff',
              fontWeight: 'bold',
              mb: 2,
            }}
          >
            Как использовать:
          </Typography>
          <Typography
            variant="body2"
            sx={{ color: '#888', mb: 1 }}
          >
            1. Нажмите "Начать сканирование"
          </Typography>
          <Typography
            variant="body2"
            sx={{ color: '#888', mb: 1 }}
          >
            2. Разрешите доступ к камере
          </Typography>
          <Typography
            variant="body2"
            sx={{ color: '#888', mb: 1 }}
          >
            3. Наведите камеру на QR-код
          </Typography>
          <Typography
            variant="body2"
            sx={{ color: '#888' }}
          >
            4. Дождитесь результата сканирования
          </Typography>
        </CardContent>
      </Card>

      {/* Result Modal */}
      <Modal
        open={showResult}
        onClose={handleResultClose}
        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',
          }}
        >
          {result?.type === 'reward' && (
            <>
              <CheckCircle sx={{ fontSize: 64, color: '#4CAF50', mb: 2 }} />
              <Typography
                variant="h6"
                sx={{
                  color: '#4CAF50',
                  fontWeight: 'bold',
                  mb: 2,
                }}
              >
                QR-код успешно отсканирован!
              </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={handleResultClose}
                sx={{
                  backgroundColor: '#4CAF50',
                  color: '#ffffff',
                }}
              >
                Отлично!
              </Button>
            </>
          )}

          {result?.type === 'open_quiz' && (
            <>
              <CheckCircle 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={handleResultClose}
                  sx={{
                    borderColor: '#333',
                    color: '#ffffff',
                  }}
                >
                  Позже
                </Button>
                <Button
                  fullWidth
                  variant="contained"
                  onClick={() => handleGoToQuiz(result.value)}
                  sx={{
                    backgroundColor: '#FFD700',
                    color: '#000000',
                  }}
                >
                  Начать
                </Button>
              </Box>
            </>
          )}

          {result?.type === '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 }}
              >
                {result.message}
              </Typography>
              <Button
                fullWidth
                variant="contained"
                onClick={handleResultClose}
                sx={{
                  backgroundColor: '#f44336',
                  color: '#ffffff',
                }}
              >
                Закрыть
              </Button>
            </>
          )}
        </Paper>
      </Modal>
    </Box>
  );
};