"use client";

import { useEffect, useState, useCallback } from "react";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { Avatar } from "@/components/ui";

interface UserData {
  username: string;
  avatar: string | null;
  hp: number;
  maxHp: number;
  xp: number;
  maxXp: number;
  level: number;
  score: number;
}

interface PlayerStatsProps {
  initialUserData?: UserData | null;
}

// Format number with consistent locale to avoid hydration mismatch
const formatNumber = (num: number): string => {
  return num.toLocaleString("en-US");
};

const defaultUserData: UserData = {
  username: "Guest",
  avatar: null,
  hp: 1000,
  maxHp: 1000,
  xp: 0,
  maxXp: 5000,
  level: 1,
  score: 0,
};

export default function PlayerStats({ initialUserData }: PlayerStatsProps) {
  const { data: session } = useSession();
  const [userData, setUserData] = useState<UserData>(
    initialUserData || defaultUserData
  );

  const refreshUserData = useCallback(async () => {
    if (!session?.user?.id) return;

    try {
      const res = await fetch(`/api/users/${session.user.id}`);
      const data = await res.json();
      if (data) {
        requestAnimationFrame(() => {
          setUserData({
            username: data.username || "Guest",
            avatar: data.avatar,
            hp: data.hp || 1000,
            maxHp: data.maxHp || 1000,
            xp: data.xp || 0,
            maxXp: data.maxXp || 5000,
            level: data.level || 1,
            score: data.score || 0,
          });
        });
      }
    } catch (error) {
      console.error("Error refreshing user data:", error);
    }
  }, [session]);

  useEffect(() => {
    // Si on a déjà des données initiales, ne rien faire (déjà initialisé dans useState)
    if (initialUserData) {
      return;
    }

    // Sinon, fallback sur le fetch côté client (pour les pages Client Components)
    if (session?.user?.id) {
      fetch(`/api/users/${session.user.id}`)
        .then((res) => res.json())
        .then((data) => {
          if (data) {
            // Utiliser requestAnimationFrame pour éviter les cascades de rendu
            requestAnimationFrame(() => {
              setUserData({
                username: data.username || "Guest",
                avatar: data.avatar,
                hp: data.hp || 1000,
                maxHp: data.maxHp || 1000,
                xp: data.xp || 0,
                maxXp: data.maxXp || 5000,
                level: data.level || 1,
                score: data.score || 0,
              });
            });
          }
        })
        .catch(() => {
          // Utiliser les données de session si l'API échoue
          requestAnimationFrame(() => {
            setUserData({
              username: session.user.username || "Guest",
              avatar: null,
              hp: 1000,
              maxHp: 1000,
              xp: 0,
              maxXp: 5000,
              level: 1,
              score: 0,
            });
          });
        });
    } else if (!initialUserData) {
      // Utiliser requestAnimationFrame pour éviter les cascades de rendu
      requestAnimationFrame(() => {
        setUserData(defaultUserData);
      });
    }
  }, [session, initialUserData]);

  // Écouter les événements de refresh du score
  useEffect(() => {
    const handleRefreshScore = () => {
      refreshUserData();
    };

    window.addEventListener("refreshUserScore", handleRefreshScore);
    return () => {
      window.removeEventListener("refreshUserScore", handleRefreshScore);
    };
  }, [refreshUserData]);

  const { username, avatar, level, score } = userData;

  return (
    <div className="flex items-center gap-3">
      {/* Avatar */}
      <Link
        href="/profile"
        className="cursor-pointer hover:opacity-80 transition-opacity"
      >
        <Avatar
          src={avatar}
          username={username}
          size="md"
          borderClassName="border-pixel-gold/20"
        />
      </Link>

      {/* Stats */}
      <div className="flex flex-col gap-1.5 min-w-[140px] sm:min-w-[160px]">
        {/* Username & Level */}
        <div className="flex items-center gap-2">
          <Link
            href="/profile"
            className="cursor-pointer hover:text-pixel-gold/80 transition-colors"
          >
            <div className="text-pixel-gold font-gaming font-bold text-sm tracking-wider">
              {username}
            </div>
          </Link>
          <div className="text-gray-400 font-pixel text-xs uppercase border border-pixel-gold/30 px-1.5 py-0.5 bg-black/40">
            Lv.{level}
          </div>
        </div>

        {/* Score Display */}
        <div className="flex items-center gap-2">
          <div className="text-gray-400 font-pixel text-xs uppercase">
            Score
          </div>
          <div className="text-pixel-gold font-gaming font-bold text-sm">
            {formatNumber(score)}
          </div>
        </div>
      </div>
    </div>
  );
}
