"use client";

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

import React from "react";
import { ComponentRegistry } from "../../ComponentRegistry";
import { V2Repeater } from "@/components/v2/V2Repeater";
import { V2RepeaterDefinition } from "./index";
import { V2RepeaterConfig, DEFAULT_REPEATER_CONFIG } from "@/types/v2-repeater";

interface V2RepeaterRendererProps {
  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;
  formData?: Record<string, any>;
  groupedData?: Record<string, any>[];
}

const V2RepeaterRenderer: React.FC<V2RepeaterRendererProps> = ({
  component,
  data,
  mode,
  isPreview,
  onDataChange,
  onRowClick,
  onButtonClick,
  parentId,
  formData,
  groupedData,
}) => {
  // component.componentConfig 또는 component.config에서 V2RepeaterConfig 추출
  const config: V2RepeaterConfig = React.useMemo(() => {
    // 🆕 componentConfig 우선 (DB에서 properties.componentConfig로 저장됨)
    const componentConfig = component?.componentConfig || component?.config || component?.props?.config || {};
    
    console.log("📋 V2RepeaterRenderer config 추출:", {
      hasComponentConfig: !!component?.componentConfig,
      hasConfig: !!component?.config,
      hasOverrides: !!(component as any)?.overrides,
      useCustomTable: componentConfig.useCustomTable,
      mainTableName: componentConfig.mainTableName,
      foreignKeyColumn: componentConfig.foreignKeyColumn,
      entityJoins: componentConfig.entityJoins,
    });
    
    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 (
    <V2Repeater
      config={config}
      componentId={component?.id}
      parentId={resolvedParentId}
      data={Array.isArray(data) ? data : undefined}
      onDataChange={onDataChange}
      onRowClick={onRowClick}
      onButtonClick={onButtonClick}
      className={component?.className}
      formData={formData}
      groupedData={groupedData}
    />
  );
};

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

export default V2RepeaterRenderer;

