"use client";

/**
 * UnifiedRepeater 렌더러
 * 컴포넌트 레지스트리에 등록하기 위한 래퍼
 */

import React from "react";
import { ComponentRegistry } from "../../ComponentRegistry";
import { UnifiedRepeater } from "@/components/unified/UnifiedRepeater";
import { UnifiedRepeaterDefinition } from "./index";
import { UnifiedRepeaterConfig, DEFAULT_REPEATER_CONFIG } from "@/types/unified-repeater";

interface UnifiedRepeaterRendererProps {
  component: any;
  data?: any;
  mode?: "view" | "edit";
  isPreview?: boolean;
  onDataChange?: (data: any[]) => void;
  onRowClick?: (row: any) => void;
  onButtonClick?: (action: string, row?: any, buttonConfig?: any) => void;
  parentId?: string | number;
}

const UnifiedRepeaterRenderer: React.FC<UnifiedRepeaterRendererProps> = ({
  component,
  data,
  mode,
  isPreview,
  onDataChange,
  onRowClick,
  onButtonClick,
  parentId,
}) => {
  // component.componentConfig 또는 component.config에서 UnifiedRepeaterConfig 추출
  const config: UnifiedRepeaterConfig = React.useMemo(() => {
    // 🆕 componentConfig 우선 (DB에서 properties.componentConfig로 저장됨)
    const componentConfig = component?.componentConfig || component?.config || component?.props?.config || {};
    
    console.log("📋 UnifiedRepeaterRenderer config 추출:", {
      hasComponentConfig: !!component?.componentConfig,
      hasConfig: !!component?.config,
      useCustomTable: componentConfig.useCustomTable,
      mainTableName: componentConfig.mainTableName,
      foreignKeyColumn: componentConfig.foreignKeyColumn,
    });
    
    return {
      ...DEFAULT_REPEATER_CONFIG,
      ...componentConfig,
      dataSource: {
        ...DEFAULT_REPEATER_CONFIG.dataSource,
        ...componentConfig.dataSource,
      },
      columns: componentConfig.columns || [],
      features: {
        ...DEFAULT_REPEATER_CONFIG.features,
        ...componentConfig.features,
      },
      modal: {
        ...DEFAULT_REPEATER_CONFIG.modal,
        ...componentConfig.modal,
      },
      button: {
        ...DEFAULT_REPEATER_CONFIG.button,
        ...componentConfig.button,
      },
    };
  }, [component]);

  // parentId 결정: props에서 전달받거나 data에서 추출
  const resolvedParentId = React.useMemo(() => {
    if (parentId) return parentId;
    if (data && config.dataSource?.referenceKey) {
      return data[config.dataSource.referenceKey];
    }
    return undefined;
  }, [parentId, data, config.dataSource?.referenceKey]);

  // 미리보기 모드에서는 샘플 데이터 표시
  if (isPreview) {
    return (
      <div className="rounded-md border border-dashed p-4 text-center">
        <div className="text-muted-foreground text-sm">
          통합 반복 데이터
          <br />
          <span className="text-xs">
            모드: {config.renderMode} | 테이블: {config.dataSource?.tableName || "미설정"}
          </span>
        </div>
      </div>
    );
  }

  return (
    <UnifiedRepeater
      config={config}
      parentId={resolvedParentId}
      data={Array.isArray(data) ? data : undefined}
      onDataChange={onDataChange}
      onRowClick={onRowClick}
      onButtonClick={onButtonClick}
      className={component?.className}
    />
  );
};

// 컴포넌트 레지스트리에 등록
ComponentRegistry.registerComponent({
  ...UnifiedRepeaterDefinition,
  render: (props: any) => <UnifiedRepeaterRenderer {...props} />,
});

export default UnifiedRepeaterRenderer;

