import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  CircularProgress,
  Alert,
} from '@mui/material';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { apiService } from '../services/api';
import { CardQuiz } from '../components/ui/CardQuiz';
import { HeaderProfile } from '../components/ui/HeaderProfile';
import { QRScannerButton } from '../components/ui/QRScannerButton';
import { GridItem } from '../components/GridItem';
import type { Quiz } from '../types';

interface QuizStatus {
  can_repeat: boolean;
  next_available_at?: string;
}

export const HomePage: React.FC = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [quizzes, setQuizzes] = useState<Quiz[]>([]);
  const [quizStatuses, setQuizStatuses] = useState<{ [key: number]: QuizStatus }>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const checkQuizStatus = async (quizId: number) => {
    try {
      const response = await apiService.canRepeatQuiz(quizId);
      if (response.success && response.data) {
        setQuizStatuses(prev => ({
          ...prev,
          [quizId]: response.data
        }));
      }
    } catch (err) {
      console.error('Error checking quiz status:', err);
    }
  };

  useEffect(() => {
    const fetchQuizzes = async () => {
      // Debug: Check Telegram Web App status and initData
      const telegramDebug = {
        windowExists: !!window,
        telegramExists: !!window.Telegram,
        webAppExists: !!window.Telegram?.WebApp,
        initData: window.Telegram?.WebApp?.initData,
        initDataUnsafe: window.Telegram?.WebApp?.initDataUnsafe,
        storedInitData: localStorage.getItem('telegram_init_data'),
        windowLocation: window.location.href,
        userAgent: navigator.userAgent,
        referrer: document.referrer
      };

      console.log('Telegram Debug:', telegramDebug);

      // Show comprehensive debug info
      // alert(`Telegram Debug Info:\n${JSON.stringify(telegramDebug, null, 2)}`);

      // Check if we have initData and store it if not already stored
      if (window.Telegram?.WebApp?.initData && !localStorage.getItem('telegram_init_data')) {
        localStorage.setItem('telegram_init_data', window.Telegram.WebApp.initData);
        console.log('Stored Telegram initData');
      }
      try {
        const response = await apiService.getAllQuizzes();
        if (response.success && response.data) {
          setQuizzes(response.data);

          // Check status for each quiz that allows repetition
          response.data.forEach(quiz => {
            if (quiz.can_repeat) {
              checkQuizStatus(quiz.id);
            }
          });
        } else {
          setError('Не удалось загрузить викторины');
        }
      } catch (err: any) {
        console.error('Error fetching quizzes:', err);

        // Show detailed error information for debugging
        const errorDetails = {
          message: err.message,
          status: err.response?.status,
          statusText: err.response?.statusText,
          data: err.response?.data,
          headers: err.config?.headers,
          url: err.config?.url
        };

        console.error('Error Details:', errorDetails);

        if (err.response?.status === 401) {
          setError(`Ошибка авторизации: ${err.response?.data?.message || 'Unknown error'}`);
        } else {
          setError(`Ошибка (${err.response?.status}): ${err.message}`);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchQuizzes();
  }, []);

  const handleStartQuiz = (quizId: number) => {
    navigate(`/quiz/${quizId}`);
  };

  const formatCooldownTime = (nextAvailableAt: string) => {
    const next = new Date(nextAvailableAt);
    const now = new Date();
    const diff = next.getTime() - now.getTime();

    if (diff <= 0) return 'Доступно сейчас';

    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

    if (hours > 0) {
      return `Через ${hours}ч ${minutes}м`;
    }
    return `Через ${minutes}м`;
  };

  const getQuizStatus = (quiz: Quiz) => {
    const status = quizStatuses[quiz.id];

    if (!quiz.can_repeat) {
      return {
        canStart: true,
        isCompleted: false,
        cooldownTime: undefined,
      };
    }

    if (status && !status.can_repeat && status.next_available_at) {
      return {
        canStart: false,
        isCompleted: true,
        cooldownTime: formatCooldownTime(status.next_available_at),
      };
    }

    return {
      canStart: true,
      isCompleted: false,
      cooldownTime: undefined,
    };
  };

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

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

  return (
    <Box>
      {/* Profile Header */}
      {user && (
        <HeaderProfile
          firstName={user.first_name}
          lastName={user.last_name}
          avatar={user.photo_url}
          starsBalance={user.stars_balance || 0}
        />
      )}

      {/* Quizzes Grid */}
      <Box sx={{
        display: 'grid',
        gridTemplateColumns: {
          xs: '1fr',
          sm: 'repeat(2, 1fr)',
          md: 'repeat(3, 1fr)'
        },
        gap: 3,
      }}>
        {quizzes.map((quiz) => {
          const quizStatus = getQuizStatus(quiz);

          return (
            <GridItem xs={12} sm={6} md={4} key={quiz.id}>
              <CardQuiz
                quiz={quiz}
                onStart={handleStartQuiz}
                isCompleted={quizStatus.isCompleted}
                cooldownTime={quizStatus.cooldownTime}
                canStart={quizStatus.canStart}
              />
            </GridItem>
          );
        })}
      </Box>

      {/* Empty State */}
      {quizzes.length === 0 && (
        <Box
          sx={{
            textAlign: 'center',
            mt: 8,
            p: 4,
            background: 'rgba(255, 255, 255, 0.02)',
            borderRadius: 2,
            border: '1px dashed rgba(255, 255, 255, 0.1)',
          }}
        >
          <Typography
            variant="h6"
            sx={{ color: '#888', mb: 2 }}
          >
            Пока нет доступных викторин
          </Typography>
          <Typography
            variant="body2"
            sx={{ color: '#666', mb: 3 }}
          >
            Загляните позже или отсканируйте QR-код для получения звёзд
          </Typography>
        </Box>
      )}

      {/* QR Scanner Button */}
      <QRScannerButton />
    </Box>
  );
};