<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import type { Lobby } from '../models/public';

const lobbies = ref<Lobby[]>([]);
const backendUrl = import.meta.env.VITE_BACKEND_URL;
const router = useRouter();
const playerName = ref<string>(localStorage.getItem('playerName') || '');
const playerId = ref<number>(Number(localStorage.getItem('playerId')) || 0);
const eventSource = ref<EventSource | null>(null);

function setupEventSource(): void {
  eventSource.value = new EventSource(`${backendUrl}/lobbies/events`);

  eventSource.value.onmessage = (event: MessageEvent) => {
    const data = JSON.parse(event.data);

    switch (data.type) {
      case 'new_lobby':
        fetchLobbies();
        break;
      case 'lobby_removed':
        fetchLobbies();
        break;
      case 'creator_changed':
        fetchLobbies();
        break;
      default:
        break;
    }
  };

  eventSource.value.onerror = (error: Event) => {
    console.error('EventSource error:', error);
    setTimeout(setupEventSource, 3000);
  };
}

// Fetch the list of lobbies from the server
async function fetchLobbies(): Promise<void> {
  try {
    const response = await axios.get<Lobby[]>(`${backendUrl}/lobbies`);
    lobbies.value = response.data;
  } catch (error: any) {
    console.error('ERROR IN FETCH:', error);

    if (error.response) {
      console.error('Response status:', error.response.status);
      console.error('Response data:', error.response.data);
    }
  }
}

async function deleteLobby(code: string): Promise<void> {
  try {
    await axios.delete(`${backendUrl}/lobbies/${code}`);
    await fetchLobbies();
  } catch (error: any) {
    console.error(`Error deleting lobby with code ${code}:`, error);

    if (error.response) {
      console.error('Response status:', error.response.status);
      console.error('Response data:', error.response.data);
    }

  }
}

async function createLobby(): Promise<void> {
  try {
    const response = await axios.post<Lobby>(
      `${backendUrl}/lobbies/creatorId/${localStorage.getItem('playerId')}/`
    );
    const lobby = response.data;
    router.push(`/lobby/${lobby.code}`);
  } catch (error: any) {
    console.error('Error creating lobby:', error);
  }
}

async function joinLobby(code: string): Promise<void> {
  try {
    await axios.post(`${backendUrl}/lobbies/${code}/players/${localStorage.getItem('playerId')}`);
    router.push(`/lobby/${code}`);
  } catch (error: any) {
    if (error.response && error.response.status === 409) {
      console.error('Player with the same name is already in the lobby');
    } else {
      console.error('Error adding player to lobby:', error);
    }
  }
}

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return `${String(date.getDate()).padStart(2, '0')}.${String(date.getMonth() + 1).padStart(2, '0')}.${date.getFullYear()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}


onMounted(async () => {
  await fetchLobbies();
  setupEventSource();
});

onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close();
  }
});

</script>

<template>
  <div
    class="bg-gradient-to-br from-gray-800 via-gray-900 to-gray-800 min-h-screen flex flex-col items-center justify-center text-white px-4 py-10"
  >
    <div class="max-w-xl w-full text-center mb-10">
      <p class="text-l text-gray-300 mb-1">
        👋 Welcome
      </p>
      <h1 class="text-4xl font-black text-white mb-6">
        {{ playerName }}
      </h1>

      <button
        class="retro-button w-full max-w-xs bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white font-semibold py-3 rounded-lg transition-all duration-300 ease-in-out"
        @click="createLobby"
      >
        Create Lobby
      </button>

      <p
        v-if="lobbies.length === 0"
        class="text-gray-400 text-base mt-6"
      >
        No lobbies available. Create a new one!
      </p>
    </div>

    <div class="w-full max-w-xl">
      <ul class="space-y-2">
        <li
          v-for="lobby in lobbies"
          :key="lobby.code"
          class="bg-gray-700 hover:bg-gray-600 transition-colors rounded-lg shadow-md px-5 py-4 flex justify-between items-center"
        >
          <div class="text-left text-sm">
            <p class="text-white font-semibold">
              <span class="text-blue-400 font-mono text-xl">{{ lobby.code }}</span>
            </p>
            <p class="text-white-400 mt-1">
              Creator: <span>{{ lobby.name }} </span>
            </p>
            <p class="text-white-400 text-xs mt-1">
              Created at: {{ formatDate(lobby.created_at) }}
            </p>
          </div>

          <div class="flex gap-2">
            <button
              class="bg-blue-600 hover:bg-blue-500 text-white font-bold text-base py-3 px-5 rounded-lg shadow-lg transition-all duration-300 transform hover:scale-105 border-2 border-blue-500"
              @click="joinLobby(lobby.code)"
            >
              🎮 &nbsp; Join Game
            </button>
            <button
              v-if="lobby.creator_id === playerId"
              class="bg-red-600 hover:bg-red-700 text-white font-semibold text-sm py-2 px-3 rounded-lg transition-all duration-300"
              @click="deleteLobby(lobby.code)"
            >
              🗑️ Delete
            </button>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
