import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import type { Lobby } from "@lila/shared";

const API_URL = (import.meta.env["VITE_API_URL"] as string) || "";

type LobbySuccessResponse = { success: true; data: Lobby };
type LobbyErrorResponse = { success: false; error: string };
type LobbyApiResponse = LobbySuccessResponse | LobbyErrorResponse;

export const Route = createFileRoute("/multiplayer/")({
  component: MultiplayerPage,
});

function MultiplayerPage() {
  const navigate = useNavigate();
  const [joinCode, setJoinCode] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [isJoining, setIsJoining] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleCreate = async (): Promise<void> => {
    setIsCreating(true);
    setError(null);
    try {
      const response = await fetch(`${API_URL}/api/v1/lobbies`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
      });
      const data = (await response.json()) as LobbyApiResponse;
      if (!data.success) {
        setError(data.error);
        return;
      }
      void navigate({
        to: "/multiplayer/lobby/$code",
        params: { code: data.data.code },
      });
    } catch {
      setError("Could not connect to server. Please try again.");
    } finally {
      setIsCreating(false);
    }
  };

  const handleJoin = async (): Promise<void> => {
    const code = joinCode.trim().toUpperCase();
    if (!code) {
      setError("Please enter a lobby code.");
      return;
    }
    setIsJoining(true);
    setError(null);
    try {
      const response = await fetch(`${API_URL}/api/v1/lobbies/${code}/join`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
      });
      const data = (await response.json()) as LobbyApiResponse;
      if (!data.success) {
        setError(data.error);
        return;
      }
      void navigate({
        to: "/multiplayer/lobby/$code",
        params: { code: data.data.code },
      });
    } catch {
      setError("Could not connect to server. Please try again.");
    } finally {
      setIsJoining(false);
    }
  };

  return (
    <div className="min-h-screen bg-linear-to-b from-purple-100 to-pink-50 flex items-center justify-center p-6">
      <div className="bg-white rounded-2xl shadow-lg p-8 w-full max-w-md flex flex-col gap-6">
        <h1 className="text-2xl font-bold text-center text-purple-800">
          Multiplayer
        </h1>

        {error && <p className="text-red-500 text-sm text-center">{error}</p>}

        {/* Create lobby */}
        <div className="flex flex-col gap-2">
          <h2 className="text-lg font-semibold text-gray-700">
            Create a lobby
          </h2>
          <p className="text-sm text-gray-500">
            Start a new game and invite friends with a code.
          </p>
          <button
            className="rounded bg-purple-600 px-4 py-2 text-white hover:bg-purple-500 disabled:opacity-50"
            onClick={() => {
              void handleCreate().catch((err) => {
                console.error("Create lobby error:", err);
              });
            }}
            disabled={isCreating || isJoining}
          >
            {isCreating ? "Creating..." : "Create Lobby"}
          </button>
        </div>

        <div className="border-t border-gray-200" />

        {/* Join lobby */}
        <div className="flex flex-col gap-2">
          <h2 className="text-lg font-semibold text-gray-700">Join a lobby</h2>
          <p className="text-sm text-gray-500">
            Enter the code shared by your host.
          </p>
          <input
            className="rounded border border-gray-300 px-3 py-2 text-sm uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-purple-400"
            placeholder="Enter code (e.g. WOLF42)"
            value={joinCode}
            onChange={(e) => setJoinCode(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                void handleJoin().catch((err) => {
                  console.error("Join lobby error:", err);
                });
              }
            }}
            maxLength={10}
            disabled={isCreating || isJoining}
          />
          <button
            className="rounded bg-gray-800 px-4 py-2 text-white hover:bg-gray-700 disabled:opacity-50"
            onClick={() => {
              void handleJoin().catch((err) => {
                console.error("Join lobby error:", err);
              });
            }}
            disabled={isCreating || isJoining || !joinCode.trim()}
          >
            {isJoining ? "Joining..." : "Join Lobby"}
          </button>
        </div>
      </div>
    </div>
  );
}
