import React, { useCallback, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppShell } from '../appShellContext';
import DocumentsLayout from './DocumentsLayout';
import { useWorkspaceSurface } from './useWorkspaceSurface';
import PanelHeader from '../ui/PanelHeader';
import BreadcrumbTrail from '../ui/BreadcrumbTrail';

const DocumentsRoute = () => {
  const {
    sidebarProps,
    documentsTableProps,
    detailPanelProps,
    detailPanelOpen,
    documentsViewMode,
    deskWorkspaceProps,
    openTagsModal,
    openCorrespondentsModal,
    previewWorkspaceDocument,
    previewWorkspaceEntry,
    previewDocumentId,
    closeDocumentPreview,
    handleThumbnailRegeneration,
    ensurePreviewData,
    resolveApiPath,
    ensureAssetUrl,
    getDocumentAsset,
    notifyApiError,
  } = useAppShell();
  const navigate = useNavigate();

  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const collapseSidebar = useCallback(() => setSidebarCollapsed(true), []);
  const expandSidebar = useCallback(() => setSidebarCollapsed(false), []);

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

  const breadcrumbs = documentsTableProps?.breadcrumbs || null;
  const parentBreadcrumb = useMemo(() => {
    if (!Array.isArray(breadcrumbs) || breadcrumbs.length <= 1) {
      return null;
    }
    return breadcrumbs[breadcrumbs.length - 2];
  }, [breadcrumbs]);

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

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

  const { surface } = useWorkspaceSurface({
    sidebarCollapsed,
    onExpandSidebar: expandSidebar,
    documentsTableProps,
    detailPanelProps,
    detailPanelOpen,
    viewMode: documentsViewMode,
    deskWorkspaceProps,
    previewWorkspaceDocument,
    previewWorkspaceEntry,
    previewDocumentId,
    ensureAssetUrl,
    ensurePreviewData,
    getDocumentAsset,
    resolveApiPath,
    notifyApiError,
    handleThumbnailRegeneration,
    closeDocumentPreview,
    parentBreadcrumb,
    onNavigateParent: handleNavigateParent,
  });

  if (!surface) {
    return (
      <DocumentsLayout
        sidebarProps={sidebarPropsWithActions}
        sidebarCollapsed={sidebarCollapsed}
      >
        <div className="main-content main-content--documents">
          <div className="main-content__body main-content__body--documents" />
        </div>
      </DocumentsLayout>
    );
  }

  const variant = surface.variant || 'documents';

  const mainContentClass = `main-content main-content--${variant}${
    surface.detail ? ' main-content--has-detail' : ''
  }`;
  const bodyClass = `main-content__body main-content__body--${variant}${
    surface.detail ? ' main-content__body--has-detail' : ''
  }`;

  const header = surface.header || null;

  let headerTitle = null;
  if (header) {
    const breadcrumbEntries = Array.isArray(header.breadcrumbs) ? header.breadcrumbs.filter(Boolean) : [];
    const lastIndex = breadcrumbEntries.length - 1;
    const trailEntries = breadcrumbEntries.length
      ? breadcrumbEntries.map((crumb, index) => ({
          id: crumb.id ?? index,
          label: crumb.name ?? crumb.label ?? crumb.title ?? '',
          onClick: index < lastIndex ? () => handleHeaderBreadcrumbClick(crumb) : null,
        }))
      : [{ id: 'current-location', label: header.title }];

    headerTitle = (
      <h2 className="main-content__title">
        <BreadcrumbTrail
          entries={trailEntries}
          className="main-content__breadcrumbs"
          separator="/"
        />
        {header.subtitle ? (
          <span className="main-content__subtitle">{header.subtitle}</span>
        ) : null}
      </h2>
    );
  }

  return (
    <DocumentsLayout
      sidebarProps={sidebarPropsWithActions}
      sidebarCollapsed={sidebarCollapsed}
    >
      <div className={mainContentClass}>
        {header ? (
          <PanelHeader
            className="main-content__header"
            leading={header.leading}
            title={headerTitle}
            titleTag="h2"
            actions={header.actions}
          />
        ) : null}
        <div className={bodyClass}>{surface.content}</div>
        {surface.detail || null}
      </div>
    </DocumentsLayout>
  );
};

export default DocumentsRoute;
