/**
 * Gen UI 动态渲染器
 * 根据 UI Schema 动态渲染组件树
 */

import { cn } from '@/lib/utils';
import type { UISchema, UIComponent, RenderContext, ComponentPropsMap } from './types';
import { getRegisteredComponent, isComponentRegistered } from './registry';

interface DynamicRendererProps {
  schema: UISchema;
  context: RenderContext;
  className?: string;
}

// 规范化组件属性 - 处理 AI 返回格式不一致的情况
function normalizeComponentProps(component: UIComponent): UIComponent {
  const { type, props = {}, id, ...rest } = component as UIComponent & Record<string, unknown>;
  
  // 如果有直接放在组件级别的属性（如 columns, rows, title 等），合并到 props 中
  const knownComponentKeys = ['type', 'props', 'id'];
  const extraProps: Record<string, unknown> = {};
  
  for (const key of Object.keys(rest)) {
    if (!knownComponentKeys.includes(key)) {
      extraProps[key] = rest[key];
    }
  }
  
  // 合并额外属性到 props
  if (Object.keys(extraProps).length > 0) {
    console.log(`[GenUI] Normalizing component "${type}": moving extra props to props object`, extraProps);
    return {
      type,
      id,
      props: { ...props, ...extraProps } as UIComponent['props']
    };
  }
  
  return component;
}

// 渲染单个组件
function renderComponent(component: UIComponent, context: RenderContext, index: number): React.ReactNode {
  // 先规范化组件属性
  const normalizedComponent = normalizeComponentProps(component);
  const { type, props, id } = normalizedComponent;
  const key = id || `component-${index}`;

  // 检查组件是否已注册
  if (!isComponentRegistered(type)) {
    console.warn(`[GenUI] Unknown component type: ${type}`);
    return (
      <div key={key} className="p-4 border border-dashed border-yellow-500 rounded bg-yellow-50 dark:bg-yellow-950">
        <p className="text-sm text-yellow-700 dark:text-yellow-300">
          未知组件类型: {type}
        </p>
      </div>
    );
  }

  // 特殊处理 container 类型
  if (type === 'container') {
    const containerProps = props as ComponentPropsMap['container'];
    const { layout = 'vertical', gap = 'md', columns = 2, children } = containerProps;

    const gapClass = { sm: 'gap-3', md: 'gap-5', lg: 'gap-7' };
    
    let layoutClass = '';
    let style: React.CSSProperties = {};

    switch (layout) {
      case 'horizontal':
        layoutClass = 'flex flex-row flex-wrap';
        break;
      case 'grid':
        layoutClass = 'grid';
        style = { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` };
        break;
      case 'vertical':
      default:
        layoutClass = 'flex flex-col';
    }

    return (
      <div key={key} className={cn(layoutClass, gapClass[gap])} style={style}>
        {children.map((child, childIndex) => renderComponent(child, context, childIndex))}
      </div>
    );
  }

  // 获取注册的组件
  const Component = getRegisteredComponent(type);
  if (!Component) {
    return null;
  }

  // 使用类型断言绕过复杂的联合类型检查
  const RenderedComponent = Component as React.ComponentType<{ props: any; context: RenderContext }>;
  return <RenderedComponent key={key} props={props} context={context} />;
}

// 主渲染器组件
export function DynamicRenderer({ schema, context, className }: DynamicRendererProps) {
  const { layout = 'vertical', gap = 'md', components } = schema;

  if (!components || components.length === 0) {
    return null;
  }

  const gapClass = { sm: 'gap-3', md: 'gap-5', lg: 'gap-7' };
  
  let layoutClass = '';
  switch (layout) {
    case 'horizontal':
      layoutClass = 'flex flex-row flex-wrap';
      break;
    case 'grid':
      layoutClass = 'grid grid-cols-2';
      break;
    case 'vertical':
    default:
      layoutClass = 'flex flex-col';
  }

  return (
    <div className={cn(layoutClass, gapClass[gap], className)}>
      {components.map((component, index) => renderComponent(component, context, index))}
    </div>
  );
}

// 导出辅助函数
export { renderComponent };
