import { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { isBrowser } from "react-device-detect";
import LoadingDisplay from "../components/LoadingDisplay";
import SessionExpiredPopup from "../components/SessionExpiredPopup";
import { NavBar } from "../components/NavBar";
import { useAuth } from "../contexts/AuthContext";
import Heatmap from "../components/Heatmap";
import type { HeatmapData } from "../components/Heatmap";
import type { User } from "../utils/authApi";

interface ScoreCountByGame {
  gameInternalName: string;
  formattedName: string;
  count: number;
}

interface RecentPlayedGame {
  gameInternalName: string;
  formattedName: string;
  timestamp: number;
}

interface UserData {
  user: User;
  recentPlayedGames: RecentPlayedGame[];
  scoreCountByGame: ScoreCountByGame[];
  isAdmin: boolean;
}

const Profile = () => {
  const { user, isLoading, logout } = useAuth();
  let targetUser =
    new URLSearchParams(window.location.search).get("userId") || ""; // looking at profile of this user
  const navigate = useNavigate();
  const [fetchingHeatmapData, setFetchingHeatmapData] = useState(true);
  const [fetchingUserData, setFetchingUserData] = useState(true);
  const [heatmapData, setHeatmapData] = useState<HeatmapData>({ data: [] });
  const [userData, setUserData] = useState<UserData | null>(null);

  useEffect(() => {
    if (targetUser) {
      setFetchingUserData(true);
      const fetchUserData = async () => {
        try {
          const response = await fetch(
            new URL(
              import.meta.env.VITE_API_URL + "/me?userId=" + targetUser,
            ),
            { credentials: "include" },
          );
          const data = await response.json();
          setUserData(data);
          setFetchingUserData(false);
        } catch (error) {
          console.error("Failed to fetch user data:", error);
        }
      };
      fetchUserData();
    }
  }, [targetUser]);

  useEffect(() => {
    if (targetUser) {
      setFetchingHeatmapData(true);
      const fetchHeatmapData = async () => {
        try {
          const response = await fetch(
            new URL(
              import.meta.env.VITE_API_URL + "/heatmap?userId=" + targetUser,
            ),
            { credentials: "include" },
          );
          const data = await response.json();
          return data;
        } catch (error) {
          setFetchingHeatmapData(false);
          console.error("Failed to fetch heatmap data:", error);
          throw error;
        }
      };
      fetchHeatmapData().then((data) => {
        const heatmapDates: { [key: string]: number } = {};
        for (let i = 0; i < data.scores.length; i++) {
          const date = new Date(data.scores[i].timestamp);
          const dateString = date.toDateString();
          if (!heatmapDates[dateString]) {
            heatmapDates[dateString] = 1;
          } else {
            heatmapDates[dateString] += 1;
          }
        }
        setHeatmapData({
          data: Object.entries(heatmapDates).map(([date, count]) => ({
            date,
            count,
          })),
        });
        setFetchingHeatmapData(false);
      });
    }
  }, [targetUser]);

  if (!user) {
    return <SessionExpiredPopup />;
  }

  if (!targetUser) {
    targetUser = user.id.toString();
  }


  if (isLoading || fetchingHeatmapData || fetchingUserData) {
    return <LoadingDisplay message="Loading Profile Page..." />;
  }

  const handleLogout = async () => {
    try {
      await logout();
      navigate("/");
    } catch (error) {
      console.error("Logout failed:", error);
      alert("Network error during logout. Please try again.");
    }
  };

  if (!user) {
    return <SessionExpiredPopup />;
  }

  return (
    <div className="min-h-screen bg-slate-950">
      <NavBar user={user} handleLogout={handleLogout} currentPage="profile" />

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
        {/* Header */}
        <div className="mb-6 sm:mb-8">
          <h1 className="text-2xl sm:text-3xl font-bold text-white mb-2">
            {user.username}
          </h1>
          <p className="text-sm sm:text-base text-slate-400">
            {userData?.user?.bio ? userData.user.bio.replace(/</g, '&lt;').replace(/>/g, '&gt;') : "I'm a fairly non-descript person"}
          </p>
        </div>
        {isBrowser ? (
          <div className="flex flex-col items-center justify-center">
            <Heatmap data={heatmapData.data} />
          </div>
        ) : null}
        <div className="mb-6 sm:mb-8">
          <h2 className="text-xl sm:text-2xl font-bold text-white mb-4">Recently Played Games</h2>
          <ul className="list-disc list-inside space-y-2 text-white">
            {userData?.recentPlayedGames.map((game, index) => (
              <li key={index} className="flex items-center justify-between p-2 bg-slate-800 rounded-lg border border-slate-700">
               <span className="font-bold hover:underline"><a href={`/score?game=${game.gameInternalName}&userId=${userData.user.id}`}>{game.formattedName}</a> </span>
                <span className="text-sm text-slate-400">{new Date(game.timestamp).toLocaleString()}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="mb-6 sm:mb-8">
          <h2 className="text-xl sm:text-2xl font-bold text-white mb-4">Total Scores</h2>
          <table className="table-auto w-full text-white border-collapse border border-slate-700">
            <thead>
              <tr>
                <th className="border border-slate-700 px-4 py-2">Game</th>
                <th className="border border-slate-700 px-4 py-2">Total Scores Uploaded</th>
              </tr>
            </thead>
            <tbody>
              {userData?.scoreCountByGame
                .sort((a, b) => b.count - a.count)
                .map((score, index) => (
                  <tr key={index}>
                    <td className="border border-slate-700 px-4 py-2">{score.formattedName}</td>
                    <td className="border border-slate-700 px-4 py-2">{score.count}</td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
    </div>
    </div>
  );
};

export default Profile;
