import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { AppShellContext } from '../appShellContext';
import DropOverlay from './DropOverlay';
import UploadQueueOverlay from './UploadQueueOverlay';
import useDocumentsWorkspace from '../hooks/documents/useDocumentsWorkspace';
import { useDocumentsPreferences } from './useDocumentsPreferences';
import SettingsRoute from './SettingsRoute';

const AppLayout: React.FC = () => {
  const documentsPreferences = useDocumentsPreferences();
  const {
    appStatus,
    location,
    shellRef,
    dropOverlayState,
    managementModals,
    contextValue,
    settingsOpen,
    closeSettings,
  } = useDocumentsWorkspace({
    documentsViewMode: documentsPreferences.documentsViewMode,
    documentsSortField: documentsPreferences.documentsSortField,
    documentsSortDirection: documentsPreferences.documentsSortDirection,
    documentsSortFieldRef: documentsPreferences.documentsSortFieldRef,
    documentsSortDirectionRef: documentsPreferences.documentsSortDirectionRef,
    onDocumentsViewModeChange: documentsPreferences.handleDocumentsViewModeChange,
    onDocumentsSortFieldChange: documentsPreferences.handleDocumentsSortFieldChange,
    onDocumentsSortDirectionToggle: documentsPreferences.handleDocumentsSortDirectionToggle,
    searchIncludeDescendants: documentsPreferences.searchIncludeDescendants,
    onToggleSearchIncludeDescendants: documentsPreferences.toggleSearchIncludeDescendants,
    onSetSearchIncludeDescendants: documentsPreferences.setSearchIncludeDescendants,
    sortRefreshReadyRef: documentsPreferences.sortRefreshReadyRef,
    handleDeskExit: documentsPreferences.handleDeskExit,
  });

  if (['logged-out', 'authenticating', 'selecting-tenant'].includes(appStatus)) {
    const shouldRememberLastLocation = appStatus !== 'logged-out';
    return (
      <Navigate
        to="/account/login"
        replace
        state={
          shouldRememberLastLocation
            ? { from: location.pathname + location.search }
            : undefined
        }
      />
    );
  }

  return (
    <AppShellContext.Provider value={contextValue}>
      <div className="app-shell" ref={shellRef}>
        <DropOverlay
          active={dropOverlayState.active}
          folderName={dropOverlayState.folderName}
        />
        <UploadQueueOverlay
          queue={contextValue.uploadQueue || []}
          onClearQueue={contextValue.clearUploadQueue}
        />
        <Outlet />
        {managementModals}
        {settingsOpen ? (
          <SettingsRoute open onClose={closeSettings} />
        ) : null}
      </div>
    </AppShellContext.Provider>
  );
};

export default AppLayout;
