import { useState, useEffect } from 'react';
import './App.css';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import ConfigCard from './components/ConfigCard';
import XRayViewer from './components/XRayViewer';
import FloatingButton from './components/FloatingButton';
import AddGameModal from './components/AddGameModal';
import { Game } from './types';
import {
  GetAllGames,
  GetActiveGameID,
  SetActiveGame,
  AddGame,
  UpdateGame,
  DeleteGame,
  TestConnection,
  XRayConnection,
} from '../wailsjs/go/main/App';

function App() {
  const [games, setGames] = useState<Game[]>([]);
  const [activeGameId, setActiveGameId] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);

  // X-Ray State
  const [xrayData, setXrayData] = useState<string | null>(null);
  const [xrayError, setXrayError] = useState<string | null>(null);
  const [xrayLoading, setXrayLoading] = useState(false);
  const [xrayLatency, setXrayLatency] = useState(0);

  // Track local edits for the active game config
  const [editGame, setEditGame] = useState<Game | null>(null);

  const activeGame = games.find((g) => g.id === activeGameId) || null;

  // Load data on mount
  useEffect(() => {
    Promise.all([GetAllGames(), GetActiveGameID()]).then(
      ([g, id]) => {
        setGames(g || []);
        setActiveGameId(id || '');
      }
    );
  }, []);

  // Sync editGame when active game changes
  useEffect(() => {
    setEditGame(activeGame ? { ...activeGame } : null);
    // Reset X-Ray when switching games
    setXrayData(null);
    setXrayError(null);
    setXrayLatency(0);
  }, [activeGameId, games]);

  const handleSelectGame = async (id: string) => {
    setActiveGameId(id);
    await SetActiveGame(id);
  };

  const handleAddGame = async (g: Omit<Game, 'id'>) => {
    const newGame = await AddGame(g as Game);
    setGames((prev) => [...prev, newGame]);
    setActiveGameId(newGame.id);
    await SetActiveGame(newGame.id);
    setShowAddModal(false);
  };

  const handleDeleteGame = async (id: string) => {
    await DeleteGame(id);
    setGames((prev) => prev.filter((g) => g.id !== id));
    if (activeGameId === id) {
      const remaining = games.filter((g) => g.id !== id);
      const newId = remaining.length > 0 ? remaining[0].id : '';
      setActiveGameId(newId);
      if (newId) await SetActiveGame(newId);
    }
  };

  const handleSave = async () => {
    if (!editGame) return;
    await UpdateGame(editGame);
    setGames((prev) =>
      prev.map((g) => (g.id === editGame.id ? editGame : g))
    );
  };

  const handleTest = async () => {
    if (!editGame) throw new Error('No game');
    return await TestConnection(editGame);
  };

  const handleXRay = async () => {
    if (!editGame) return;
    setXrayLoading(true);
    setXrayError(null);
    setXrayData(null);
    
    try {
      const res = await XRayConnection(editGame);
      setXrayLatency(res.latency);
      if (res.success) {
        setXrayData(res.body);
      } else {
        setXrayError(res.error || '请求失败');
      }
    } catch (e: any) {
      setXrayError(e.message || '系统错误');
    } finally {
      setXrayLoading(false);
    }
  };

  const title = activeGame
    ? `控制中心 — ${activeGame.name}`
    : '控制中心';

  return (
    <div className="app-layout">
      <Sidebar
        games={games}
        activeGameId={activeGameId}
        onSelectGame={handleSelectGame}
        onAddGame={() => setShowAddModal(true)}
        onDeleteGame={handleDeleteGame}
      />
      <div className="main-content">
        <Header title={title} />
        <div className="content-area">
          <ConfigCard
            game={editGame}
            onGameUpdate={setEditGame}
            onSave={handleSave}
            onTest={handleTest}
            onXRay={handleXRay}
          />
          <XRayViewer
            data={xrayData}
            error={xrayError}
            loading={xrayLoading}
            latency={xrayLatency}
          />
        </div>
      </div>
      <FloatingButton />
      <AddGameModal
        open={showAddModal}
        onClose={() => setShowAddModal(false)}
        onAdd={handleAddGame}
      />
    </div>
  );
}

export default App;
