import { useCallback } from 'react';
import { Edge } from '@xyflow/react';
import { ConfigPanel } from '../ConfigPanel';
import { AppSelectorPanel } from '../AppSelectorPanel';
import { DataFieldsModal } from '../DataFieldsModal';
import { VersionHistoryPanel, RestoreVersionDialog } from '../versioning';
import { WorkflowReactFlowNode, WorkflowNodeData } from '../../types/reactflow';
import { Version } from '../../types/workflow';
import { useAppSelector, useDataFieldsModal, useVersionHistory } from '../../stores';

export interface FlowSidebarProps {
  /** ID of the currently selected node */
  selectedNodeId: string | null;
  /** All workflow nodes */
  nodes: WorkflowReactFlowNode[];
  /** All workflow edges */
  edges: Edge[];
  /** Close the config panel */
  onCloseConfig: () => void;
  /** Update node data (takes snapshot for undo internally) */
  onUpdateNode: (updatedNodeData: Partial<WorkflowNodeData>) => void;
  /** Request node deletion */
  onDeleteNode: (nodeId: string) => void;
  /** Handle app selected from sidebar */
  onAppSelected: (item: { id: string; name: string; icon: string; integration?: string }) => void;
  /** Handle closing the app selector */
  onCloseAppSelector: () => void;
  /** Workflow ID (for version history) */
  workflowId?: string;
  /** Request to restore a version */
  onRestoreRequest: (version: Version) => void;
  /** Handle making a version live */
  onMakeLive: (version: Version) => void;
  /** Version to restore (for confirmation dialog) */
  versionToRestore: Version | null;
  /** Close the restore dialog */
  onCloseRestoreDialog: () => void;
  /** Confirm version restore */
  onRestoreConfirm: () => void;
  /** Whether a restore operation is in progress */
  isRestoring: boolean;
}

/**
 * FlowSidebar manages all sidebar panels for the FlowBuilder.
 *
 * Renders the ConfigPanel, AppSelectorPanel, DataFieldsModal,
 * VersionHistoryPanel, and RestoreVersionDialog based on current state.
 * Reads app selector, data fields modal, and version history state
 * directly from stores.
 */
export function FlowSidebar({
  selectedNodeId,
  nodes,
  edges,
  onCloseConfig,
  onUpdateNode,
  onDeleteNode,
  onAppSelected,
  onCloseAppSelector,
  workflowId,
  onRestoreRequest,
  onMakeLive,
  versionToRestore,
  onCloseRestoreDialog,
  onRestoreConfirm,
  isRestoring,
}: FlowSidebarProps) {
  const { showAppSelector, appSelectorType } = useAppSelector();
  const { dataFieldsModal, closeDataFieldsModal } = useDataFieldsModal();
  const { isHistoryPanelOpen, closeHistoryPanel } = useVersionHistory();

  const selectedNode = nodes.find((n) => n.id === selectedNodeId);

  const handleConfigUpdate = useCallback(
    (updatedNode: {
      name: string;
      icon: string;
      status: string;
      errorCount?: number;
      config?: Record<string, unknown>;
      label?: string;
    }) => {
      onUpdateNode({
        name: updatedNode.name,
        icon: updatedNode.icon,
        status: updatedNode.status as WorkflowNodeData['status'],
        errorCount: updatedNode.errorCount,
        config: updatedNode.config,
        label: updatedNode.label,
      });
    },
    [onUpdateNode],
  );

  return (
    <>
      {/* Config Panel (inline in the main flex layout) */}
      {selectedNode && selectedNode.data.status !== 'placeholder' && (
        <ConfigPanel
          node={{
            id: selectedNode.id,
            type: selectedNode.type as 'trigger' | 'action',
            name: selectedNode.data.name,
            icon: selectedNode.data.icon,
            x: selectedNode.position.x,
            y: selectedNode.position.y,
            status: selectedNode.data.status,
            errorCount: selectedNode.data.errorCount,
            config: selectedNode.data.config,
            label: selectedNode.data.label,
            actionType: selectedNode.data.actionType,
          }}
          nodes={nodes}
          edges={edges}
          onClose={onCloseConfig}
          onUpdate={handleConfigUpdate}
          onDelete={onDeleteNode}
        />
      )}

      {/* App Selector Panel (overlaid) */}
      {showAppSelector && (
        <AppSelectorPanel
          type={appSelectorType}
          onSelect={onAppSelected}
          onClose={onCloseAppSelector}
        />
      )}

      {/* Data Fields Modal */}
      <DataFieldsModal
        nodeType={dataFieldsModal?.nodeType || 'trigger'}
        typeIdentifier={dataFieldsModal?.typeIdentifier || null}
        open={!!dataFieldsModal}
        onOpenChange={(open) => !open && closeDataFieldsModal()}
      />

      {/* Version History Panel */}
      {workflowId && (
        <VersionHistoryPanel
          workflowId={parseInt(workflowId)}
          isOpen={isHistoryPanelOpen}
          onClose={closeHistoryPanel}
          onRestore={onRestoreRequest}
          onMakeLive={onMakeLive}
        />
      )}

      {/* Restore Version Dialog */}
      <RestoreVersionDialog
        version={versionToRestore}
        isOpen={!!versionToRestore}
        onClose={onCloseRestoreDialog}
        onConfirm={onRestoreConfirm}
        isRestoring={isRestoring}
      />
    </>
  );
}
