import React, { useRef } from 'react';
import { useAppShell } from '../lib/context/AppShellContext';
import { usePanelResizeBindings } from '../app/PanelManagerContext';
import type { Identifier } from '../types/identifiers';
import SidebarFolderList from './components/SidebarFolderList';
import SidebarTagList from './components/SidebarTagList';
import SidebarCorrespondentList from './components/SidebarCorrespondentList';
import { FolderIdentifier } from './components/SidebarFolderNode';
import { TenantOption } from './components/SidebarMenu';
import SidebarHeader from './components/SidebarHeader';
import SidebarSearch from './components/SidebarSearch';

interface SidebarProps {
  onSelect: (folderId: FolderIdentifier) => void;
  onDrop: (event: React.DragEvent<HTMLDivElement>, folderId: FolderIdentifier) => void;
  onDragOver: (event: React.DragEvent<HTMLDivElement>, folderId: FolderIdentifier) => void;
  onDragLeave: (event: React.DragEvent<HTMLDivElement>) => void;
  onDeleteFolder: (folderId: FolderIdentifier) => void;
  onRenameFolder?: (folderId: FolderIdentifier, name: string) => void;
  selectedFolder?: FolderIdentifier | null;
  onFolderDragStart?: (event: React.DragEvent<HTMLDivElement>, folderId: FolderIdentifier) => void;
  onFolderDragEnd?: (event: React.DragEvent<HTMLDivElement>) => void;
  draggedFolderId?: FolderIdentifier | null;
  onCreateFolder?: (parentId?: Identifier | null) => void;
  creatingFolder?: boolean;
}

const Sidebar: React.FC<SidebarProps> = ({
  onSelect,
  onDrop,
  onDragOver,
  onDragLeave,
  onDeleteFolder,
  onRenameFolder,
  selectedFolder = null,
  onFolderDragStart,
  onFolderDragEnd,
  draggedFolderId = null,
  onCreateFolder,
  creatingFolder = false,
}) => {
  const {
    sidebarSuppressed,
    openTagsModal,
    openCorrespondentsModal,
    handleLogout,
    tags = [],
    correspondents = [],
    tenant,
    tenants,
    tenantOptions,
    handleTenantSelect,
    openSettings,
    handleFileSelection, // Used for upload
  } = useAppShell();

  const onManageTags = openTagsModal;
  const onManageCorrespondents = openCorrespondentsModal;

  // Derived or context-based handlers/values
  const tenantName = (tenant as TenantOption)?.name;
  const effectiveTenants = (tenants || tenantOptions || []);
  const activeTenantId = (tenant as TenantOption)?.id;

  const onUploadFiles = handleFileSelection;

  const sidebarRef = useRef<HTMLDivElement | null>(null);
  const {
    panelStyle: sidebarStyle,
    handleProps: sidebarHandleProps,
    isPanelResizing: isResizingSidebar,
  } = usePanelResizeBindings('sidebar', { panelRef: sidebarRef });

  const sidebarClassNames = ['sidebar'];
  if (isResizingSidebar) {
    sidebarClassNames.push('sidebar--resizing');
  }
  if (sidebarSuppressed) {
    sidebarClassNames.push('sidebar--suppressed');
  }

  return (
    <aside className={sidebarClassNames.join(' ')} ref={sidebarRef} style={sidebarStyle}>
      <button
        type="button"
        className={`resize-handle resize-handle--right${isResizingSidebar ? ' is-active' : ''}`}
        aria-label="Resize sidebar"
        {...sidebarHandleProps}
      >
        <span className="resize-handle__line" aria-hidden="true" />
      </button>

      <SidebarHeader
        tenantName={tenantName}
        tenants={effectiveTenants}
        activeTenantId={activeTenantId}
        onSelectTenant={handleTenantSelect}
        onOpenSettings={openSettings}
        onLogout={handleLogout}
        onUploadFiles={onUploadFiles}
        selectedFolder={selectedFolder}
      />

      <div className="panel-body sidebar__body">
        <SidebarSearch />

        <SidebarFolderList
          selectedFolder={selectedFolder}
          onSelect={onSelect}
          onDrop={onDrop}
          onDragOver={onDragOver}
          onDragLeave={onDragLeave}
          onDeleteFolder={onDeleteFolder}
          onRenameFolder={onRenameFolder}
          onFolderDragStart={onFolderDragStart}
          onFolderDragEnd={onFolderDragEnd}
          draggedFolderId={draggedFolderId}
          onCreateFolder={onCreateFolder}
          creatingFolder={creatingFolder}
        />

        <SidebarTagList
          tags={tags}
          untaggedFilterId={null}
          onManageTags={onManageTags}
        />

        <SidebarCorrespondentList
          correspondents={correspondents}
          onManageCorrespondents={onManageCorrespondents}
        />
      </div>
    </aside>
  );
};

export default Sidebar;
