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

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

interface DocumentsShellView {
  sidebarProps: ComponentProps<typeof Sidebar> | null;
  surfaceConfig: WorkspaceSurfaceConfig;
  documentsFilter: DocumentsFilterValue;
  documentsManager: any;
  foldersManager: any; // Using any to avoid circular dependency
}

const useDocumentsShell = (): DocumentsShellView => {
  const shell = useAppShell();

  return useMemo(() => {
    const sidebar = (shell.sidebarProps as ComponentProps<typeof Sidebar> | undefined) || null;
    const surfaceConfig: WorkspaceSurfaceConfig = {
      documentsTableProps: (shell.documentsTableProps ?? null) as WorkspaceSurfaceConfig['documentsTableProps'],
      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'],
    };

    const sidebarWithActions = sidebar
      ? {
        ...sidebar,
        onManageTags: shell.openTagsModal as (() => void) | undefined,
        onManageCorrespondents: shell.openCorrespondentsModal as (() => void) | undefined,
      }
      : null;

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

export default useDocumentsShell;
