"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";

interface UserData {
  username: string;
  avatar: string | null;
  hp: number;
  maxHp: number;
  xp: number;
  maxXp: number;
  level: 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,
};

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

  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) {
            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,
            });
          }
        })
        .catch(() => {
          // Utiliser les données de session si l'API échoue
          setUserData({
            username: session.user.username || "Guest",
            avatar: null,
            hp: 1000,
            maxHp: 1000,
            xp: 0,
            maxXp: 5000,
            level: 1,
          });
        });
    } else {
      setUserData(defaultUserData);
    }
  }, [session, initialUserData]);

  const { username, avatar, hp, maxHp, xp, maxXp, level } = userData;
  
  // Calculer les pourcentages cibles
  const targetHpPercentage = (hp / maxHp) * 100;
  const targetXpPercentage = (xp / maxXp) * 100;
  
  // Initialiser les pourcentages à 0 si on a des données initiales (pour l'animation)
  // Sinon utiliser directement les valeurs calculées
  const [hpPercentage, setHpPercentage] = useState(
    initialUserData ? 0 : targetHpPercentage
  );
  const [xpPercentage, setXpPercentage] = useState(
    initialUserData ? 0 : targetXpPercentage
  );

  useEffect(() => {
    // Si on a des données initiales, animer depuis 0 vers la valeur cible
    if (initialUserData) {
      const hpTimer = setTimeout(() => {
        setHpPercentage(targetHpPercentage);
      }, 100);

      const xpTimer = setTimeout(() => {
        setXpPercentage(targetXpPercentage);
      }, 200);

      return () => {
        clearTimeout(hpTimer);
        clearTimeout(xpTimer);
      };
    } else {
      // Sinon, mettre à jour directement (pour les pages Client Components)
      setHpPercentage(targetHpPercentage);
      setXpPercentage(targetXpPercentage);
    }
  }, [targetHpPercentage, targetXpPercentage, initialUserData]);

  const hpColor =
    hpPercentage > 60
      ? "from-green-600 to-green-700"
      : hpPercentage > 30
      ? "from-yellow-600 to-orange-700"
      : "from-red-700 to-red-900";

  return (
    <div className="flex items-center gap-3">
      {/* Avatar */}
      <div className="w-10 h-10 rounded-full border border-pixel-gold/20 overflow-hidden bg-gray-900 flex items-center justify-center">
        {avatar ? (
          <img
            src={avatar}
            alt={username}
            className="w-full h-full object-cover"
          />
        ) : (
          <span className="text-pixel-gold text-xs font-bold">
            {username.charAt(0).toUpperCase()}
          </span>
        )}
      </div>

      {/* Stats */}
      <div className="flex flex-col gap-1.5 min-w-[200px]">
        {/* Username & Level */}
        <div className="flex items-center gap-2">
          <div className="text-pixel-gold font-gaming font-bold text-sm tracking-wider">
            {username}
          </div>
          <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>
        
        {/* Bars side by side */}
        <div className="flex flex-col gap-1">
          <div className="flex items-center gap-2">
            {/* HP Bar */}
            <div className="relative h-2 flex-1 bg-gray-900 border border-gray-700 rounded overflow-hidden">
              <div
                className={`absolute inset-0 bg-gradient-to-r ${hpColor} transition-all duration-1000 ease-out`}
                style={{ width: `${hpPercentage}%` }}
              >
                <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent animate-shimmer"></div>
              </div>
              {hpPercentage < 30 && (
                <div className="absolute inset-0 border border-red-500 rounded animate-pulse"></div>
              )}
            </div>

            {/* XP Bar */}
            <div className="relative h-2 flex-1 bg-gray-900 border border-pixel-gold/30 rounded overflow-hidden">
              <div
                className="absolute inset-0 bg-gradient-to-r from-pixel-gold/80 via-pixel-gold/70 to-pixel-gold/80 transition-all duration-1000 ease-out"
                style={{ width: `${xpPercentage}%` }}
              >
                <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent animate-shimmer"></div>
              </div>
            </div>
          </div>
          {/* Labels */}
          <div className="flex items-center gap-2 text-[8px] font-pixel text-gray-400">
            <div className="flex-1 text-left">
              HP {hp} / {maxHp}
            </div>
            <div className="flex-1 text-right">
              XP {formatNumber(xp)} / {formatNumber(maxXp)}
            </div>
          </div>
        </div>
      </div>

      <style jsx>{`
        @keyframes shimmer {
          0% {
            transform: translateX(-100%);
          }
          100% {
            transform: translateX(100%);
          }
        }
        .animate-shimmer {
          animation: shimmer 2s infinite;
        }
      `}</style>
    </div>
  );
}

