import {Navigate, Outlet, useParams} from 'react-router-dom';
import {WorkspaceProvider, useWorkspace} from '@/contexts';
import {WorkspaceSidebar} from '@/components/layout/workspace-sidebar';

export function WorkspaceLayout() {
    const {workspace_slug} = useParams<{workspace_slug: string}>();

    if (!workspace_slug) {
        return <Navigate to="/404" replace/>;
    }

    return (
        <WorkspaceProvider workspaceSlug={workspace_slug}>
            <WorkspaceLayoutInner/>
        </WorkspaceProvider>
    );
}

function WorkspaceLayoutInner() {
    const {currentWorkspace, isLoading} = useWorkspace();

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

    if (!currentWorkspace) {
        return (
            <div className="flex h-screen w-full items-center justify-center bg-background">
                <div className="text-muted-foreground">Workspace not found or access denied.</div>
            </div>
        );
    }

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