import Header from './header';
import NewNoteModal from '@components/modals/new-note-modal';
import Onboarding, {useOnboardingStatus} from './onboarding';
import React, {useRef, useState} from 'react';
import Sidebar from './sidebar';
import {Navigate, ScrollRestoration} from '@tryghost/admin-x-framework';
import {useAppBasePath} from '@src/hooks/use-app-base-path';
import {useCurrentPage} from '@src/hooks/use-current-page';
import {useCurrentUser} from '@tryghost/admin-x-framework/api/current-user';
import {useKeyboardShortcuts} from '@hooks/use-keyboard-shortcuts';
import {useTopicsForUser} from '@src/hooks/use-activity-pub-queries';

const Layout: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({children, ...props}) => {
    const {isOnboarded} = useOnboardingStatus();
    const basePath = useAppBasePath();
    const {data: currentUser, isLoading} = useCurrentUser();
    const containerRef = useRef<HTMLDivElement>(null);
    const [isMobileSidebarOpen, setIsMobileSidebarOpen] = useState(false);
    const currentPage = useCurrentPage();
    const {topicsQuery} = useTopicsForUser();
    const {data: topicsData} = topicsQuery;
    const hasTopics = topicsData && topicsData.topics.length > 0;

    const {isNewNoteModalOpen, setIsNewNoteModalOpen} = useKeyboardShortcuts();

    const toggleMobileSidebar = () => {
        setIsMobileSidebarOpen(!isMobileSidebarOpen);
    };

    const closeMobileSidebar = () => {
        setIsMobileSidebarOpen(false);
    };

    if (isLoading || !currentUser) {
        return null;
    }

    if (!isOnboarded) {
        return <Navigate to={`${basePath}/welcome`} replace />;
    }

    return (
        <div ref={containerRef} className={`h-screen w-full ${isOnboarded && 'overflow-y-auto'}`} data-scrollable-container>
            <ScrollRestoration containerRef={containerRef} />
            <div className='relative mx-auto flex max-w-page flex-col' {...props}>
                {isOnboarded ?
                    <>
                        <div className='block grid-cols-[auto_320px] items-start lg:grid'>
                            <div className='z-0 min-w-0'>
                                <Header
                                    showBorder={!(currentPage === 'reader' && hasTopics) && !(currentPage === 'explore')}
                                    onToggleMobileSidebar={toggleMobileSidebar}
                                />
                                <div className='px-[min(4vw,32px)]'>
                                    {children}
                                </div>
                            </div>
                            <Sidebar
                                isMobileSidebarOpen={isMobileSidebarOpen}
                                onCloseMobileSidebar={closeMobileSidebar}
                            />
                        </div>
                        {/* Mobile sidebar backdrop */}
                        {isMobileSidebarOpen && (
                            <div
                                className="fixed inset-0 z-40 lg:hidden"
                                onClick={closeMobileSidebar}
                            />
                        )}
                    </> :
                    <Onboarding />
                }
            </div>

            <NewNoteModal
                open={isNewNoteModalOpen}
                onOpenChange={setIsNewNoteModalOpen}
            />
        </div>
    );
};

export default Layout;
