import React, { ReactNode } from 'react';
import SelectionFloatingActions from '../documents/SelectionFloatingActions';
import { createDocumentsTableHeaderActions } from '../documents/DocumentsPanel';
import createWorkspaceSurfaceConfig from '../documents/workspaceHeader';
import DocumentViewerPanel from '../preview/DocumentViewerPanel';
import DesktopWorkspace from './DesktopWorkspace';

type WorkspaceProps = Record<string, any>;

interface Breadcrumb {
  id?: string | number;
  name?: string;
  label?: string;
  title?: string;
}

interface DetailProps extends Record<string, any> {
  onClose?: () => void;
  onOpenPreview?: () => void;
  tags?: unknown;
}

interface CreateDesktopSurfaceArgs {
  workspaceProps?: WorkspaceProps | null;
  renderSidebarToggle?: () => ReactNode;
  parentBreadcrumb?: Breadcrumb | null;
  onNavigateParent?: () => void;
  detailProps?: DetailProps | null;
  detailOpen?: boolean;
}

const createDesktopSurface = ({
  workspaceProps,
  renderSidebarToggle,
  parentBreadcrumb,
  onNavigateParent,
  detailProps = null,
  detailOpen = false,
}: CreateDesktopSurfaceArgs) => {
  if (!workspaceProps) {
    return null;
  }

  const {
    currentFolderName,
    searchResults,
    onRefresh,
    viewMode,
    onViewModeChange,
    selectedDocumentIds,
    selectedFolderIds,
    onDeleteSelection,
    onClearSelection,
    tags,
    correspondents,
    documentLookup,
    tagLookupById,
    onBulkTagAdd,
    onBulkTagRemove,
    onBulkCorrespondentAdd,
    onBulkCorrespondentRemove,
    onBulkReanalyze,
    folderOptions,
    onMoveDocumentsToFolder,
    searchIncludeDescendants,
    onToggleSearchIncludeDescendants,
  } = workspaceProps;

  const title = Array.isArray(searchResults) ? 'Search results' : currentFolderName;
  const subtitle = Array.isArray(searchResults)
    ? `${searchResults.length} matching document${searchResults.length === 1 ? '' : 's'}`
    : null;

  const documentSelectionCount = Array.isArray(selectedDocumentIds) ? selectedDocumentIds.length : 0;
  const folderSelectionCount = Array.isArray(selectedFolderIds) ? selectedFolderIds.length : 0;
  const selectionCount = documentSelectionCount + folderSelectionCount;
  const actions = createDocumentsTableHeaderActions({
    viewMode: viewMode || 'desk',
    onViewModeChange,
    onRefresh,
    includeDescendants: searchIncludeDescendants,
    onToggleIncludeDescendants: onToggleSearchIncludeDescendants,
  });

  const floatingActions = selectionCount > 0
    ? (
        <SelectionFloatingActions
          selectionCount={selectionCount}
          selectedDocumentIds={selectedDocumentIds}
          selectedFolderIds={selectedFolderIds}
          documentLookup={documentLookup}
          tags={tags}
          tagLookupById={tagLookupById}
          correspondents={correspondents}
          onBulkTagAdd={onBulkTagAdd}
          onBulkTagRemove={onBulkTagRemove}
          onBulkCorrespondentAdd={onBulkCorrespondentAdd}
          onBulkCorrespondentRemove={onBulkCorrespondentRemove}
          onBulkReanalyze={onBulkReanalyze}
          onDeleteSelection={onDeleteSelection}
          onClearSelection={onClearSelection}
          folderOptions={folderOptions}
          onMoveDocumentsToFolder={onMoveDocumentsToFolder}
        />
      )
    : null;

  const sidebarToggle = renderSidebarToggle ? renderSidebarToggle() : null;
  const detail = detailOpen && detailProps
    ? (() => {
        const { onClose, onOpenPreview, tags: tagOptions, ...restDetailProps } = detailProps;
        return (
          <DocumentViewerPanel
            variant="sidebar"
            onCollapsePanel={onClose}
            onMaximizePanel={onOpenPreview}
            tagOptions={tagOptions}
            {...restDetailProps}
          />
        );
      })()
    : null;
  const surfaceConfig = createWorkspaceSurfaceConfig({
    key: 'workspace',
    variant: 'workspace',
    title,
    subtitle,
    sidebarToggle,
    parentBreadcrumb,
    onNavigateParent,
    actions,
    breadcrumbs: workspaceProps?.breadcrumbs || null,
    selectionLabel: null,
    floatingActions,
    content: (
      <DesktopWorkspace
        {...workspaceProps}
      />
    ),
    detail,
  });

  return {
    ...surfaceConfig,
    supportsDetail: Boolean(detailProps),
  };
};

export default createDesktopSurface;
