"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import DarkThemeLayout from "../components/DarkThemeLayout";
import Navbar from "../components/Navbar";
import PointsDisplay from "../components/PointsDisplay";
import TransactionHistory from "../components/TransactionHistory";
import BadgeCard from "../components/BadgeCard";

interface User {
  id: string;
  username: string;
  email: string;
  points: number;
  createdAt: string;
}

interface Badge {
  id: string;
  name: string;
  description: string;
  icon: string;
  earnedDate?: string;
  progress?: number;
  requirement?: number;
}

export default function ProfilePage() {
  const router = useRouter();
  const [user, setUser] = useState<User | null>(null);
  const [badges, setBadges] = useState<Badge[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (!token) {
      router.push("/login");
      return;
    }

    fetchData();
  }, [router]);

  const fetchData = async () => {
    try {
      const token = localStorage.getItem("token");
      const headers = { Authorization: `Bearer ${token}` };

      const [userRes, badgesRes] = await Promise.all([
        fetch("/api/users/me", { headers }),
        fetch("/api/users/me/badges", { headers })
      ]);

      if (!userRes.ok || !badgesRes.ok) {
        throw new Error("Failed to fetch data");
      }

      const userData = await userRes.json();
      const badgesData = await badgesRes.json();

      if (userData.success && userData.data) {
        setUser({
          id: userData.data.id,
          username: userData.data.name,
          email: userData.data.email,
          points: userData.data.pointsBalance || 0,
          createdAt: userData.data.createdAt,
        });
      }
      if (badgesData.success && badgesData.data) {
        setBadges(badgesData.data.badges || []);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
      localStorage.removeItem("token");
      router.push("/login");
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <DarkThemeLayout>
        <div className="flex items-center justify-center min-h-screen">
          <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-yellow-500"></div>
        </div>
      </DarkThemeLayout>
    );
  }

  if (!user) {
    return null;
  }

  const joinedDate = new Date(user.createdAt).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric"
  });

  const earnedBadges = badges.filter(b => b.earnedDate);
  const inProgressBadges = badges.filter(b => !b.earnedDate);

  return (
    <>
      <Navbar user={user} />
      <DarkThemeLayout>
        <div className="space-y-8">
          <div>
            <h1 className="text-4xl font-bold text-white mb-2">Profile</h1>
            <p className="text-gray-400 text-lg">Manage your account and view your achievements</p>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-1 space-y-6">
              <div className="bg-gray-800 border border-gray-700 rounded-xl p-8">
                <div className="text-center">
                  <div className="w-24 h-24 mx-auto rounded-full bg-gradient-to-br from-yellow-400 to-orange-500 flex items-center justify-center text-white text-4xl font-bold mb-4 shadow-xl shadow-yellow-500/50">
                    {user.username[0].toUpperCase()}
                  </div>
                  <h2 className="text-2xl font-bold text-white mb-1">{user.username}</h2>
                  <p className="text-gray-400 text-sm mb-6">{user.email}</p>

                  <div className="space-y-3">
                    <div className="flex items-center justify-between py-3 px-4 bg-gray-700 rounded-lg">
                      <span className="text-gray-300 text-sm">Joined</span>
                      <span className="text-white font-medium">{joinedDate}</span>
                    </div>
                    <div className="flex items-center justify-between py-3 px-4 bg-gray-700 rounded-lg">
                      <span className="text-gray-300 text-sm">User ID</span>
                      <span className="text-white font-mono text-xs">{user.id.slice(0, 8)}...</span>
                    </div>
                  </div>
                </div>
              </div>

              <PointsDisplay points={user.points} size="medium" />
            </div>

            <div className="lg:col-span-2 space-y-6">
              <div>
                <h2 className="text-2xl font-bold text-white mb-4">Transaction History</h2>
                <TransactionHistory />
              </div>

              <div>
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-2xl font-bold text-white">
                    Badges Earned ({earnedBadges.length})
                  </h2>
                </div>
                {earnedBadges.length === 0 ? (
                  <div className="bg-gray-800 border border-gray-700 rounded-xl p-12 text-center">
                    <svg className="w-16 h-16 mx-auto text-gray-600 mb-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                    <p className="text-gray-400">No badges earned yet</p>
                    <p className="text-gray-500 text-sm mt-2">Complete tasks to earn your first badge!</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {earnedBadges.map(badge => (
                      <BadgeCard key={badge.id} badge={badge} earned={true} />
                    ))}
                  </div>
                )}
              </div>

              {inProgressBadges.length > 0 && (
                <div>
                  <h2 className="text-2xl font-bold text-white mb-4">
                    Badges In Progress ({inProgressBadges.length})
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {inProgressBadges.map(badge => (
                      <BadgeCard key={badge.id} badge={badge} earned={false} />
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </DarkThemeLayout>
    </>
  );
}
