"use client";

import React from "react";
import { AutoRegisteringComponentRenderer } from "../../AutoRegisteringComponentRenderer";
import { V2RackStructureDefinition } from "./index";
import { RackStructureComponent } from "./RackStructureComponent";
import { GeneratedLocation } from "./types";

/**
 * 렉 구조 설정 렌더러
 * 자동 등록 시스템을 사용하여 컴포넌트를 레지스트리에 등록
 */
export class RackStructureRenderer extends AutoRegisteringComponentRenderer {
  static componentDefinition = V2RackStructureDefinition;

  render(): React.ReactElement {
    const { formData, isPreview, config, tableName, onFormDataChange } = this.props as Record<string, unknown>;

    return (
      <RackStructureComponent
        config={(config as object) || {}}
        formData={formData as Record<string, unknown>}
        tableName={tableName as string}
        onChange={(locations) =>
          this.handleLocationsChange(
            locations,
            onFormDataChange as ((fieldName: string, value: unknown) => void) | undefined,
          )
        }
        isPreview={isPreview as boolean}
      />
    );
  }

  /**
   * 생성된 위치 데이터 변경 핸들러
   * formData에 _rackStructureLocations 키로 저장하여 저장 액션에서 감지
   */
  protected handleLocationsChange = (
    locations: GeneratedLocation[],
    onFormDataChange?: (fieldName: string, value: unknown) => void,
  ) => {
    // 생성된 위치 데이터를 컴포넌트에 저장
    this.updateComponent({ generatedLocations: locations });

    // formData에도 저장하여 저장 액션에서 감지할 수 있도록 함
    if (onFormDataChange) {
      onFormDataChange("_rackStructureLocations", locations);
    }
  };
}

// 자동 등록 실행
RackStructureRenderer.registerSelf();

// Hot Reload 지원 (개발 모드)
if (process.env.NODE_ENV === "development") {
  RackStructureRenderer.enableHotReload();
}
