"use client";

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

interface User {
  username: string;
  points: number;
}

export default function TasksPage() {
  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({
          username: data.data.name,
          points: data.data.pointsBalance || 0,
        });
      }
    } catch (error) {
      console.error("Error fetching user 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;
  }

  return (
    <>
      <Navbar user={user} />
      <DarkThemeLayout>
        <div className="space-y-8">
          <div>
            <h1 className="text-4xl font-bold text-white mb-2">Available Tasks</h1>
            <p className="text-gray-400 text-lg">
              Complete tasks to earn points and climb the leaderboard
            </p>
          </div>

          <TaskList />
        </div>
      </DarkThemeLayout>
    </>
  );
}
