import React, { useEffect, useState, useCallback } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../api/axios';
import { formatLocalDateTime, formatLocalTime } from '../utils/dateUtils';
import PopularityBadge from '../components/PopularityBadge';

function Home() {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const [activeSession, setActiveSession] = useState(null);
  const [sessionGames, setSessionGames] = useState([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);

  const loadSessionGames = useCallback(async (sessionId, silent = false) => {
    try {
      const gamesResponse = await api.get(`/sessions/${sessionId}/games`);
      // Reverse chronological order (most recent first)
      setSessionGames(gamesResponse.data.reverse());
    } catch (error) {
      if (!silent) {
        console.error('Failed to load session games', error);
      }
    }
  }, []);

  const loadActiveSession = useCallback(async () => {
    try {
      const response = await api.get('/sessions/active');
      
      // Handle both old format (direct session) and new format (session: null)
      const session = response.data?.session !== undefined ? response.data.session : response.data;
      setActiveSession(session);
      
      if (session?.id) {
        await loadSessionGames(session.id);
      }
    } catch (error) {
      // No active session is okay
      setActiveSession(null);
    } finally {
      setLoading(false);
    }
  }, [loadSessionGames]);

  useEffect(() => {
    loadActiveSession();
  }, [loadActiveSession]);

  // Auto-refresh for active session status and games
  useEffect(() => {
    // Poll for session status changes every 3 seconds
    const interval = setInterval(() => {
      loadActiveSession();
    }, 3000);
    
    return () => clearInterval(interval);
  }, [loadActiveSession]);

  const handleCreateSession = async () => {
    setCreating(true);
    try {
      await api.post('/sessions');
      // Navigate to picker page after creating session
      navigate('/picker');
    } catch (error) {
      console.error('Failed to create session:', error);
      alert('Failed to create session. Please try again.');
      setCreating(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="text-xl text-gray-600 dark:text-gray-400">Loading...</div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">

      {activeSession ? (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-4 sm:p-6 mb-8">
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-4 mb-4">
            <div className="flex-1">
              <h2 className="text-xl sm:text-2xl font-semibold text-green-600 dark:text-green-400 mb-2">
                Live Session Active
              </h2>
              <p className="text-sm sm:text-base text-gray-600 dark:text-gray-400">
                Started: {formatLocalDateTime(activeSession.created_at)}
              </p>
              {activeSession.notes && (
                <p className="text-sm sm:text-base text-gray-600 dark:text-gray-400 mt-2">Notes: {activeSession.notes}</p>
              )}
            </div>
            {isAuthenticated && (
              <Link
                to="/picker"
                className="bg-indigo-600 dark:bg-indigo-700 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 dark:hover:bg-indigo-800 transition text-center sm:text-left whitespace-nowrap"
              >
                Pick a Game
              </Link>
            )}
          </div>

          {sessionGames.length > 0 && (
            <div className="mt-6">
              <h3 className="text-lg sm:text-xl font-semibold mb-4 text-gray-800 dark:text-gray-100">Games Played This Session</h3>
              <div className="space-y-2">
                {sessionGames.map((game, index) => {
                  const displayIndex = sessionGames.length - index;
                  const isPlaying = game.status === 'playing';
                  const isSkipped = game.status === 'skipped';
                  return (
                  <div
                    key={game.id}
                    className={`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 p-3 sm:p-4 rounded-lg transition ${
                      isPlaying
                        ? 'bg-green-50 dark:bg-green-900/20 border-2 border-green-300 dark:border-green-700'
                        : isSkipped
                        ? 'bg-gray-100 dark:bg-gray-700/50'
                        : 'bg-gray-50 dark:bg-gray-700'
                    }`}
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className={`font-semibold text-sm sm:text-base break-words ${
                          isSkipped 
                            ? 'text-gray-500 dark:text-gray-500 line-through' 
                            : 'text-gray-700 dark:text-gray-200'
                        }`}>
                          {displayIndex}. {game.title}
                        </span>
                        {isPlaying && (
                          <span className="inline-flex items-center gap-1 text-xs bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-2 py-1 rounded font-semibold">
                            🎮 Playing
                          </span>
                        )}
                        {isSkipped && (
                          <span className="inline-flex items-center gap-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 px-2 py-1 rounded">
                            ⏭️ Skipped
                          </span>
                        )}
                        {game.room_code && (
                          <span className="inline-flex items-center gap-1 text-xs bg-indigo-600 dark:bg-indigo-700 text-white px-2 py-1 rounded font-mono font-bold">
                            🎮 {game.room_code}
                          </span>
                        )}
                        <PopularityBadge 
                          upvotes={game.upvotes || 0}
                          downvotes={game.downvotes || 0}
                          popularityScore={game.popularity_score || 0}
                          size="sm"
                          showCounts={true}
                          showNet={true}
                          showRatio={true}
                        />
                      </div>
                      <div className="text-xs sm:text-sm text-gray-500 dark:text-gray-400 mt-1">
                        ({game.pack_name})
                        {game.manually_added === 1 && (
                          <span className="ml-2 text-xs bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 px-2 py-1 rounded">
                            Manual
                          </span>
                        )}
                      </div>
                    </div>
                    <span className="text-xs sm:text-sm text-gray-500 dark:text-gray-400 flex-shrink-0">
                      {formatLocalTime(game.played_at)}
                    </span>
                  </div>
                );
                })}
              </div>
            </div>
          )}
        </div>
      ) : (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 mb-8">
          <h2 className="text-2xl font-semibold text-gray-700 dark:text-gray-200 mb-4">
            No Active Session
          </h2>
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            There is currently no game session in progress.
          </p>
          {isAuthenticated ? (
            <button
              onClick={handleCreateSession}
              disabled={creating}
              className="inline-block bg-indigo-600 dark:bg-indigo-700 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 dark:hover:bg-indigo-800 transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {creating ? 'Creating Session...' : 'Start a New Session'}
            </button>
          ) : (
            <p className="text-gray-500 dark:text-gray-400">
              Admin access required to start a new session.
            </p>
          )}
        </div>
      )}

      <div className="grid md:grid-cols-2 gap-6">
        <Link
          to="/history"
          className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 hover:shadow-xl hover:scale-[1.02] transition-all group"
        >
          <h3 className="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-2 flex items-center justify-between">
            <span>Session History</span>
            <svg 
              className="w-5 h-5 text-gray-400 dark:text-gray-500 group-hover:text-indigo-600 dark:group-hover:text-indigo-400 group-hover:translate-x-1 transition-all" 
              fill="none" 
              stroke="currentColor" 
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </h3>
          <p className="text-gray-600 dark:text-gray-300">
            View past gaming sessions and the games that were played
          </p>
        </Link>

        {isAuthenticated && (
          <Link
            to="/manager"
            className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 hover:shadow-xl hover:scale-[1.02] transition-all group"
          >
            <h3 className="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-2 flex items-center justify-between">
              <span>Game Manager</span>
              <svg 
                className="w-5 h-5 text-gray-400 dark:text-gray-500 group-hover:text-indigo-600 dark:group-hover:text-indigo-400 group-hover:translate-x-1 transition-all" 
                fill="none" 
                stroke="currentColor" 
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </h3>
            <p className="text-gray-600 dark:text-gray-300">
              Manage games, packs, and view statistics
            </p>
          </Link>
        )}
      </div>
    </div>
  );
}

export default Home;

