import { useMemo } from 'react';
import { useAppShell } from '../lib/context/AppShellContext';
import type { DocumentsFilterValue } from '../documents/context/DocumentsFilterContext';
import type { UseWorkspaceSurfaceArgs } from './useWorkspaceSurface';
import type { Identifier } from '../types/identifiers';

import useDocumentsPanelProps from '../documents/logic/useDocumentsPanelProps';

type WorkspaceSurfaceConfig = Omit<UseWorkspaceSurfaceArgs, 'sidebarHidden' | 'onExpandSidebar'> & {
  openDetailPanel?: (documentId: Identifier) => void;
  closeDetailPanel?: () => void;
  handleBreadcrumbNavigate?: (crumb: any) => void;
};

interface DocumentsShellView {
  surfaceConfig: WorkspaceSurfaceConfig;
  documentsFilter: DocumentsFilterValue;
  documentsManager: any;
  foldersManager: any;
}

const useDocumentsShell = (): DocumentsShellView => {
  const shell = useAppShell();
  const documentsPanelProps = useDocumentsPanelProps(shell as any);

  return useMemo(() => {
    const surfaceConfig: WorkspaceSurfaceConfig = {
      documentsTableProps: documentsPanelProps,
      detailPanelProps: (shell.detailPanelProps ?? null) as WorkspaceSurfaceConfig['detailPanelProps'],
      detailPanelOpen: Boolean(shell.detailPanelOpen),
      openDetailPanel: shell.openDetailPanel as WorkspaceSurfaceConfig['openDetailPanel'],
      closeDetailPanel: shell.closeDetailPanel as WorkspaceSurfaceConfig['closeDetailPanel'],
      previewWorkspaceDocument: shell.previewWorkspaceDocument,
      previewDocumentId: (shell.previewDocumentId as Identifier) ?? null,
      closeDocumentPreview: shell.closeDocumentPreview as WorkspaceSurfaceConfig['closeDocumentPreview'],
      ensurePreviewData: shell.ensurePreviewData as WorkspaceSurfaceConfig['ensurePreviewData'],
      ensureAssetUrl: shell.ensureAssetUrl as WorkspaceSurfaceConfig['ensureAssetUrl'],
      getDocumentAsset: shell.getDocumentAsset as WorkspaceSurfaceConfig['getDocumentAsset'],
      notifyApiError: shell.notifyApiError as WorkspaceSurfaceConfig['notifyApiError'],
      handleBreadcrumbNavigate: shell.handleBreadcrumbNavigate as WorkspaceSurfaceConfig['handleBreadcrumbNavigate'],
    };

    return {
      surfaceConfig,
      documentsFilter: shell.documentsFilter as DocumentsFilterValue,
      documentsManager: shell.documentsManager,
      foldersManager: shell.foldersManager,
    };
  }, [shell, documentsPanelProps]);
};

export default useDocumentsShell;
