import {Outlet} from 'react-router-dom';
import {useQuery} from '@tanstack/react-query';
import {workspaceList, workspaceInfo} from '@/client';
import type {WorkspaceInfoResponse} from '@/client';
import {WorkspaceSidebar} from '@/components/layout/workspace-sidebar';
import {Spinner} from '@/components/ui/spinner';

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

    const first = data?.workspaces?.[0];
    const slug = first?.slug;

    const {data: workspaceInfoData, isLoading: infoLoading} = useQuery({
        queryKey: ['workspaceInfo', slug],
        queryFn: async (): Promise<WorkspaceInfoResponse> => {
            if (!slug) throw new Error('no slug');
            const resp = await workspaceInfo({path: {slug}});
            return resp.data!.data!;
        },
        enabled: !!slug,
    });

    if (isLoading || infoLoading) {
        return (
            <div className="flex h-screen w-full items-center justify-center bg-background">
                <Spinner/>
            </div>
        );
    }

    if (!workspaceInfoData) {
        return (
            <div className="flex h-screen w-full items-center justify-center bg-background">
                <div className="text-muted-foreground">Loading workspace...</div>
            </div>
        );
    }

    return (
        <div className="flex h-screen w-full bg-background">
            <WorkspaceSidebar workspace={workspaceInfoData}/>
            <main className="flex-1 overflow-y-auto">
                <Outlet/>
            </main>
        </div>
    );
}
