import React, { useCallback, useEffect, useMemo } from 'react';
import type { ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppShell } from '../appShellContext';
import {
  DocumentsFilterProvider,
} from '../documents/context/DocumentsFilterContext';
import type { DocumentsFilterValue } from '../documents/context/DocumentsFilterContext';
import { useWorkspaceSurface } from './useWorkspaceSurface';
import { DocumentsHeaderBreadcrumb } from '../documents/panel/DocumentsPanelHeader';
import { SidebarProvider, useSidebarContext } from '../sidebar/SidebarContext';
import { PanelManagerProvider, usePanelManager } from './PanelManagerContext';
import Sidebar from '../sidebar/Sidebar';

type Identifier = string | number;

type EnsureAssetUrl = (
  docId: Identifier,
  asset: unknown,
  options?: Record<string, unknown>,
) => Promise<unknown> | void;

type EnsurePreviewData = (docId: Identifier, options?: Record<string, unknown>) => Promise<unknown>;
type GetDocumentAsset = (document: unknown, assetType: string) => unknown;
type ResolveApiPath = (path: string) => string;
type NotifyApiError = (error: unknown, fallbackMessage?: string) => void;

interface DocumentsTableProps {
  breadcrumbs?: DocumentsHeaderBreadcrumb[] | null;
  onBreadcrumbNavigate?: (crumb: DocumentsHeaderBreadcrumb) => void;
  [key: string]: unknown;
}

interface DocumentsRouteAppShell {
  sidebarProps?: Record<string, unknown> | null;
  documentsTableProps?: DocumentsTableProps | null;
  detailPanelProps?: Record<string, unknown> | null;
  detailPanelOpen?: boolean;
  openTagsModal?: () => void;
  openCorrespondentsModal?: () => void;
  previewWorkspaceDocument?: unknown;
  documentLink?: unknown;
  previewDocumentId?: Identifier | null;
  closeDocumentPreview?: () => void;
  ensurePreviewData?: EnsurePreviewData;
  resolveApiPath?: ResolveApiPath;
  ensureAssetUrl?: EnsureAssetUrl;
  getDocumentAsset?: GetDocumentAsset;
  notifyApiError?: NotifyApiError;
  documentsFilter: DocumentsFilterValue;
}

const DocumentsRouteContent: React.FC = () => {
  const {
    sidebarProps,
    documentsTableProps,
    detailPanelProps,
    detailPanelOpen,
    openTagsModal,
    openCorrespondentsModal,
    previewWorkspaceDocument,
    documentLink,
    previewDocumentId,
    closeDocumentPreview,
    ensurePreviewData,
    resolveApiPath,
    ensureAssetUrl,
    getDocumentAsset,
    notifyApiError,
    documentsFilter,
  } = useAppShell() as unknown as DocumentsRouteAppShell;
  const navigate = useNavigate();
  const { collapsed: sidebarCollapsed } = useSidebarContext();
  const {
    sidebarSuppressed,
    expandSidebar,
  } = usePanelManager();

  const safeSidebarProps = useMemo<Record<string, unknown>>(
    () => (sidebarProps && Object(sidebarProps) === sidebarProps ? sidebarProps : {}),
    [sidebarProps],
  );

  const sidebarPropsWithActions = useMemo(
    () => ({
      ...safeSidebarProps,
      onManageTags: openTagsModal,
      onManageCorrespondents: openCorrespondentsModal,
    }),
    [safeSidebarProps, openTagsModal, openCorrespondentsModal],
  );

  const sidebarHidden = sidebarCollapsed || sidebarSuppressed;

  const handleHeaderBreadcrumbClick = useCallback((crumb: DocumentsHeaderBreadcrumb) => {
    if (!crumb || !crumb.id) {
      return;
    }
    const target = crumb.id === 'root' ? '/documents' : `/documents/folder/${crumb.id}`;
    navigate(target);
  }, [navigate]);

  const documentsTablePropsWithNav = useMemo(() => (
    documentsTableProps
      ? { ...documentsTableProps, onBreadcrumbNavigate: handleHeaderBreadcrumbClick }
      : null
  ), [documentsTableProps, handleHeaderBreadcrumbClick]);

  const { surface } = useWorkspaceSurface({
    sidebarHidden,
    onExpandSidebar: expandSidebar,
    documentsTableProps: documentsTablePropsWithNav,
    detailPanelProps,
    detailPanelOpen,
    previewWorkspaceDocument,
    documentLink,
    previewDocumentId,
    ensureAssetUrl,
    ensurePreviewData,
    getDocumentAsset,
    resolveApiPath,
    notifyApiError,
    closeDocumentPreview,
  });

  useEffect(() => {
    document.body.classList.add('has-main-content');
    return () => {
      document.body.classList.remove('has-main-content');
    };
  }, []);

  const renderSurface = () => {
    const layoutClass = `documents-main${sidebarHidden ? ' documents-main--sidebar-hidden' : ''}`;
    const sidebarNode = !sidebarHidden ? <Sidebar {...sidebarPropsWithActions} /> : null;
    const surfaceDetail = surface && (surface as { detail?: ReactNode }).detail ? (surface as { detail?: ReactNode }).detail : null;
    const surfaceBody = surface ? surface.content : null;

    return (
      <main className={layoutClass}>
        {sidebarNode}
        <div className="main-content">
          {surfaceBody}
        </div>
        {surfaceDetail}
      </main>
    );
  };

  const content = renderSurface();
  return (
    <DocumentsFilterProvider value={documentsFilter}>
      {content}
    </DocumentsFilterProvider>
  );
};

const DocumentsRoute: React.FC = () => (
  <SidebarProvider>
    <PanelManagerProvider>
      <DocumentsRouteContent />
    </PanelManagerProvider>
  </SidebarProvider>
);

export default DocumentsRoute;
