import {useEffect} from 'react';
import {useNavigate} from 'react-router-dom';
import {useQuery} from '@tanstack/react-query';
import {workspaceList} from '@/client';
import {Spinner} from '@/components/ui/spinner';

export function WorkspaceRedirect() {
    const navigate = useNavigate();

    const {data, isLoading} = useQuery({
        queryKey: ['workspaceList'],
        queryFn: async () => {
            const resp = await workspaceList();
            return resp.data?.data;
        },
    });

    useEffect(() => {
        if (isLoading) return;
        const first = data?.workspaces?.[0];
        if (first?.slug) {
            navigate(`/w/${first.slug}`, {replace: true});
        } else {
            navigate('/init/workspace', {replace: true});
        }
    }, [isLoading, data, navigate]);

    return (
        <div className="flex items-center justify-center h-screen">
            <Spinner/>
        </div>
    );
}
