"use client";

import React from "react";
import { AutoRegisteringComponentRenderer } from "../../AutoRegisteringComponentRenderer";
import { V2DateDefinition } from "./index";
import { V2Date } from "@/components/v2/V2Date";
import { isColumnRequiredByMeta } from "../../DynamicComponentRenderer";
import { getFormatRules } from "@/lib/formatting";

/**
 * V2Date 렌더러
 * 자동 등록 시스템을 사용하여 컴포넌트를 레지스트리에 등록
 */
export class V2DateRenderer extends AutoRegisteringComponentRenderer {
  static componentDefinition = V2DateDefinition;

  render(): React.ReactElement {
    const { component, formData, onFormDataChange, isDesignMode, isSelected, isInteractive, ...restProps } = this.props;

    // 컴포넌트 설정 추출
    const config = component.componentConfig || component.config || {};
    const columnName = component.columnName;
    const tableName = component.tableName || this.props.tableName;

    // formData에서 현재 값 가져오기
    const currentValue = formData?.[columnName] ?? component.value ?? "";

    // 값 변경 핸들러
    const handleChange = (value: any) => {
      if (isInteractive && onFormDataChange && columnName) {
        onFormDataChange(columnName, value);
      }
    };

    // 라벨: style.labelText 우선, 없으면 component.label 사용
    // style.labelDisplay가 false면 라벨 숨김
    const style = component.style || {};
    const effectiveLabel = style.labelDisplay === false ? undefined : style.labelText || component.label;

    return (
      <V2Date
        id={component.id}
        value={currentValue}
        onChange={handleChange}
        config={{
          dateType: config.dateType || config.webType || "date",
          format: config.format || getFormatRules().date.display,
          placeholder: config.placeholder || style.placeholder || "날짜 선택",
          showTime: config.showTime || false,
          use24Hours: config.use24Hours ?? true,
          minDate: config.minDate,
          maxDate: config.maxDate,
        }}
        style={component.style}
        size={component.size}
        {...restProps}
        label={effectiveLabel}
        required={component.required || isColumnRequiredByMeta(tableName, columnName)}
        readonly={config.readonly || component.readonly}
        disabled={config.disabled || component.disabled}
      />
    );
  }
}

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

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