"use client";

import React, { useEffect, useState } from "react";
import { ComponentRendererProps, AutoGenerationConfig } from "@/types/component";
import { NumberInputConfig } from "./types";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";
import { AutoGenerationUtils } from "@/lib/utils/autoGeneration";

export interface NumberInputComponentProps extends ComponentRendererProps {
  config?: NumberInputConfig;
  value?: any; // 외부에서 전달받는 값
}

/**
 * NumberInput 컴포넌트
 * number-input 컴포넌트입니다
 */
export const NumberInputComponent: React.FC<NumberInputComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  isInteractive = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  formData,
  onFormDataChange,
  value: externalValue, // 외부에서 전달받은 값
  ...props
}) => {
  // 컴포넌트 설정
  const componentConfig = {
    ...config,
    ...component.config,
  } as NumberInputConfig;

  // 스타일 계산 (위치는 RealtimePreviewDynamic에서 처리하므로 제외)
  const componentStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    ...component.style,
    ...style,
  };

  // 디자인 모드 스타일
  if (isDesignMode) {
    componentStyle.border = "1px dashed #cbd5e1";
    componentStyle.borderColor = isSelected ? "#3b82f6" : "#cbd5e1";
  }

  // 이벤트 핸들러
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onClick?.();
  };

  // DOM에 전달하면 안 되는 React-specific props 필터링
  const {
    selectedScreen,
    onZoneComponentDrop,
    onZoneClick,
    componentConfig: _componentConfig,
    component: _component,
    isSelected: _isSelected,
    onClick: _onClick,
    onDragStart: _onDragStart,
    onDragEnd: _onDragEnd,
    size: _size,
    position: _position,
    style: _style,
    screenId: _screenId,
    tableName: _tableName,
    onRefresh: _onRefresh,
    onClose: _onClose,
    ...domProps
  } = props;

  // DOM 안전한 props만 필터링
  const safeDomProps = filterDOMProps(domProps);

  return (
    <div style={componentStyle} className={className} {...safeDomProps}>
      {/* 라벨 렌더링 */}
      {component.label && component.style?.labelDisplay !== false && (
        <label
          style={{
            position: "absolute",
            top: "-25px",
            left: "0px",
            fontSize: component.style?.labelFontSize || "14px",
            color: component.style?.labelColor || "#374151",
            fontWeight: "500",
          }}
        >
          {component.label}
          {component.required && (
            <span
              style={{
                color: "#ef4444",
              }}
            >
              *
            </span>
          )}
        </label>
      )}

      <input
        type="number"
        value={
          // 1순위: 외부에서 전달받은 value (DynamicComponentRenderer에서 전달)
          externalValue !== undefined
            ? externalValue
            : // 2순위: 인터랙티브 모드에서 formData
              isInteractive && formData && component.columnName
              ? formData[component.columnName] || ""
              : // 3순위: 컴포넌트 자체 값
                component.value || ""
        }
        placeholder={componentConfig.placeholder || ""}
        disabled={componentConfig.disabled || false}
        required={componentConfig.required || false}
        readOnly={componentConfig.readonly || false}
        min={componentConfig.min}
        max={componentConfig.max}
        step={componentConfig.step || 1}
        style={{
          width: "100%",
          height: "100%",
          border: "1px solid #d1d5db",
          borderRadius: "4px",
          padding: "8px 12px",
          fontSize: "14px",
          outline: "none",
          // isInteractive 모드에서는 사용자 스타일 우선 적용
          ...(isInteractive && component.style ? component.style : {}),
        }}
        onClick={handleClick}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
        onChange={(e) => {
          const newValue = e.target.value;
          console.log("🎯 NumberInputComponent onChange 호출:", {
            componentId: component.id,
            columnName: component.columnName,
            newValue,
            isInteractive,
            hasOnFormDataChange: !!onFormDataChange,
            hasOnChange: !!props.onChange,
          });

          // isInteractive 모드에서는 formData 업데이트
          if (isInteractive && onFormDataChange && component.columnName) {
            console.log(`📤 NumberInputComponent -> onFormDataChange 호출: ${component.columnName} = "${newValue}"`);
            onFormDataChange(component.columnName, newValue);
          }
          // 디자인 모드에서는 component.onChange 호출
          else if (component.onChange) {
            console.log(`📤 NumberInputComponent -> component.onChange 호출: ${newValue}`);
            component.onChange(newValue);
          }
          // props.onChange가 있으면 호출 (호환성)
          else if (props.onChange) {
            console.log(`📤 NumberInputComponent -> props.onChange 호출: ${newValue}`);
            props.onChange(newValue);
          }
        }}
      />
    </div>
  );
};

/**
 * NumberInput 래퍼 컴포넌트
 * 추가적인 로직이나 상태 관리가 필요한 경우 사용
 */
export const NumberInputWrapper: React.FC<NumberInputComponentProps> = (props) => {
  return <NumberInputComponent {...props} />;
};
