"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 DailyCheckinButton from "./components/DailyCheckinButton";
import TaskList from "./components/TaskList";
import BadgeCard from "./components/BadgeCard";

interface User {
  id: string;
  username: string;
  email: string;
  points: number;
  rank: number;
  badgeCount: number;
  streak: number;
  hasCheckedInToday: boolean;
}

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

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

    fetchUserData();
  }, [router]);

  const fetchUserData = async () => {
    try {
      const token = localStorage.getItem("token");
      const response = await fetch("/api/users/me", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      if (!response.ok) {
        throw new Error("Failed to fetch user data");
      }
      const data = await response.json();
      if (data.success && data.data) {
        setUser({
          id: data.data.id,
          username: data.data.name,
          email: data.data.email,
          points: data.data.pointsBalance || 0,
          rank: 0,
          badgeCount: data.data.badgesCount || 0,
          streak: 0,
          hasCheckedInToday: false,
        });
      } else {
        throw new Error("Invalid response");
      }
    } catch (error) {
      console.error("Error fetching user data:", error);
      localStorage.removeItem("token");
      router.push("/login");
    } finally {
      setLoading(false);
    }
  };

  const handleCheckin = async () => {
    try {
      const response = await fetch("/api/checkin", {
        method: "POST",
      });
      const data = await response.json();

      if (data.success) {
        setUser(prev => prev ? {
          ...prev,
          points: prev.points + data.points,
          streak: data.streak,
          hasCheckedInToday: true
        } : null);

        return data;
      }

      throw new Error("Check-in failed");
    } catch (error) {
      console.error("Check-in error:", error);
      return { success: false, points: 0, streak: 0 };
    }
  };

  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;
  }

  return (
    <>
      <Navbar user={user} />
      <DarkThemeLayout>
        <div className="space-y-8">
          <div className="text-center">
            <h1 className="text-4xl font-bold text-white mb-2">
              Welcome back, {user.username}!
            </h1>
            <p className="text-gray-400 text-lg">
              Ready to earn more points today?
            </p>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2 space-y-6">
              <div className="flex items-center justify-center">
                <PointsDisplay points={user.points} size="large" />
              </div>

              <DailyCheckinButton
                initialStreak={user.streak}
                hasCheckedInToday={user.hasCheckedInToday}
                onCheckin={handleCheckin}
              />

              <div>
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-2xl font-bold text-white">Available Tasks</h2>
                  <a
                    href="/tasks"
                    className="text-yellow-400 hover:text-yellow-300 font-medium transition"
                  >
                    View All →
                  </a>
                </div>
                <TaskList />
              </div>
            </div>

            <div className="space-y-6">
              <div className="bg-gray-800 border border-gray-700 rounded-xl p-6">
                <h3 className="text-xl font-bold text-white mb-4">Quick Stats</h3>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <svg className="w-5 h-5 text-yellow-400" 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>
                      <span className="text-gray-300">Global Rank</span>
                    </div>
                    <span className="text-2xl font-bold text-yellow-400">#{user.rank}</span>
                  </div>

                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <svg className="w-5 h-5 text-purple-400" 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>
                      <span className="text-gray-300">Badges Earned</span>
                    </div>
                    <span className="text-2xl font-bold text-purple-400">{user.badgeCount}</span>
                  </div>

                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <svg className="w-5 h-5 text-orange-400" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M12.395 2.553a1 1 0 00-1.45-.385c-.345.23-.614.558-.822.88-.214.33-.403.713-.57 1.116-.334.804-.614 1.768-.84 2.734a31.365 31.365 0 00-.613 3.58 2.64 2.64 0 01-.945-1.067c-.328-.68-.398-1.534-.398-2.654A1 1 0 005.05 6.05 6.981 6.981 0 003 11a7 7 0 1011.95-4.95c-.592-.591-.98-.985-1.348-1.467-.363-.476-.724-1.063-1.207-2.03zM12.12 15.12A3 3 0 017 13s.879.5 2.5.5c0-1 .5-4 1.25-4.5.5 1 .786 1.293 1.371 1.879A2.99 2.99 0 0113 13a2.99 2.99 0 01-.879 2.121z" clipRule="evenodd" />
                      </svg>
                      <span className="text-gray-300">Current Streak</span>
                    </div>
                    <span className="text-2xl font-bold text-orange-400">{user.streak} days</span>
                  </div>
                </div>

                <div className="mt-6 pt-6 border-t border-gray-700">
                  <a
                    href="/leaderboard"
                    className="w-full block text-center bg-gradient-to-r from-yellow-500 to-orange-500 text-white font-semibold py-3 rounded-lg hover:from-yellow-600 hover:to-orange-600 transition transform hover:scale-105"
                  >
                    View Leaderboard
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </DarkThemeLayout>
    </>
  );
}
