"use client";

/**
 * UnifiedComponentRenderer
 * 
 * Unified 컴포넌트를 동적으로 렌더링하는 컴포넌트
 * props.unifiedType에 따라 적절한 컴포넌트를 렌더링
 */

import React, { forwardRef, useMemo } from "react";
import { 
  UnifiedComponentProps,
  isUnifiedInput,
  isUnifiedSelect,
  isUnifiedDate,
  isUnifiedText,
  isUnifiedMedia,
  isUnifiedList,
  isUnifiedLayout,
  isUnifiedGroup,
  isUnifiedBiz,
  isUnifiedHierarchy,
} from "@/types/unified-components";
import { UnifiedInput } from "./UnifiedInput";
import { UnifiedSelect } from "./UnifiedSelect";
import { UnifiedDate } from "./UnifiedDate";
import { UnifiedList } from "./UnifiedList";
import { UnifiedLayout } from "./UnifiedLayout";
import { UnifiedGroup } from "./UnifiedGroup";
import { UnifiedMedia } from "./UnifiedMedia";
import { UnifiedBiz } from "./UnifiedBiz";
import { UnifiedHierarchy } from "./UnifiedHierarchy";

interface UnifiedComponentRendererProps {
  props: UnifiedComponentProps;
  className?: string;
}

/**
 * Unified 컴포넌트 렌더러
 */
export const UnifiedComponentRenderer = forwardRef<HTMLDivElement, UnifiedComponentRendererProps>(
  ({ props, className }, ref) => {
    const component = useMemo(() => {
      // 타입 가드를 사용하여 적절한 컴포넌트 렌더링
      if (isUnifiedInput(props)) {
        return <UnifiedInput {...props} />;
      }

      if (isUnifiedSelect(props)) {
        return <UnifiedSelect {...props} />;
      }

      if (isUnifiedDate(props)) {
        return <UnifiedDate {...props} />;
      }

      if (isUnifiedText(props)) {
        // UnifiedText는 UnifiedInput의 textarea 모드로 대체
        // 필요시 별도 구현
        return (
          <div className="p-2 border rounded text-sm text-muted-foreground">
            UnifiedText (UnifiedInput textarea 모드 사용 권장)
          </div>
        );
      }

      if (isUnifiedMedia(props)) {
        return <UnifiedMedia {...props} />;
      }

      if (isUnifiedList(props)) {
        return <UnifiedList {...props} />;
      }

      if (isUnifiedLayout(props)) {
        return <UnifiedLayout {...props} />;
      }

      if (isUnifiedGroup(props)) {
        return <UnifiedGroup {...props} />;
      }

      if (isUnifiedBiz(props)) {
        return <UnifiedBiz {...props} />;
      }

      if (isUnifiedHierarchy(props)) {
        return <UnifiedHierarchy {...props} />;
      }

      // 알 수 없는 타입
      return (
        <div className="p-2 border border-destructive rounded text-sm text-destructive">
          알 수 없는 컴포넌트 타입: {(props as { unifiedType?: string }).unifiedType}
        </div>
      );
    }, [props]);

    return (
      <div ref={ref} className={className}>
        {component}
      </div>
    );
  }
);

UnifiedComponentRenderer.displayName = "UnifiedComponentRenderer";

export default UnifiedComponentRenderer;

