import { useState } from 'react'
import React from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { useQuery } from '@tanstack/react-query'
import { 
  ComputerDesktopIcon as GamepadIcon,
  MagnifyingGlassIcon,
  AdjustmentsHorizontalIcon,
  TrophyIcon,
  PlayIcon,
  CheckCircleIcon,
  ChevronDownIcon,
  ListBulletIcon,
  Squares2X2Icon,
  PhotoIcon
} from '@heroicons/react/24/outline'
import GameCard, { GameItem } from '../components/GameCard'
import { gamesApi } from '../services/api'

type ViewMode = 'grid' | 'list' | 'covers'
type SortOption = 'title_asc' | 'title_desc' | 'year_asc' | 'year_desc' | 'playtime_desc' | 'rating_desc' | 'last_played_desc'

const sortOptions: { value: SortOption; label: string }[] = [
  { value: 'title_asc', label: 'Title (A-Z)' },
  { value: 'title_desc', label: 'Title (Z-A)' },
  { value: 'year_asc', label: 'Release Year (Oldest First)' },
  { value: 'year_desc', label: 'Release Year (Newest First)' },
  { value: 'playtime_desc', label: 'Most Played' },
  { value: 'rating_desc', label: 'Highest Rated' },
  { value: 'last_played_desc', label: 'Last Played' }
]

const categoryIcons = {
  BEATEN: TrophyIcon,
  PLAYING: PlayIcon,
  COMPLETED: CheckCircleIcon,
  UNPLAYED: GamepadIcon
}

const categoryColors = {
  BEATEN: 'from-yellow-500 to-amber-600',
  PLAYING: 'from-blue-500 to-blue-600',
  COMPLETED: 'from-green-500 to-green-600',
  UNPLAYED: 'from-gray-500 to-gray-600'
}

export default function GamesPage() {
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const [viewMode, setViewMode] = useState<ViewMode>('grid')
  const [sortBy, setSortBy] = useState<SortOption>('title_asc')
  const [showFilters, setShowFilters] = useState(false)
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['BEATEN', 'PLAYING']))

  const { data: gamesData, isLoading, error } = useQuery({
    queryKey: ['games', searchTerm, sortBy],
    queryFn: () => gamesApi.getAll({ search: searchTerm, sort: sortBy }),
    enabled: !selectedCategory
  })

  const { data: categoryData, isLoading: isLoadingCategory } = useQuery({
    queryKey: ['games', 'category', selectedCategory, searchTerm, sortBy],
    queryFn: () => gamesApi.getByCategory(selectedCategory!, { search: searchTerm, sort: sortBy }),
    enabled: !!selectedCategory
  })

  const toggleCategory = (category: string) => {
    setExpandedCategories(prev => {
      const newSet = new Set(prev)
      if (newSet.has(category)) {
        newSet.delete(category)
      } else {
        newSet.add(category)
      }
      return newSet
    })
  }

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault()
  }

  const clearFilters = () => {
    setSearchTerm('')
    setSelectedCategory(null)
    setSortBy('title_asc')
  }

  const activeFiltersCount = [
    searchTerm,
    selectedCategory,
    sortBy !== 'title_asc'
  ].filter(Boolean).length

  if (isLoading || isLoadingCategory) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <motion.div 
          className="text-center"
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
        >
          <div className="relative">
            <div className="w-16 h-16 border-4 border-green-200 rounded-full"></div>
            <motion.div 
              className="absolute top-0 left-0 w-16 h-16 border-4 border-green-600 rounded-full border-t-transparent"
              animate={{ rotate: 360 }}
              transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
            />
          </div>
          <motion.p 
            className="mt-6 text-gray-600 text-lg"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
          >
            Loading games...
          </motion.p>
        </motion.div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <motion.div 
          className="text-center max-w-md"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <GamepadIcon className="mx-auto h-20 w-20 text-gray-400 mb-6" />
          <h2 className="text-3xl font-bold text-gray-900 mb-3">Error Loading Games</h2>
          <p className="text-gray-600 mb-8 text-lg">Failed to load your game library. Please try again later.</p>
          <motion.button
            onClick={() => window.location.reload()}
            className="btn btn-primary"
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            Try Again
          </motion.button>
        </motion.div>
      </div>
    )
  }

  const categories = selectedCategory 
    ? [{ name: selectedCategory, count: categoryData?.count || 0, games: categoryData?.games || [] }]
    : gamesData?.data || []

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white shadow-sm border-b border-gray-200">
        <div className="container mx-auto px-4 py-6">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gradient-to-r from-green-500 to-emerald-600 rounded-xl">
                <GamepadIcon className="w-6 h-6 text-white" />
              </div>
              <h1 className="text-3xl font-bold text-gray-900">Games Library</h1>
            </div>
            
            {/* Search and Filters */}
            <div className="flex flex-col sm:flex-row gap-3 flex-1 lg:max-w-2xl">
              <form onSubmit={handleSearch} className="flex-1">
                <div className="relative">
                  <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search games..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-green-500 focus:border-transparent"
                  />
                </div>
              </form>
              
              <motion.button
                onClick={() => setShowFilters(!showFilters)}
                className={`px-4 py-2 rounded-xl border transition-all duration-200 flex items-center gap-2 ${
                  activeFiltersCount > 0 
                    ? 'border-green-500 bg-green-50 text-green-700' 
                    : 'border-gray-300 hover:border-gray-400'
                }`}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <AdjustmentsHorizontalIcon className="w-4 h-4" />
                Filters
                {activeFiltersCount > 0 && (
                  <span className="bg-green-600 text-white text-xs px-2 py-1 rounded-full">
                    {activeFiltersCount}
                  </span>
                )}
              </motion.button>
            </div>
          </div>

          {/* Filters Panel */}
          <AnimatePresence>
            {showFilters && (
              <motion.div 
                className="mt-6 p-4 bg-gray-50 rounded-xl border border-gray-200"
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                transition={{ duration: 0.3 }}
              >
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {/* Sort */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">Sort By</label>
                    <select
                      value={sortBy}
                      onChange={(e) => setSortBy(e.target.value as SortOption)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
                    >
                      {sortOptions.map(option => (
                        <option key={option.value} value={option.value}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* View Mode */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">View Mode</label>
                    <div className="flex gap-2">
                      {[
                        { mode: 'grid' as ViewMode, icon: Squares2X2Icon, label: 'Grid' },
                        { mode: 'list' as ViewMode, icon: ListBulletIcon, label: 'List' },
                        { mode: 'covers' as ViewMode, icon: PhotoIcon, label: 'Covers' }
                      ].map(({ mode, icon: Icon, label }) => (
                        <motion.button
                          key={mode}
                          onClick={() => setViewMode(mode)}
                          className={`flex-1 px-3 py-2 rounded-lg border transition-all duration-200 flex items-center justify-center gap-1 ${
                            viewMode === mode
                              ? 'border-green-500 bg-green-50 text-green-700'
                              : 'border-gray-300 hover:border-gray-400'
                          }`}
                          whileHover={{ scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                        >
                          <Icon className="w-4 h-4" />
                          <span className="text-sm">{label}</span>
                        </motion.button>
                      ))}
                    </div>
                  </div>

                  {/* Clear Filters */}
                  <div className="flex items-end">
                    <motion.button
                      onClick={clearFilters}
                      className="w-full px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-all duration-200"
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                    >
                      Clear All Filters
                    </motion.button>
                  </div>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>

      {/* Categories and Games */}
      <div className="container mx-auto px-4 py-8">
        {/* Category Navigation */}
        {!selectedCategory && (
          <motion.div 
            className="mb-8"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
          >
            <div className="flex flex-wrap gap-3">
              {categories.map((category: any) => {
                const Icon = categoryIcons[category.name as keyof typeof categoryIcons]
                return (
                  <motion.button
                    key={category.name}
                    onClick={() => setSelectedCategory(category.name)}
                    className="group relative px-6 py-3 bg-white rounded-xl shadow-sm border border-gray-200 hover:shadow-md transition-all duration-200"
                    whileHover={{ scale: 1.02, y: -2 }}
                    whileTap={{ scale: 0.98 }}
                  >
                    <div className="flex items-center gap-3">
                      <div className={`p-2 bg-gradient-to-r ${categoryColors[category.name as keyof typeof categoryColors]} rounded-lg`}>
                        <Icon className="w-5 h-5 text-white" />
                      </div>
                      <div className="text-left">
                        <div className="font-semibold text-gray-900">{category.name}</div>
                        <div className="text-sm text-gray-500">{category.count} games</div>
                      </div>
                    </div>
                    <ChevronDownIcon className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 group-hover:text-gray-600 transition-colors" />
                  </motion.button>
                )
              })}
            </div>
          </motion.div>
        )}

        {/* Back to Categories */}
        {selectedCategory && (
          <motion.div 
            className="mb-6"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
          >
            <motion.button
              onClick={() => setSelectedCategory(null)}
              className="flex items-center gap-2 px-4 py-2 bg-white rounded-lg border border-gray-300 hover:bg-gray-50 transition-all duration-200"
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
            >
              <ChevronDownIcon className="w-4 h-4 rotate-90" />
              Back to Categories
            </motion.button>
          </motion.div>
        )}

        {/* Games List */}
        <div className="space-y-8">
          {categories.map((category: any) => (
            <motion.div
              key={category.name}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
            >
              {/* Category Header */}
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className={`p-2 bg-gradient-to-r ${categoryColors[category.name as keyof typeof categoryColors]} rounded-lg`}>
                    {React.createElement(categoryIcons[category.name as keyof typeof categoryIcons], { 
                      className: "w-5 h-5 text-white" 
                    })}
                  </div>
                  <h2 className="text-2xl font-bold text-gray-900">
                    {category.name} ({category.count})
                  </h2>
                </div>
                
                {!selectedCategory && (
                  <motion.button
                    onClick={() => toggleCategory(category.name)}
                    className="flex items-center gap-2 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 transition-colors"
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                  >
                    {expandedCategories.has(category.name) ? 'Collapse' : 'Expand'}
                    <ChevronDownIcon className={`w-4 h-4 transform transition-transform ${
                      expandedCategories.has(category.name) ? 'rotate-180' : ''
                    }`} />
                  </motion.button>
                )}
              </div>

              {/* Games Grid/List */}
              <AnimatePresence>
                {(expandedCategories.has(category.name) || selectedCategory) && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: 'auto' }}
                    exit={{ opacity: 0, height: 0 }}
                    transition={{ duration: 0.3 }}
                  >
                    {category.games.length === 0 ? (
                      <div className="text-center py-12 bg-white rounded-xl border border-gray-200">
                        <GamepadIcon className="mx-auto w-12 h-12 text-gray-400 mb-4" />
                        <p className="text-gray-500">No games found in this category</p>
                      </div>
                    ) : (
                      <div className={
                        viewMode === 'grid' 
                          ? 'grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6'
                          : viewMode === 'list'
                          ? 'space-y-2'
                          : 'grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-6'
                      }>
                        {category.games.map((game: GameItem, index: number) => (
                          <motion.div
                            key={game.id}
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: index * 0.05 }}
                          >
                            <GameCard
                              game={game}
                              viewMode={viewMode}
                            />
                          </motion.div>
                        ))}
                      </div>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>
          ))}
        </div>
      </div>
    </div>
  )
}
