/**
 * Gen UI 组件注册表
 * 白名单机制，只有注册的组件才能被渲染
 */

import { Separator } from '@/components/ui/separator';
import type { ComponentType, ComponentRegistry, RenderContext } from './types';
import {
  StatsRow,
  DataTable,
  GenChart,
  AlertBox,
  ActionButtons,
  ApprovalCard,
  InsightCard,
  ProgressBar,
  TextBlock,
  AgentStatus,
  AgentCapabilities,
  AgentThinking,
  AgentSettingsCard,
  AgentSettingsList,
  SandboxResultCard,
  InsightFeed,
  ApprovalList,
} from './components';

// 分隔线组件
function Divider({ props }: { props: { margin?: 'sm' | 'md' | 'lg' }; context: RenderContext }) {
  const marginClass = {
    sm: 'my-2',
    md: 'my-4',
    lg: 'my-6',
  };
  return <Separator className={marginClass[props.margin || 'md']} />;
}

// Sandbox 结果包装组件
function SandboxResult({ props, context }: { 
  props: { result: any; showRerun?: boolean; showCancel?: boolean }; 
  context: RenderContext 
}) {
  const handleRerun = props.showRerun ? () => {
    context.onAction?.('sandbox.rerun', { executionId: props.result.executionId });
  } : undefined;

  const handleCancel = props.showCancel ? () => {
    context.onAction?.('sandbox.cancel', { executionId: props.result.executionId });
  } : undefined;

  return (
    <SandboxResultCard 
      result={props.result} 
      onRerun={handleRerun}
      onCancel={handleCancel}
    />
  );
}

// 组件注册表 - 白名单
export const componentRegistry: ComponentRegistry = {
  stats_row: StatsRow,
  data_table: DataTable,
  chart: GenChart,
  alert: AlertBox,
  action_buttons: ActionButtons,
  approval_card: ApprovalCard,
  insight_card: InsightCard,
  progress_bar: ProgressBar,
  text: TextBlock,
  divider: Divider,
  // Agent 相关组件
  agent_status: AgentStatus,
  agent_capabilities: AgentCapabilities,
  agent_thinking: AgentThinking,
  agent_settings_card: AgentSettingsCard,
  agent_settings_list: AgentSettingsList,
  // Sandbox 相关组件
  sandbox_result: SandboxResult,
  // 动态列表组件
  insight_feed: InsightFeed,
  approval_list: ApprovalList,
  // container 在 DynamicRenderer 中特殊处理
};

// 检查组件是否注册
export function isComponentRegistered(type: ComponentType): boolean {
  return type in componentRegistry || type === 'container';
}

// 获取注册的组件
export function getRegisteredComponent(type: ComponentType) {
  return componentRegistry[type];
}

// 获取所有支持的组件类型
export function getSupportedComponentTypes(): ComponentType[] {
  return [...Object.keys(componentRegistry), 'container'] as ComponentType[];
}
