'use client';
import { connect } from "http2";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import io from 'socket.io-client';


export default function Home() {
  const nameInputRef = useRef<HTMLInputElement>(null);
  const currentPlayers = useState<string | null>(null);
  const [apiConnected, setAPIStatus] = useState<boolean>(false);
  const [gameStatus, setGameStatus] = useState<{ gameActive: boolean, players: any[] }>({
    gameActive: false,
    players: [],
  });

  let baseUrl = "";

  if (typeof window !== "undefined") {
    baseUrl = `${window.location.protocol}//${window.location.hostname}`;
  }
  const backendUrl = `${baseUrl}:${process.env.NEXT_PUBLIC_API_BASE}`;
  const socket = io(`${backendUrl}`);


  const fetchStatus = async () => {
    try {
      const res = await fetch(`${backendUrl}/status`);
      const data = await res.json();
      setAPIStatus(true);
      setGameStatus(data);
    } catch (err) {
      console.error("Failed to fetch status", err);
      setAPIStatus(false);
    }
  };

  // useEffect(() => {
  //   fetchStatus();
  //   // Need to change this so it just listens on a socket instead
  //   const interval = setInterval(fetchStatus, 5000);
  //   return () => clearInterval(interval);
  // }, []);

  useEffect(() => {
    socket.on('connect', () => {
      console.log('Connected to Socket.IO server');
      setAPIStatus(true);
      fetchStatus();
    });

    socket.on('player_update', (data: { nextPlayer: string }) => {
      fetchStatus();
    });

    return () => {
      socket.off('player_update');
    };
  }, []);

  const addPlayer = async () => {
      const playerName = nameInputRef.current?.value?.trim();
      if (!playerName) {
        alert("Please enter a player name");
        return;
      }

      try {
        console.log(`${process.env.NEXT_PUBLIC_API_BASE}`);
        const res = await fetch(`${backendUrl}/add`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name: playerName, group: selectedGroup }),
        });

        if (!res.ok) {
          throw new Error(`Server error: ${res.statusText}`);
        }

        if (nameInputRef.current) {
          nameInputRef.current.value = "";
        }
      } catch (error) {
        console.error("Failed to add player:", error);
      }
    };

    const startGame = async() => {
      fetch(`${backendUrl}/start`);
    }

    const [selectedGroup, setSelectedGroup] = useState<"stripes" | "solids">("stripes");

    const advanceTurn = async () => {
      await fetch(`${backendUrl}/next`); // triggers backend to emit event
    };

    const resetGame = async () => {
      await fetch(`${backendUrl}/reset`); // triggers backend to emit event
    };

    console.log(apiConnected);
    if (apiConnected) {
      return (
        <div>
          <div className="border rounded p-4 max-w-md m-5">
            <h2 className="text-xl font-semibold mb-3">🎯 Game Info</h2>
            <p className="mb-2">Game Active: <strong>{gameStatus.gameActive ? "Yes" : "No"}</strong></p>
            <table className="w-full text-left border-t">
              <thead>
                <tr><th className="py-1">Player</th><th>Group</th></tr>
              </thead>
              <tbody>
                {gameStatus.players.map((player, idx) => (
                  <tr key={idx} className="border-t">
                    <td className="py-1">{player.name}</td>
                    <td>{player.group}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
            <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
              <div className="flex gap-8 mb-4">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="group"
                    value="stripes"
                    checked={selectedGroup === "stripes"}
                    onChange={() => setSelectedGroup("stripes")}
                    className="cursor-pointer"
                  />
                  Stripes
                </label>

                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="radio"
                    name="group"
                    value="solids"
                    checked={selectedGroup === "solids"}
                    onChange={() => setSelectedGroup("solids")}
                    className="cursor-pointer"
                  />
                  Solids
                </label>
              </div>
              <div className="flex gap-4 items-center flex-col sm:flex-row">
                <input ref={nameInputRef} id="name" placeholder="Enter Name Here"></input>
              </div>
              

              <div className="flex gap-4 items-center flex-col sm:flex-row">
                <button
                  onClick={addPlayer}
                  className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto">
                    <Image
                      className="dark:invert"
                      src="/add.svg"
                      alt="Vercel logomark"
                      width={20}
                      height={20}
                  />
                    Add Player</button>
                <button
                  className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
                  onClick={startGame}
                >
                  <Image
                    className="dark:invert"
                    src="/play-button.svg"
                    alt="Vercel logomark"
                    width={20}
                    height={20}
                  />
                  Start Game
                </button>
                <button
                  className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
                  onClick={resetGame}
                >                
                  <Image
                    className="dark:invert"
                    src="/reset.svg"
                    alt="Vercel logomark"
                    width={20}
                    height={20}
                  />
                  Reset Game</button>
                <button
                  onClick={advanceTurn}
                  className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto">
                  <Image
                    className="dark:invert"
                    src="/next.svg"
                    alt="Vercel logomark"
                    width={20}
                    height={20}
                  />Next Turn</button>
              </div>
            </main>
          </div>
        </div>
      );
    }
    else
      return (
        <div>
          <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
            <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">             
              <p>Not Connected to API {apiConnected}</p>
              <div className="flex gap-4 items-center flex-col sm:flex-row">
                <button
                  className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
                  onClick={startGame}
                >
                  <Image
                    className="dark:invert"
                    src="/play-button.svg"
                    alt="Vercel logomark"
                    width={20}
                    height={20}
                  />
                  Try Reconnecting
                </button>
              </div>
            </main>
          </div>
        </div>
      );
}
