import { useMemo } from 'react';
import type { ComponentProps } from 'react';
import { useAppShell } from '../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'>;

interface DocumentsShellView {
  sidebarProps: ComponentProps<typeof Sidebar> | null;
  surfaceConfig: WorkspaceSurfaceConfig;
  documentsFilter: DocumentsFilterValue;
}

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),
      previewWorkspaceDocument: shell.previewWorkspaceDocument,
      documentLink: shell.documentLink,
      previewDocumentId: (shell.previewDocumentId as Identifier | null | undefined) ?? 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'],
    };

    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,
    };
  }, [shell]);
};

export default useDocumentsShell;
