'use client';

import { useRouter } from 'next/navigation';
import { useAuthContext } from '@/providers/AuthProvider';
import { useProjects } from '@/hooks/useProjects';
import Dashboard from '@/components/Dashboard';
import { Loader2, BookOpen } from 'lucide-react';
import { useEffect } from 'react';

export default function DashboardPage() {
    const router = useRouter();
    const { user, logout, loading } = useAuthContext();
    const { projects, setCurrentProjectId, createProject } = useProjects(user);

    useEffect(() => {
        if (!loading && !user) {
            router.replace('/login');
        }
    }, [user, loading, router]);

    if (loading || !user) {
        return (
            <div className="h-screen w-full flex flex-col items-center justify-center bg-slate-900 text-white">
                <Loader2 className="animate-spin text-blue-500 mb-4" size={48} />
                <div className="flex items-center gap-2">
                    <BookOpen className="text-blue-500" size={20} />
                    <span className="text-lg font-bold">PlumeIA</span>
                </div>
            </div>
        );
    }

    return (
        <Dashboard
            user={user}
            projects={projects}
            onSelect={(id) => {
                setCurrentProjectId(id);
                router.push(`/project/${id}`);
            }}
            onCreate={async () => {
                const id = await createProject();
                if (id) {
                    setCurrentProjectId(id);
                    router.push(`/project/${id}`);
                }
            }}
            onLogout={() => {
                logout();
                router.push('/');
            }}
            onPricing={() => router.push('/pricing')}
            onProfile={() => router.push('/profile')}
        />
    );
}
