'use client'

import { useState, useEffect } from 'react'
import { Search, Play, Users } from 'lucide-react'

export default function Games() {
  const [games, setGames] = useState([])
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [stats, setStats] = useState({ total_games: 0, total_active: 0 })
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // fetchGames
  useEffect(() => {
    const fetchGames = async () => {
      setLoading(true)
      setPage(1)
      setHasMore(true)
      try {
        const [gamesRes, statsRes] = await Promise.all([
          fetch('/api/proxy?endpoint=game&page=1&limit=12'),
          fetch('/api/proxy?endpoint=stats&page=1&limit=12')
        ])
        
        if (!gamesRes.ok) {
          console.error('Games response status:', gamesRes.status)
        }
        
        const gamesData = await gamesRes.json()
        const statsData = await statsRes.json()
        
        console.log('Games response:', gamesData)
        console.log('Stats response:', statsData)
        
        setGames(gamesData?.games || [])
        setStats({
          total_games: statsData?.total_games || gamesData?.total || 0,
          total_active: statsData?.total_active || 0
        })
        
        const total = gamesData?.total || 0
        setHasMore((gamesData?.games || []).length < total)
      } catch (error) {
        console.error('Failed to fetch games:', error)
        setGames([])
      } finally {
        setLoading(false)
      }
    }

    fetchGames()
  }, [])

  // loadMoreGames
  const loadMoreGames = async () => {
    if (loadingMore || !hasMore) return
    
    setLoadingMore(true)
    try {
      const nextPage = page + 1
      const response = await fetch(`/api/proxy?endpoint=game&page=${nextPage}&limit=12`)
      const data = await response.json()
      
      console.log(`Page ${nextPage} response:`, data)
      
      const newGames = data?.games || []
      setGames(prev => [...prev, ...newGames])
      setPage(nextPage)
      
      const total = data?.total || 0
      setHasMore(games.length + newGames.length < total)
    } catch (error) {
      console.error('Failed to load more games:', error)
    } finally {
      setLoadingMore(false)
    }
  }

  // handleScroll
  useEffect(() => {
    const handleScroll = () => {
      if (loading || loadingMore || !hasMore) return
      
      const scrollTop = window.scrollY
      const windowHeight = window.innerHeight
      const documentHeight = document.documentElement.scrollHeight
      
      if (scrollTop + windowHeight >= documentHeight - 500) {
        loadMoreGames()
      }
    }

    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [loading, loadingMore, hasMore, page, games.length])

  // getFilteredGames
  const getFilteredGames = () => {
    if (!searchQuery.trim()) return games
    
    return games.filter(game => 
      game.place_name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      game.creator?.toLowerCase().includes(searchQuery.toLowerCase())
    )
  }

  const filteredGames = getFilteredGames()

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#000000' }}>
      <div className="p-8">
        <div 
          className="relative rounded-2xl border p-8 mb-6 overflow-hidden"
          style={{
            backgroundColor: 'rgba(10, 10, 10, 0.6)',
            borderColor: '#1a1a1a',
            backdropFilter: 'blur(20px)',
          }}
        >
          <div 
            className="absolute inset-0 opacity-30"
            style={{
              background: 'radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.15), transparent 50%), radial-gradient(circle at 80% 50%, rgba(168, 85, 247, 0.15), transparent 50%)',
            }}
          />
          
          <div className="relative z-10">
            <h1 
              className="text-4xl font-bold mb-2"
              style={{ 
                color: '#ffffff',
                textShadow: '0 0 30px rgba(255, 255, 255, 0.1)',
              }}
            >
              Games
            </h1>
            <p 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              Browse supported games
            </p>
          </div>
        </div>

        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div className="relative">
              <Search 
                className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 transition-colors duration-200"
                style={{ color: '#565656' }}
              />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search games..."
                className="pl-12 pr-5 py-3 rounded-2xl text-sm transition-all duration-300"
                style={{
                  width: '360px',
                  backgroundColor: 'rgba(10, 10, 10, 0.6)',
                  border: '1px solid #1a1a1a',
                  color: '#ffffff',
                  outline: 'none',
                  backdropFilter: 'blur(10px)',
                }}
                onFocus={(e) => {
                  e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.9)'
                  e.currentTarget.style.boxShadow = '0 0 20px rgba(255, 255, 255, 0.1)'
                  e.currentTarget.previousElementSibling.style.color = '#ffffff'
                }}
                onBlur={(e) => {
                  e.currentTarget.style.borderColor = '#1a1a1a'
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.6)'
                  e.currentTarget.style.boxShadow = 'none'
                  e.currentTarget.previousElementSibling.style.color = '#565656'
                }}
              />
            </div>

            <div className="flex gap-3">
              <div 
                className="px-4 py-2 rounded-xl text-sm font-semibold"
                style={{
                  backgroundColor: 'rgba(10, 10, 10, 0.6)',
                  border: '1px solid #1a1a1a',
                  color: '#6b7280',
                  backdropFilter: 'blur(10px)',
                }}
              >
                🎮 {stats.total_games} games
              </div>
              
              <div 
                className="px-4 py-2 rounded-xl text-sm font-semibold"
                style={{
                  backgroundColor: 'rgba(10, 10, 10, 0.6)',
                  border: '1px solid #1a1a1a',
                  color: '#6b7280',
                  backdropFilter: 'blur(10px)',
                }}
              >
                👥 {stats.total_active} active
              </div>
            </div>
          </div>
        </div>

        {loading ? (
          <div className="flex flex-col items-center justify-center py-32">
            <div 
              className="w-16 h-16 rounded-full animate-spin mb-6 relative"
              style={{
                border: '3px solid #1a1a1a',
                borderTopColor: '#ffffff',
                boxShadow: '0 0 30px rgba(255, 255, 255, 0.2)',
              }}
            />
            <div className="text-base font-medium" style={{ color: '#6b7280' }}>
              Loading games...
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
            {filteredGames.map((game, index) => (
              <div
                key={index}
                className="rounded-3xl border overflow-hidden transition-all duration-300 group relative"
                style={{
                  backgroundColor: 'rgba(10, 10, 10, 0.4)',
                  borderColor: '#1a1a1a',
                  backdropFilter: 'blur(20px)',
                  cursor: 'pointer',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                  e.currentTarget.style.transform = 'translateY(-6px) scale(1.02)'
                  e.currentTarget.style.boxShadow = '0 12px 40px rgba(255, 255, 255, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.1)'
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.8)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = '#1a1a1a'
                  e.currentTarget.style.transform = 'translateY(0) scale(1)'
                  e.currentTarget.style.boxShadow = 'none'
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.4)'
                }}
              >
                {game.thumbnail_url && (
                  <div 
                    className="w-full h-48 bg-cover bg-center relative overflow-hidden"
                    style={{
                      backgroundImage: `url(${game.thumbnail_url})`,
                      backgroundColor: '#0a0a0a',
                    }}
                  >
                    <div 
                      className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-all duration-500"
                      style={{
                        background: 'linear-gradient(to top, rgba(0,0,0,0.95), rgba(255, 255, 255, 0.05) 60%, transparent)',
                      }}
                    />
                  </div>
                )}

                <div className="p-6">
                  <h3 
                    className="font-bold text-lg mb-3 truncate transition-colors duration-200"
                    style={{ 
                      color: '#ffffff',
                      letterSpacing: '-0.02em',
                    }}
                  >
                    {game.place_name || 'Untitled Game'}
                  </h3>

                  {game.creator && (
                    <p 
                      className="text-sm mb-2 leading-relaxed"
                      style={{ color: '#6b7280' }}
                    >
                      by {game.creator}
                    </p>
                  )}

                  <div className="flex gap-2 mb-5 text-xs" style={{ color: '#6b7280' }}>
                    {game.total_active && (
                      <span>👥 {game.total_active} playing</span>
                    )}
                    {game.visits && (
                      <span>👁️ {game.visits.toLocaleString()} visits</span>
                    )}
                  </div>

                  <div className="flex gap-2.5">
                    <button
                      onClick={() => console.log('Launch game:', game)}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-sm font-bold transition-all duration-300 relative overflow-hidden"
                      style={{
                        backgroundColor: 'rgba(59, 130, 246, 0.15)',
                        border: '1px solid rgba(59, 130, 246, 0.3)',
                        color: '#3b82f6',
                        cursor: 'pointer',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(59, 130, 246, 0.25)'
                        e.currentTarget.style.borderColor = 'rgba(59, 130, 246, 0.5)'
                        e.currentTarget.style.transform = 'scale(1.03)'
                        e.currentTarget.style.boxShadow = '0 0 20px rgba(59, 130, 246, 0.3)'
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(59, 130, 246, 0.15)'
                        e.currentTarget.style.borderColor = 'rgba(59, 130, 246, 0.3)'
                        e.currentTarget.style.transform = 'scale(1)'
                        e.currentTarget.style.boxShadow = 'none'
                      }}
                    >
                      <Play className="h-4 w-4" />
                      Launch
                    </button>

                    {game.total_active && (
                      <div
                        className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-sm font-bold"
                        style={{
                          backgroundColor: 'rgba(0, 0, 0, 0.4)',
                          border: '1px solid #2a2a2a',
                          color: '#6b7280',
                        }}
                      >
                        <Users className="h-4 w-4" />
                        {game.total_active}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {!loading && filteredGames.length === 0 && (
          <div className="flex flex-col items-center justify-center py-24">
            <div 
              className="w-24 h-24 rounded-full flex items-center justify-center mb-6"
              style={{
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                border: '2px solid rgba(59, 130, 246, 0.3)',
              }}
            >
              <Play 
                className="h-12 w-12"
                style={{ color: '#3b82f6', opacity: 0.5 }}
              />
            </div>
            <div 
              className="text-lg font-semibold mb-2"
              style={{ color: '#ffffff' }}
            >
              No games available
            </div>
            <div 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              {searchQuery ? 'Try a different search term' : 'Games will appear here when they become available'}
            </div>
          </div>
        )}

        {loadingMore && (
          <div className="flex justify-center py-8">
            <div 
              className="w-12 h-12 rounded-full animate-spin"
              style={{
                border: '3px solid #1a1a1a',
                borderTopColor: '#ffffff',
                boxShadow: '0 0 30px rgba(255, 255, 255, 0.2)',
              }}
            />
          </div>
        )}

        {!loading && !loadingMore && !hasMore && filteredGames.length > 0 && (
          <div className="flex justify-center py-8">
            <div 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              All games loaded
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
