'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/context/AuthContext';
import { getProfile } from '@/lib/api';

// Define a type for our user object
interface User {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  role: string;
  createdAt: string;
}

export default function DashboardPage() {
  const { token, logout } = useAuth();
  // Apply the User type to our state, allowing it to be User or null
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!token) {
      // No need to call logout() here, as it will cause an infinite loop if the token is invalid.
      // The AuthProvider should handle the redirect.
      setLoading(false);
      return;
    }

    const fetchProfile = async () => {
      try {
        const profile = await getProfile(token);
        setUser(profile);
      } catch (error) {
        console.error("Failed to fetch profile:", error);
        logout(); // Logout if the token is invalid or expired
      } finally {
        setLoading(false);
      }
    };

    fetchProfile();
  }, [token, logout]);

  if (loading) {
    return <div className="min-h-screen bg-slate-950 flex items-center justify-center text-white">Loading...</div>;
  }

  if (!user) {
    // This can happen if the token is invalid or the fetch fails.
    // The user will be redirected by the logout() call in the catch block.
    return <div className="min-h-screen bg-slate-950 flex items-center justify-center text-white">Redirecting to login...</div>;
  }

  return (
    <div className="min-h-screen bg-slate-950 text-white p-8">
      <h1 className="text-3xl font-bold mb-4">Welcome, {user.firstName}!</h1>
      <p>This is your dashboard.</p>
      <button onClick={logout} className="mt-4 bg-blue-600 text-white font-bold rounded-xl px-4 py-2 hover:bg-blue-500 transition-all">
        Logout
      </button>
    </div>
  );
}
