import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../components/Toast';
import api from '../api/axios';
import PopularityBadge from '../components/PopularityBadge';

function Manager() {
  const { isAuthenticated, loading: authLoading } = useAuth();
  const navigate = useNavigate();
  const { error, success } = useToast();

  const [games, setGames] = useState([]);
  const [packs, setPacks] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [editingGame, setEditingGame] = useState(null);
  const [showAddGame, setShowAddGame] = useState(false);
  const [showImportExport, setShowImportExport] = useState(false);
  
  // Tree view states
  const [expandedPacks, setExpandedPacks] = useState(new Set());
  const [searchFilter, setSearchFilter] = useState('');
  const [viewMode, setViewMode] = useState('all'); // all, enabled, disabled
  const [packSortBy, setPackSortBy] = useState('name'); // name, enabled, games, activity

  useEffect(() => {
    // Wait for auth to finish loading before checking authentication
    if (authLoading) return;
    
    if (!isAuthenticated) {
      navigate('/login');
      return;
    }
    loadData();
  }, [isAuthenticated, authLoading, navigate]);

  const loadData = async () => {
    try {
      const [gamesRes, packsRes, statsRes, packBiasRes] = await Promise.all([
        api.get('/games'),
        api.get('/games/meta/packs'),
        api.get('/stats'),
        api.get('/games/packs')
      ]);

      setGames(gamesRes.data);
      
      // Merge pack metadata with favor bias data
      const packBiasMap = {};
      packBiasRes.data.forEach(pack => {
        packBiasMap[pack.name] = pack.favor_bias || 0;
      });
      
      const enrichedPacks = packsRes.data.map(pack => ({
        ...pack,
        favor_bias: packBiasMap[pack.name] || 0
      }));
      
      setPacks(enrichedPacks);
      setStats(statsRes.data);
    } catch (err) {
      console.error('Failed to load data', err);
    } finally {
      setLoading(false);
    }
  };

  const handleToggleGame = async (gameId) => {
    try {
      await api.patch(`/games/${gameId}/toggle`);
      await loadData();
    } catch (err) {
      error('Failed to toggle game');
    }
  };

  const handleTogglePack = async (packName, enabled) => {
    try {
      await api.patch(`/games/packs/${encodeURIComponent(packName)}/toggle`, { enabled });
      await loadData();
      success(`Pack ${enabled ? 'enabled' : 'disabled'}`);
    } catch (err) {
      error('Failed to toggle pack');
    }
  };

  const handleGameFavorChange = async (gameId, newBias) => {
    try {
      await api.patch(`/games/${gameId}/favor`, { favor_bias: newBias });
      await loadData();
    } catch (err) {
      error('Failed to update game favor status');
    }
  };

  const handlePackFavorChange = async (packName, newBias) => {
    try {
      await api.patch(`/games/packs/${encodeURIComponent(packName)}/favor`, { favor_bias: newBias });
      await loadData();
    } catch (err) {
      error('Failed to update pack favor status');
    }
  };

  const [confirmingDelete, setConfirmingDelete] = useState(null);

  const handleDeleteClick = (gameId) => {
    if (confirmingDelete === gameId) {
      handleDeleteGame(gameId);
    } else {
      setConfirmingDelete(gameId);
      setTimeout(() => setConfirmingDelete(null), 3000);
    }
  };

  const handleDeleteGame = async (gameId) => {
    try {
      await api.delete(`/games/${gameId}`);
      await loadData();
      setConfirmingDelete(null);
      success('Game deleted successfully');
    } catch (err) {
      error('Failed to delete game');
      setConfirmingDelete(null);
    }
  };

  const handleExportCSV = async () => {
    try {
      const response = await api.get('/games/export/csv', {
        responseType: 'blob'
      });
      
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'games-export.csv');
      document.body.appendChild(link);
      link.click();
      link.remove();
      success('CSV exported successfully');
    } catch (err) {
      error('Failed to export CSV');
    }
  };

  // Natural sort for alphanumeric strings (fixes "Pack 10" vs "Pack 4")
  const naturalSort = (a, b) => {
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  };

  // Organize games by pack for tree view
  const packTree = React.useMemo(() => {
    const tree = {};
    
    // Build tree structure
    games.forEach(game => {
      if (!tree[game.pack_name]) {
        const packInfo = packs.find(p => p.name === game.pack_name);
        tree[game.pack_name] = {
          name: game.pack_name,
          enabled_count: packInfo?.enabled_count || 0,
          total_count: packInfo?.total_count || 0,
          favor_bias: packInfo?.favor_bias || 0,
          games: [],
          total_plays: 0
        };
      }
      
      // Apply search filter
      if (searchFilter && !game.title.toLowerCase().includes(searchFilter.toLowerCase())) {
        return;
      }
      
      // Apply view mode filter
      if (viewMode === 'enabled' && !game.enabled) return;
      if (viewMode === 'disabled' && game.enabled) return;
      
      tree[game.pack_name].games.push(game);
      tree[game.pack_name].total_plays += game.play_count || 0;
    });
    
    // Convert to array and sort
    return Object.values(tree)
      .filter(pack => pack.games.length > 0) // Only show packs with games matching filters
      .sort((a, b) => {
        // Fully disabled packs go to bottom (unless sorting by something specific)
        const aDisabled = a.enabled_count === 0;
        const bDisabled = b.enabled_count === 0;
        if (packSortBy === 'name' && aDisabled !== bDisabled) {
          return aDisabled ? 1 : -1;
        }
        
        // Sort by selected criteria
        switch (packSortBy) {
          case 'name':
            return naturalSort(a.name, b.name);
          
          case 'enabled':
            // Most enabled first
            const aRatio = a.enabled_count / a.total_count;
            const bRatio = b.enabled_count / b.total_count;
            if (aRatio !== bRatio) return bRatio - aRatio;
            return naturalSort(a.name, b.name);
          
          case 'games':
            // Most games first
            if (a.total_count !== b.total_count) return b.total_count - a.total_count;
            return naturalSort(a.name, b.name);
          
          case 'activity':
            // Most played first
            if (a.total_plays !== b.total_plays) return b.total_plays - a.total_plays;
            return naturalSort(a.name, b.name);
          
          default:
            return naturalSort(a.name, b.name);
        }
      });
  }, [games, packs, searchFilter, viewMode, packSortBy]);

  const togglePack = (packName) => {
    const newExpanded = new Set(expandedPacks);
    if (newExpanded.has(packName)) {
      newExpanded.delete(packName);
    } else {
      newExpanded.add(packName);
    }
    setExpandedPacks(newExpanded);
  };

  const toggleAllPacks = (expand) => {
    if (expand) {
      setExpandedPacks(new Set(packTree.map(p => p.name)));
    } else {
      setExpandedPacks(new Set());
    }
  };

  if (authLoading || 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-7xl mx-auto">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <h1 className="text-3xl sm:text-4xl font-bold text-gray-800 dark:text-gray-100">Game Manager</h1>
        
        {/* Action Buttons */}
        <div className="flex flex-wrap gap-2">
          <button
            onClick={() => setShowAddGame(true)}
            className="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition text-sm"
          >
            + Add Game
          </button>
          <button
            onClick={() => setShowImportExport(!showImportExport)}
            className="bg-gray-600 dark:bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-700 dark:hover:bg-gray-800 transition text-sm"
          >
            Import/Export
          </button>
          <button
            onClick={handleExportCSV}
            className="bg-green-600 dark:bg-green-700 text-white px-4 py-2 rounded-lg hover:bg-green-700 dark:hover:bg-green-800 transition text-sm"
          >
            Export CSV
          </button>
        </div>
      </div>

      {/* Statistics */}
      {stats && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4 mb-6">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
            <div className="text-2xl sm:text-3xl font-bold text-indigo-600 dark:text-indigo-400">{stats.games.count}</div>
            <div className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">Total Games</div>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
            <div className="text-2xl sm:text-3xl font-bold text-green-600 dark:text-green-400">{stats.gamesEnabled.count}</div>
            <div className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">Enabled</div>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
            <div className="text-2xl sm:text-3xl font-bold text-blue-600 dark:text-blue-400">{stats.packs.count}</div>
            <div className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">Packs</div>
          </div>
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
            <div className="text-2xl sm:text-3xl font-bold text-purple-600 dark:text-purple-400">{stats.totalGamesPlayed.count}</div>
            <div className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">Played</div>
          </div>
        </div>
      )}

      {/* Import/Export Panel */}
      {showImportExport && (
        <ImportExportPanel onClose={() => setShowImportExport(false)} onImportComplete={loadData} />
      )}

      {/* Add/Edit Game Form */}
      {(showAddGame || editingGame) && (
        <GameForm
          game={editingGame}
          onClose={() => {
            setShowAddGame(false);
            setEditingGame(null);
          }}
          onSave={loadData}
        />
      )}

      {/* Tree View - Packs and Games */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-4 sm:p-6">
        {/* Header Controls */}
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
          <h2 className="text-2xl font-semibold text-gray-800 dark:text-gray-100">
            Packs & Games
          </h2>
          
          <div className="flex flex-wrap gap-2 items-center w-full sm:w-auto">
            {/* Search */}
            <input
              type="text"
              placeholder="Search games..."
              value={searchFilter}
              onChange={(e) => setSearchFilter(e.target.value)}
              className="flex-1 sm:flex-initial sm:w-48 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
            />
            
            {/* Sort Packs */}
            <select
              value={packSortBy}
              onChange={(e) => setPackSortBy(e.target.value)}
              className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
              title="Sort packs by"
            >
              <option value="name">Sort: Name</option>
              <option value="enabled">Sort: % Enabled</option>
              <option value="games">Sort: # Games</option>
              <option value="activity">Sort: Activity</option>
            </select>
            
            {/* View Mode Filter */}
            <select
              value={viewMode}
              onChange={(e) => setViewMode(e.target.value)}
              className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
            >
              <option value="all">All Games</option>
              <option value="enabled">Enabled Only</option>
              <option value="disabled">Disabled Only</option>
            </select>
            
            {/* Expand/Collapse All */}
            <div className="flex gap-1">
              <button
                onClick={() => toggleAllPacks(true)}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300"
                title="Expand all packs"
              >
                ⊕
              </button>
              <button
                onClick={() => toggleAllPacks(false)}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300"
                title="Collapse all packs"
              >
                ⊖
              </button>
            </div>
          </div>
        </div>

        {/* Tree View */}
        <div className="space-y-1">
          {packTree.length === 0 ? (
            <div className="text-center py-8 text-gray-500 dark:text-gray-400">
              No games found matching your filters
            </div>
          ) : (
            packTree.map((pack) => (
              <PackTreeNode
                key={pack.name}
                pack={pack}
                isExpanded={expandedPacks.has(pack.name)}
                onToggle={() => togglePack(pack.name)}
                onTogglePack={handleTogglePack}
                onToggleGame={handleToggleGame}
                onEditGame={setEditingGame}
                onDeleteGame={handleDeleteGame}
                onDeleteClick={handleDeleteClick}
                confirmingDelete={confirmingDelete}
                onPackFavorChange={handlePackFavorChange}
                onGameFavorChange={handleGameFavorChange}
              />
            ))
          )}
        </div>
      </div>
    </div>
  );
}

// Pack Tree Node Component
function PackTreeNode({ pack, isExpanded, onToggle, onTogglePack, onToggleGame, onEditGame, onDeleteGame, onDeleteClick, confirmingDelete, onPackFavorChange, onGameFavorChange }) {
  const isFullyDisabled = pack.enabled_count === 0;
  const isFullyEnabled = pack.enabled_count === pack.total_count;
  
  // Determine pack background based on favor bias
  const getPackBackground = () => {
    if (isFullyDisabled) {
      return 'bg-gray-100 dark:bg-gray-800/50 opacity-70';
    }
    if (pack.favor_bias === 1) {
      return 'bg-green-50 dark:bg-green-900/20 hover:bg-green-100 dark:hover:bg-green-900/30 border-l-4 border-green-400 dark:border-green-600';
    }
    if (pack.favor_bias === -1) {
      return 'bg-red-50 dark:bg-red-900/20 hover:bg-red-100 dark:hover:bg-red-900/30 border-l-4 border-red-400 dark:border-red-600';
    }
    return 'bg-gray-50 dark:bg-gray-700/30 hover:bg-gray-100 dark:hover:bg-gray-700/50';
  };
  
  return (
    <div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
      {/* Pack Header */}
      <div 
        className={`p-3 transition ${getPackBackground()}`}
      >
        {/* Row 1: Expand/Collapse + Checkbox + Pack Name */}
        <div className="flex items-center gap-2 mb-2">
          {/* Expand/Collapse Button */}
          <button
            onClick={onToggle}
            className="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 w-6 h-6 flex items-center justify-center flex-shrink-0"
          >
            {isExpanded ? '▼' : '▶'}
          </button>
          
          {/* Pack Checkbox */}
          <input
            type="checkbox"
            checked={isFullyEnabled}
            onChange={(e) => {
              e.stopPropagation();
              onTogglePack(pack.name, e.target.checked);
            }}
            className="w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-indigo-600 focus:ring-indigo-500 dark:bg-gray-700 cursor-pointer flex-shrink-0 mr-2"
            title={`${isFullyEnabled ? 'Disable' : 'Enable'} all games in ${pack.name}`}
          />
          
          {/* Pack Name */}
          <div 
            className="flex-1 min-w-0 cursor-pointer"
            onClick={onToggle}
          >
            <div className={`font-semibold text-base md:text-lg truncate ${
              isFullyDisabled 
                ? 'text-gray-500 dark:text-gray-500' 
                : 'text-gray-800 dark:text-gray-100'
            }`}>
              📦 {pack.name}
            </div>
          </div>
        </div>
        
        {/* Row 2: Metadata + Favor Controls */}
        <div className="flex items-center justify-between gap-2 ml-12">
          {/* Pack Info */}
          <div className="text-xs md:text-sm text-gray-500 dark:text-gray-400">
            {pack.enabled_count} / {pack.total_count} enabled
          </div>
          
          {/* Pack Favor Controls */}
          {!isFullyDisabled && (
            <div className="flex items-center gap-1.5 md:gap-2" onClick={(e) => e.stopPropagation()}>
              {pack.favor_bias === 1 && (
                <span className="text-xs md:text-sm font-semibold bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-2 py-0.5 md:py-1 rounded whitespace-nowrap">
                  Favored
                </span>
              )}
              {pack.favor_bias === -1 && (
                <span className="text-xs md:text-sm font-semibold bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 px-2 py-0.5 md:py-1 rounded whitespace-nowrap">
                  Disfavored
                </span>
              )}
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  if (pack.favor_bias === 1) {
                    onPackFavorChange(pack.name, 0);
                  } else {
                    onPackFavorChange(pack.name, 1);
                  }
                }}
                className={`text-xs md:text-sm px-2 md:px-3 py-1 md:py-1.5 rounded transition font-medium whitespace-nowrap ${
                  pack.favor_bias === 1
                    ? 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
                    : 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 hover:bg-green-200 dark:hover:bg-green-800'
                }`}
              >
                {pack.favor_bias === 1 ? 'Unfavor' : 'Favor'}
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  if (pack.favor_bias === -1) {
                    onPackFavorChange(pack.name, 0);
                  } else {
                    onPackFavorChange(pack.name, -1);
                  }
                }}
                className={`text-xs md:text-sm px-2 md:px-3 py-1 md:py-1.5 rounded transition font-medium whitespace-nowrap ${
                  pack.favor_bias === -1
                    ? 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
                    : 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-800'
                }`}
              >
                {pack.favor_bias === -1 ? 'Undisfavor' : 'Disfavor'}
              </button>
            </div>
          )}
        </div>
      </div>
      
      {/* Games List */}
      {isExpanded && pack.games.length > 0 && (
        <div className="bg-white dark:bg-gray-800">
          {pack.games.map((game) => {
            // Determine game row background based on favor bias
            const getGameBackground = () => {
              if (game.favor_bias === 1) {
                return 'bg-green-50 dark:bg-green-900/10 hover:bg-green-100 dark:hover:bg-green-900/20 border-l-4 border-green-300 dark:border-green-700';
              }
              if (game.favor_bias === -1) {
                return 'bg-red-50 dark:bg-red-900/10 hover:bg-red-100 dark:hover:bg-red-900/20 border-l-4 border-red-300 dark:border-red-700';
              }
              return 'hover:bg-gray-50 dark:hover:bg-gray-700/30';
            };
            
            return (
            <div
              key={game.id}
              className={`p-3 pl-8 sm:pl-12 border-t border-gray-100 dark:border-gray-700 transition ${getGameBackground()}`}
            >
              {/* Row 1: Checkbox + Game Icon + Title */}
              <div className="flex items-center gap-2 mb-2">
                {/* Game Checkbox */}
                <input
                  type="checkbox"
                  checked={game.enabled}
                  onChange={(e) => {
                    e.stopPropagation();
                    onToggleGame(game.id);
                  }}
                  className="w-4 h-4 rounded border-gray-300 dark:border-gray-600 text-indigo-600 focus:ring-indigo-500 dark:bg-gray-700 cursor-pointer flex-shrink-0 mr-3"
                />
                
                {/* Game Icon and Title */}
                <span className="text-lg md:text-xl flex-shrink-0">🎮</span>
                <span className={`font-medium text-base md:text-lg truncate flex-1 ${
                  game.enabled 
                    ? 'text-gray-800 dark:text-gray-200' 
                    : 'text-gray-500 dark:text-gray-500 line-through'
                }`}>
                  {game.title}
                </span>
              </div>
              
              {/* Row 2: Game Stats + Favor Controls */}
              <div className="flex items-center justify-between gap-2 ml-7">
                {/* Game Stats */}
                <div className="flex items-center gap-3 text-xs md:text-sm text-gray-500 dark:text-gray-400">
                  <span title="Players">{game.min_players}-{game.max_players} 👥</span>
                  <span title="Play count">{game.play_count} ▶️</span>
                  <PopularityBadge 
                    upvotes={game.upvotes || 0}
                    downvotes={game.downvotes || 0}
                    popularityScore={game.popularity_score || 0}
                    size="sm"
                    showCounts={false}
                    showNet={true}
                    showRatio={false}
                  />
                </div>
                
                {/* Favor Controls */}
                {game.enabled && (
                  <div className="flex items-center gap-1.5 md:gap-2">
                    {game.favor_bias === 1 && (
                      <span className="text-xs md:text-sm font-semibold bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-2 py-0.5 md:py-1 rounded whitespace-nowrap">
                        Favored
                      </span>
                    )}
                    {game.favor_bias === -1 && (
                      <span className="text-xs md:text-sm font-semibold bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 px-2 py-0.5 md:py-1 rounded whitespace-nowrap">
                        Disfavored
                      </span>
                    )}
                    
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        if (game.favor_bias === 1) {
                          onGameFavorChange(game.id, 0);
                        } else {
                          onGameFavorChange(game.id, 1);
                        }
                      }}
                      className={`text-xs md:text-sm px-2 md:px-3 py-1 md:py-1.5 rounded transition font-medium whitespace-nowrap ${
                        game.favor_bias === 1
                          ? 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
                          : 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 hover:bg-green-200 dark:hover:bg-green-800'
                      }`}
                    >
                      {game.favor_bias === 1 ? 'Unfavor' : 'Favor'}
                    </button>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        if (game.favor_bias === -1) {
                          onGameFavorChange(game.id, 0);
                        } else {
                          onGameFavorChange(game.id, -1);
                        }
                      }}
                      className={`text-xs md:text-sm px-2 md:px-3 py-1 md:py-1.5 rounded transition font-medium whitespace-nowrap ${
                          game.favor_bias === -1
                            ? 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
                            : 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-800'
                        }`}
                      >
                        {game.favor_bias === -1 ? 'Undisfavor' : 'Disfavor'}
                      </button>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    )}
  </div>
  );
}

function GameForm({ game, onClose, onSave }) {
  const { error, success } = useToast();
  const [formData, setFormData] = useState(game || {
    pack_name: '',
    title: '',
    min_players: 1,
    max_players: 8,
    length_minutes: '',
    has_audience: false,
    family_friendly: false,
    game_type: '',
    secondary_type: ''
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      if (game) {
        await api.put(`/games/${game.id}`, formData);
        success('Game updated successfully');
      } else {
        await api.post('/games', formData);
        success('Game added successfully');
      }
      onSave();
      onClose();
    } catch (err) {
      error('Failed to save game');
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg p-8 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <h2 className="text-2xl font-bold mb-6 dark:text-gray-100">{game ? 'Edit Game' : 'Add New Game'}</h2>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Title *</label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({...formData, title: e.target.value})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                required
              />
            </div>
            
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Pack Name *</label>
              <input
                type="text"
                value={formData.pack_name}
                onChange={(e) => setFormData({...formData, pack_name: e.target.value})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                required
              />
            </div>
            
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Min Players *</label>
              <input
                type="number"
                min="1"
                value={formData.min_players}
                onChange={(e) => setFormData({...formData, min_players: parseInt(e.target.value)})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                required
              />
            </div>
            
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Max Players *</label>
              <input
                type="number"
                min="1"
                value={formData.max_players}
                onChange={(e) => setFormData({...formData, max_players: parseInt(e.target.value)})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                required
              />
            </div>
            
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Length (minutes)</label>
              <input
                type="number"
                value={formData.length_minutes}
                onChange={(e) => setFormData({...formData, length_minutes: e.target.value ? parseInt(e.target.value) : ''})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
              />
            </div>
            
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Game Type</label>
              <input
                type="text"
                value={formData.game_type}
                onChange={(e) => setFormData({...formData, game_type: e.target.value})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
              />
            </div>
            
            <div>
              <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Secondary Type</label>
              <input
                type="text"
                value={formData.secondary_type}
                onChange={(e) => setFormData({...formData, secondary_type: e.target.value})}
                className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
              />
            </div>
          </div>
          
          <div className="flex gap-4">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.has_audience}
                onChange={(e) => setFormData({...formData, has_audience: e.target.checked})}
                className="mr-2 form-checkbox"
              />
              <span className="text-gray-700 dark:text-gray-300">Has Audience</span>
            </label>
            
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={formData.family_friendly}
                onChange={(e) => setFormData({...formData, family_friendly: e.target.checked})}
                className="mr-2 form-checkbox"
              />
              <span className="text-gray-700 dark:text-gray-300">Family Friendly</span>
            </label>
          </div>
          
          <div className="flex gap-4 pt-4">
            <button
              type="submit"
              className="flex-1 bg-indigo-600 text-white py-3 rounded-lg hover:bg-indigo-700 transition"
            >
              Save
            </button>
            <button
              type="button"
              onClick={onClose}
              className="flex-1 bg-gray-600 dark:bg-gray-700 text-white py-3 rounded-lg hover:bg-gray-700 dark:hover:bg-gray-800 transition"
            >
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function ImportExportPanel({ onClose, onImportComplete }) {
  const { error, success } = useToast();
  const [csvData, setCsvData] = useState('');
  const [importMode, setImportMode] = useState('append');

  const handleImport = async () => {
    if (!csvData.trim()) {
      error('Please enter CSV data');
      return;
    }

    try {
      await api.post('/games/import/csv', { csvData, mode: importMode });
      success('Import successful!');
      onImportComplete();
      onClose();
    } catch (err) {
      error('Import failed: ' + (err.response?.data?.error || err.message));
    }
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 mb-6">
      <h3 className="text-xl font-semibold mb-4 dark:text-gray-100">Import Games from CSV</h3>
      
      <div className="mb-4">
        <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">Import Mode</label>
        <select
          value={importMode}
          onChange={(e) => setImportMode(e.target.value)}
          className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
        >
          <option value="append">Append (keep existing games)</option>
          <option value="replace">Replace (delete all existing games)</option>
        </select>
      </div>
      
      <div className="mb-4">
        <label className="block text-gray-700 dark:text-gray-300 font-semibold mb-2">CSV Data</label>
        <textarea
          value={csvData}
          onChange={(e) => setCsvData(e.target.value)}
          className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg h-48 font-mono text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
          placeholder="Paste CSV data here..."
        />
      </div>
      
      <div className="flex gap-4">
        <button
          onClick={handleImport}
          className="bg-indigo-600 dark:bg-indigo-700 text-white px-6 py-2 rounded-lg hover:bg-indigo-700 dark:hover:bg-indigo-800 transition"
        >
          Import
        </button>
        <button
          onClick={onClose}
          className="bg-gray-600 dark:bg-gray-700 text-white px-6 py-2 rounded-lg hover:bg-gray-700 dark:hover:bg-gray-800 transition"
        >
          Close
        </button>
      </div>
    </div>
  );
}

export default Manager;

