import React, { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { useNakama } from "./providers/NakamaProvider";
import Player from "./Player";
import { PlayerModel } from "./models/player";

import TicTacToeBoard from "./games/tictactoe/TicTacToeBoard";

export default function App() {
  // setting up a 2D game boards
  const [boards, setBoards] = useState<Record<string, { grid: string[][] }>>({});
  const [turn, setTurn] = useState<number>(0);
  const [winner, setWinner] = useState<string | null>(null);
  const [gameOver, setGameOver] = useState<boolean | null>(null);
  const [players, setPlayers] = useState<PlayerModel[]>([]);

  const { sendMatchData, onMatchData, matchId, session } = useNakama();

  // ------------------------------------------
  // MATCH DATA CALLBACK (from Player component)
  // ------------------------------------------
  function onMatchDataCallback(msg: { opCode: number; data: any }) {
    console.log("[Match Data]", msg);

    if (msg.opCode === 2) {
      const state = msg.data;
      console.log("Match state:", state);

      setBoards(state.boards);
      setTurn(state.turn);
      setGameOver(state.game_over);
      if (state.winner >= 0) {
        setWinner(state.players[state.winner].username);
      // } else if (state.game_over) {
      //   // Game ended but winner = -1 → draw
      //   setWinner("draw");
      } else {
        // Ongoing game, no winner
        setWinner(null);
      }
      setPlayers(state.players || []);
    }
  }

  useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "auto";
    };
  }, []);

  useEffect(() => {
    onMatchData(onMatchDataCallback);
  }, [onMatchData]);

  // ------------------------------------------
  // SEND A MOVE
  // ------------------------------------------
  function handleCellClick(row: number, col: number) {
    if (!matchId) return;

    sendMatchData(matchId, 1, {data: {row, col}});
  }

  return (
    <div
      style={{
        height: "100vh",
        display: "flex",
        flexDirection: "column",
        background: "#060606",
        color: "white",
        overflow: "hidden",
      }}
    >
      {/* ---------------- HEADER (always fixed at top) ---------------- */}
      <header
        style={{
          padding: "16px 20px",
          background: "rgba(255,255,255,0.04)",
          borderBottom: "1px solid rgba(255,255,255,0.08)",
          backdropFilter: "blur(6px)",
          textAlign: "center",
          fontSize: "26px",
          fontWeight: 700,
          letterSpacing: "1px",
        }}
      >
        Tic Tac Toe
      </header>

      {/* ---------------- MAIN CONTENT (scrolls) ---------------- */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        style={{
          flex: 1,
          overflowY: "auto",
          padding: "20px",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <Player onMatchDataCallback={onMatchDataCallback} />

        <div
          style={{
            padding: "20px",
            background: "rgba(255,255,255,0.03)",
            borderRadius: "20px",
            boxShadow: "0 6px 20px rgba(0,0,0,0.4)",
            minWidth: "300px",
          }}
        >
          <TicTacToeBoard
            boards={boards}
            turn={turn}
            winner={winner}
            gameOver={gameOver}
            players={players}
            myUserId={session?.user_id ?? null}
            onCellClick={handleCellClick}
          />
        </div>
      </motion.div>
    </div>
  );
}
