"use client";

import BackgroundWrapper from "@/components/BackgroundWrapper";
import Header from "@/components/Header";
import { API_URL, getToken } from "@/lib/auth";
import React, { useEffect, useState } from "react";

const page = () => {
  const [boardError, setBoardError] = useState<string | null>(null);
  const [boardData, setBoardData] = useState([]);
  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true);

  async function fetchBoardData() {
    try {
      const boardResponse = await fetch(`${API_URL}/leaderboard`, {
        method: "GET",
      });

      if (!boardResponse.ok) {
        throw new Error("Failed to fetch leaderboard data");
      }

      const fetchedBoardData = await boardResponse.json();
      if (Array.isArray(fetchedBoardData) && fetchedBoardData.length > 0) {
        setBoardData(fetchedBoardData);
      } else {
        setBoardError("No leaderboard data available.");
        setBoardData([]);
      }
    } catch (error) {
      console.error(error);
      setBoardError("Something went wrong. Please try again.");
      setBoardData([]);
    }
  }

  useEffect(() => {
    async function fetchUser() {
      try {
        const token = await getToken();
        if (!token) throw new Error("User is not authenticated");

        const response = await fetch(`${API_URL}/me`, {
          method: "get",
          headers: { Authorization: `Bearer ${token}` },
        });

        if (!response.ok) throw new Error("Failed to fetch user data");

        const fetchedUserData = await response.json();
        setLoading(false);
        setUserData(fetchedUserData);
      } catch (error) {
        console.error(error);
        setUserData(null);
      }
    }

    fetchUser();
    fetchBoardData();
  }, []);

  const getTopThree = (boardData) => {
    if (!boardData || !Array.isArray(boardData)) return [];
    const sortedData = boardData
      .filter((player) => player?.points !== undefined) // Ensure `points` exists
      .sort((a, b) => b.points - a.points);

    const topThree = sortedData.slice(0, 3).map((player, index) => ({
      ...player,
      rank: index + 1,
      height: index === 0 ? 280 : index === 1 ? 250 : 220,
    }));

    return [topThree[1], topThree[0], topThree[2]].filter(Boolean); // Handle missing players
  };

  const getLeaderboard = (boardData) => {
    return boardData.slice().sort((a, b) => b.points - a.points);
  };

  const getUserData = (boardData, name) => {
    if (!boardData || !Array.isArray(boardData)) return [];
    const sortedData = boardData
      .filter((player) => player?.name && player?.points !== undefined)
      .sort((a, b) => b.points - a.points);

    const result = sortedData.find((player) => player.name === name);
    return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
  };

  return (
    <BackgroundWrapper>
      <section>
        <Header displaySubject={"Leaderboard"} displayTabTitle={null} />
      </section>
    </BackgroundWrapper>
  );
};

export default page;
