"use client";

import React, { useEffect, useState } from "react";
import { ComponentRendererProps } from "@/types/component";
import { AutoGenerationConfig } from "@/types/screen";
import { TextInputConfig } from "./types";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";
import { AutoGenerationUtils } from "@/lib/utils/autoGeneration";
import { INPUT_CLASSES, cn, getInputClasses } from "../common/inputStyles";
import { ChevronDown, Check, ChevronsUpDown } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";

export interface TextInputComponentProps extends ComponentRendererProps {
  config?: TextInputConfig;
}

/**
 * TextInput 컴포넌트
 * text-input 컴포넌트입니다
 */
export const TextInputComponent: React.FC<TextInputComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  isInteractive = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  formData,
  onFormDataChange,
  ...props
}) => {
  // 컴포넌트 설정
  const componentConfig = {
    ...config,
    ...component.config,
  } as TextInputConfig;

  // 자동생성 설정 (props에서 전달받은 값 우선 사용)
  const autoGeneration: AutoGenerationConfig = props.autoGeneration ||
    component.autoGeneration ||
    componentConfig.autoGeneration || {
      type: "none",
      enabled: false,
    };

  // 숨김 상태 (props에서 전달받은 값 우선 사용)
  const isHidden = props.hidden !== undefined ? props.hidden : component.hidden || componentConfig.hidden || false;

  // 자동생성된 값 상태
  const [autoGeneratedValue, setAutoGeneratedValue] = useState<string>("");

  // 테스트용: 컴포넌트 라벨에 "test"가 포함되면 강제로 UUID 자동생성 활성화
  const testAutoGeneration = component.label?.toLowerCase().includes("test")
    ? {
        type: "uuid" as AutoGenerationType,
        enabled: true,
      }
    : autoGeneration;

  // 디버그 로그 (필요시 주석 해제)
  // console.log("🔧 텍스트 입력 컴포넌트 설정:", {
  //   config,
  //   componentConfig,
  //   component: component,
  //   autoGeneration,
  //   testAutoGeneration,
  //   isTestMode: component.label?.toLowerCase().includes("test"),
  //   isHidden,
  //   isInteractive,
  //   formData,
  //   columnName: component.columnName,
  //   currentFormValue: formData?.[component.columnName],
  //   componentValue: component.value,
  //   autoGeneratedValue,
  // });

  // 자동생성 값 생성 (컴포넌트 마운트 시 또는 폼 데이터 변경 시)
  useEffect(() => {
    console.log("🔄 자동생성 useEffect 실행:", {
      enabled: testAutoGeneration.enabled,
      type: testAutoGeneration.type,
      isInteractive,
      columnName: component.columnName,
      hasFormData: !!formData,
      hasOnFormDataChange: !!onFormDataChange,
    });

    if (testAutoGeneration.enabled && testAutoGeneration.type !== "none") {
      // 폼 데이터에 이미 값이 있으면 자동생성하지 않음
      const currentFormValue = formData?.[component.columnName];
      const currentComponentValue = component.value;

      console.log("🔍 자동생성 조건 확인:", {
        currentFormValue,
        currentComponentValue,
        hasCurrentValue: !!(currentFormValue || currentComponentValue),
        autoGeneratedValue,
      });

      // 자동생성된 값이 없고, 현재 값도 없을 때만 생성
      if (!autoGeneratedValue && !currentFormValue && !currentComponentValue) {
        const generatedValue = AutoGenerationUtils.generateValue(testAutoGeneration, component.columnName);
        console.log("✨ 자동생성된 값:", generatedValue);

        if (generatedValue) {
          setAutoGeneratedValue(generatedValue);

          // 폼 데이터에 자동생성된 값 설정 (인터랙티브 모드에서만)
          if (isInteractive && onFormDataChange && component.columnName) {
            console.log("📝 폼 데이터에 자동생성 값 설정:", {
              columnName: component.columnName,
              value: generatedValue,
            });
            onFormDataChange(component.columnName, generatedValue);
          }
        }
      } else if (!autoGeneratedValue && testAutoGeneration.type !== "none") {
        // 디자인 모드에서도 미리보기용 자동생성 값 표시
        const previewValue = AutoGenerationUtils.generatePreviewValue(testAutoGeneration);
        console.log("🎨 디자인 모드 미리보기 값:", previewValue);
        setAutoGeneratedValue(previewValue);
      } else {
        console.log("⏭️ 이미 값이 있어서 자동생성 건너뜀:", {
          hasAutoGenerated: !!autoGeneratedValue,
          hasFormValue: !!currentFormValue,
          hasComponentValue: !!currentComponentValue,
        });
      }
    }
  }, [testAutoGeneration, isInteractive, component.columnName, component.value, formData, onFormDataChange]);

  // 스타일 계산 (위치는 RealtimePreviewDynamic에서 처리하므로 제외)
  const componentStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    ...component.style,
    ...style,
    // 숨김 기능: 디자인 모드에서는 연하게, 실제 화면에서는 완전히 숨김
    ...(isHidden && {
      opacity: isDesignMode ? 0.4 : 0,
      backgroundColor: isDesignMode ? "#f3f4f6" : "transparent",
      pointerEvents: isDesignMode ? "auto" : "none",
      display: isDesignMode ? "block" : "none",
    }),
  };

  // 디자인 모드 스타일
  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,
    autoGeneration: _autoGeneration,
    hidden: _hidden,
    isInModal: _isInModal,
    isPreview: _isPreview,
    originalData: _originalData,
    allComponents: _allComponents,
    selectedRows: _selectedRows,
    selectedRowsData: _selectedRowsData,
    refreshKey: _refreshKey,
    onUpdateLayout: _onUpdateLayout,
    onSelectedRowsChange: _onSelectedRowsChange,
    onConfigChange: _onConfigChange,
    ...domProps
  } = props;

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

  // webType에 따른 실제 input type 및 검증 규칙 결정
  const webType = component.componentConfig?.webType || "text";
  const inputType = (() => {
    switch (webType) {
      case "email":
        return "email";
      case "tel":
        return "tel";
      case "url":
        return "url";
      case "password":
        return "password";
      case "textarea":
        return "text"; // textarea는 별도 처리
      case "text":
      default:
        return "text";
    }
  })();

  // webType별 검증 패턴
  const validationPattern = (() => {
    switch (webType) {
      case "tel":
        // 한국 전화번호 형식: 010-1234-5678, 02-1234-5678 등
        return "[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}";
      default:
        return undefined;
    }
  })();

  // webType별 placeholder
  const defaultPlaceholder = (() => {
    switch (webType) {
      case "email":
        return "example@email.com";
      case "tel":
        return "010-1234-5678";
      case "url":
        return "https://example.com";
      case "password":
        return "비밀번호를 입력하세요";
      case "textarea":
        return "내용을 입력하세요";
      default:
        return "텍스트를 입력하세요";
    }
  })();

  // 이메일 입력 상태 (username@domain 분리)
  const [emailUsername, setEmailUsername] = React.useState("");
  const [emailDomain, setEmailDomain] = React.useState("gmail.com");
  const [emailDomainOpen, setEmailDomainOpen] = React.useState(false);

  // 전화번호 입력 상태 (3개 부분으로 분리)
  const [telPart1, setTelPart1] = React.useState("");
  const [telPart2, setTelPart2] = React.useState("");
  const [telPart3, setTelPart3] = React.useState("");

  // URL 입력 상태 (프로토콜 + 도메인)
  const [urlProtocol, setUrlProtocol] = React.useState("https://");
  const [urlDomain, setUrlDomain] = React.useState("");

  // 이메일 도메인 목록
  const emailDomains = ["gmail.com", "naver.com", "daum.net", "kakao.com", "직접입력"];

  // 이메일 값 동기화
  React.useEffect(() => {
    if (webType === "email") {
      const currentValue =
        isInteractive && formData && component.columnName ? formData[component.columnName] : component.value || "";

      if (currentValue && typeof currentValue === "string" && currentValue.includes("@")) {
        const [username, domain] = currentValue.split("@");
        setEmailUsername(username || "");
        setEmailDomain(domain || "gmail.com");
      }
    }
  }, [webType, component.value, formData, component.columnName, isInteractive]);

  // 전화번호 값 동기화
  React.useEffect(() => {
    if (webType === "tel") {
      const currentValue =
        isInteractive && formData && component.columnName ? formData[component.columnName] : component.value || "";

      if (currentValue && typeof currentValue === "string") {
        const parts = currentValue.split("-");
        setTelPart1(parts[0] || "");
        setTelPart2(parts[1] || "");
        setTelPart3(parts[2] || "");
      }
    }
  }, [webType, component.value, formData, component.columnName, isInteractive]);

  // URL 값 동기화
  React.useEffect(() => {
    if (webType === "url") {
      const currentValue =
        isInteractive && formData && component.columnName ? formData[component.columnName] : component.value || "";

      if (currentValue && typeof currentValue === "string") {
        if (currentValue.startsWith("https://")) {
          setUrlProtocol("https://");
          setUrlDomain(currentValue.substring(8));
        } else if (currentValue.startsWith("http://")) {
          setUrlProtocol("http://");
          setUrlDomain(currentValue.substring(7));
        } else {
          setUrlDomain(currentValue);
        }
      }
    }
  }, [webType, component.value, formData, component.columnName, isInteractive]);

  // 이메일 타입 전용 UI
  if (webType === "email") {
    return (
      <div className={`flex w-full flex-col ${className || ""}`} {...safeDomProps}>
        {/* 라벨 렌더링 */}
        {component.label && component.style?.labelDisplay !== false && (
          <label className="mb-1.5 text-sm font-medium text-slate-600">
            {component.label}
            {component.required && <span className="text-red-500">*</span>}
          </label>
        )}

        <div className="box-border flex h-full w-full items-center gap-2">
          {/* 사용자명 입력 */}
          <input
            type="text"
            value={emailUsername}
            placeholder="사용자명"
            disabled={componentConfig.disabled || false}
            readOnly={componentConfig.readonly || false}
            onChange={(e) => {
              const newUsername = e.target.value;
              setEmailUsername(newUsername);
              const fullEmail = `${newUsername}@${emailDomain}`;

              if (isInteractive && onFormDataChange && component.columnName) {
                onFormDataChange(component.columnName, fullEmail);
              }
            }}
            className={`h-full flex-1 rounded-md border px-3 py-2 text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
          />

          {/* @ 구분자 */}
          <span className="text-base font-medium text-gray-500">@</span>

          {/* 도메인 선택/입력 (Combobox) */}
          <Popover open={emailDomainOpen} onOpenChange={setEmailDomainOpen}>
            <PopoverTrigger asChild>
              <button
                type="button"
                role="combobox"
                aria-expanded={emailDomainOpen}
                disabled={componentConfig.disabled || false}
                className={cn(
                  "flex h-full flex-1 items-center justify-between rounded-md border px-3 py-2 text-sm transition-all duration-200",
                  isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300",
                  componentConfig.disabled ? "cursor-not-allowed bg-gray-100 text-gray-400" : "bg-white text-gray-900",
                  "hover:border-orange-400 focus:border-orange-500 focus:ring-2 focus:ring-orange-100 focus:outline-none",
                  emailDomainOpen && "border-orange-500 ring-2 ring-orange-100",
                )}
              >
                <span className={cn("truncate", !emailDomain && "text-gray-400")}>{emailDomain || "도메인 선택"}</span>
                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
              </button>
            </PopoverTrigger>
            <PopoverContent className="w-[200px] p-0" align="start">
              <Command>
                <CommandInput
                  placeholder="도메인 검색 또는 입력..."
                  value={emailDomain}
                  onValueChange={(value) => {
                    setEmailDomain(value);
                    const fullEmail = `${emailUsername}@${value}`;

                    if (isInteractive && onFormDataChange && component.columnName) {
                      onFormDataChange(component.columnName, fullEmail);
                    }
                  }}
                />
                <CommandList>
                  <CommandEmpty>직접 입력한 도메인: {emailDomain}</CommandEmpty>
                  <CommandGroup>
                    {emailDomains
                      .filter((d) => d !== "직접입력")
                      .map((domain) => (
                        <CommandItem
                          key={domain}
                          value={domain}
                          onSelect={(currentValue) => {
                            setEmailDomain(currentValue);
                            const fullEmail = `${emailUsername}@${currentValue}`;

                            if (isInteractive && onFormDataChange && component.columnName) {
                              onFormDataChange(component.columnName, fullEmail);
                            }
                            setEmailDomainOpen(false);
                          }}
                        >
                          <Check className={cn("mr-2 h-4 w-4", emailDomain === domain ? "opacity-100" : "opacity-0")} />
                          {domain}
                        </CommandItem>
                      ))}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>
        </div>
      </div>
    );
  }

  // 전화번호 타입 전용 UI
  if (webType === "tel") {
    return (
      <div className={`flex w-full flex-col ${className || ""}`} {...safeDomProps}>
        {/* 라벨 렌더링 */}
        {component.label && component.style?.labelDisplay !== false && (
          <label className="mb-1.5 text-sm font-medium text-slate-600">
            {component.label}
            {component.required && <span className="text-red-500">*</span>}
          </label>
        )}

        <div className="box-border flex h-full w-full items-center gap-1.5">
          {/* 첫 번째 부분 (지역번호) */}
          <input
            type="text"
            value={telPart1}
            placeholder="010"
            maxLength={3}
            disabled={componentConfig.disabled || false}
            readOnly={componentConfig.readonly || false}
            onChange={(e) => {
              const value = e.target.value.replace(/[^0-9]/g, "");
              setTelPart1(value);
              const fullTel = `${value}-${telPart2}-${telPart3}`;

              if (isInteractive && onFormDataChange && component.columnName) {
                onFormDataChange(component.columnName, fullTel);
              }
            }}
            className={`h-full flex-1 rounded-md border px-3 py-2 text-center text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
          />

          <span className="text-base font-medium text-gray-500">-</span>

          {/* 두 번째 부분 */}
          <input
            type="text"
            value={telPart2}
            placeholder="1234"
            maxLength={4}
            disabled={componentConfig.disabled || false}
            readOnly={componentConfig.readonly || false}
            onChange={(e) => {
              const value = e.target.value.replace(/[^0-9]/g, "");
              setTelPart2(value);
              const fullTel = `${telPart1}-${value}-${telPart3}`;

              if (isInteractive && onFormDataChange && component.columnName) {
                onFormDataChange(component.columnName, fullTel);
              }
            }}
            className={`h-full flex-1 rounded-md border px-3 py-2 text-center text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
          />

          <span className="text-base font-medium text-gray-500">-</span>

          {/* 세 번째 부분 */}
          <input
            type="text"
            value={telPart3}
            placeholder="5678"
            maxLength={4}
            disabled={componentConfig.disabled || false}
            readOnly={componentConfig.readonly || false}
            onChange={(e) => {
              const value = e.target.value.replace(/[^0-9]/g, "");
              setTelPart3(value);
              const fullTel = `${telPart1}-${telPart2}-${value}`;

              if (isInteractive && onFormDataChange && component.columnName) {
                onFormDataChange(component.columnName, fullTel);
              }
            }}
            className={`h-full flex-1 rounded-md border px-3 py-2 text-center text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
          />
        </div>
      </div>
    );
  }

  // URL 타입 전용 UI
  if (webType === "url") {
    return (
      <div className={`flex w-full flex-col ${className || ""}`} {...safeDomProps}>
        {/* 라벨 렌더링 */}
        {component.label && component.style?.labelDisplay !== false && (
          <label className="mb-1.5 text-sm font-medium text-slate-600">
            {component.label}
            {component.required && <span className="text-red-500">*</span>}
          </label>
        )}

        <div className="box-border flex h-full w-full items-center gap-1">
          {/* 프로토콜 선택 */}
          <select
            value={urlProtocol}
            disabled={componentConfig.disabled || false}
            onChange={(e) => {
              const newProtocol = e.target.value;
              setUrlProtocol(newProtocol);
              const fullUrl = `${newProtocol}${urlDomain}`;

              if (isInteractive && onFormDataChange && component.columnName) {
                onFormDataChange(component.columnName, fullUrl);
              }
            }}
            className={`h-full w-[100px] cursor-pointer rounded-md border px-2 py-2 text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
          >
            <option value="https://">https://</option>
            <option value="http://">http://</option>
          </select>

          {/* 도메인 입력 */}
          <input
            type="text"
            value={urlDomain}
            placeholder="www.example.com"
            disabled={componentConfig.disabled || false}
            readOnly={componentConfig.readonly || false}
            onChange={(e) => {
              const newDomain = e.target.value;
              setUrlDomain(newDomain);
              const fullUrl = `${urlProtocol}${newDomain}`;

              if (isInteractive && onFormDataChange && component.columnName) {
                onFormDataChange(component.columnName, fullUrl);
              }
            }}
            className={`h-full flex-1 rounded-md border px-3 py-2 text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
          />
        </div>
      </div>
    );
  }

  // textarea 타입인 경우 별도 렌더링
  if (webType === "textarea") {
    return (
      <div className={`flex w-full flex-col ${className || ""}`} {...safeDomProps}>
        {/* 라벨 렌더링 */}
        {component.label && component.style?.labelDisplay !== false && (
          <label className="mb-1.5 text-sm font-medium text-slate-600">
            {component.label}
            {component.required && <span className="text-red-500">*</span>}
          </label>
        )}

        <textarea
          value={(() => {
            let displayValue = "";

            if (isInteractive && formData && component.columnName) {
              displayValue = formData[component.columnName] || autoGeneratedValue || "";
            } else {
              displayValue = component.value || autoGeneratedValue || "";
            }

            return displayValue;
          })()}
          placeholder={
            testAutoGeneration.enabled && testAutoGeneration.type !== "none"
              ? `자동생성: ${AutoGenerationUtils.getTypeDescription(testAutoGeneration.type)}`
              : componentConfig.placeholder || defaultPlaceholder
          }
          disabled={componentConfig.disabled || false}
          required={componentConfig.required || false}
          readOnly={componentConfig.readonly || false}
          onChange={(e) => {
            if (isInteractive && onFormDataChange && component.columnName) {
              onFormDataChange(component.columnName, e.target.value);
            }
          }}
          className={`box-border h-full w-full max-w-full resize-none rounded-md border px-3 py-2 text-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} placeholder:text-gray-400 focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
        />
      </div>
    );
  }

  return (
    <div className={`flex w-full max-w-full flex-col ${className || ""}`} {...safeDomProps}>
      {/* 라벨 렌더링 */}
      {component.label && component.style?.labelDisplay !== false && (
        <label className="mb-1.5 text-sm font-medium text-slate-600">
          {component.label}
          {component.required && <span className="text-red-500">*</span>}
        </label>
      )}

      <input
        type={inputType}
        value={(() => {
          let displayValue = "";

          if (isInteractive && formData && component.columnName) {
            // 인터랙티브 모드: formData 우선, 없으면 자동생성 값
            const rawValue = formData[component.columnName] || autoGeneratedValue || "";
            // 객체인 경우 빈 문자열로 변환 (에러 방지)
            displayValue = typeof rawValue === "object" ? "" : String(rawValue);
          } else {
            // 디자인 모드: component.value 우선, 없으면 자동생성 값
            const rawValue = component.value || autoGeneratedValue || "";
            displayValue = typeof rawValue === "object" ? "" : String(rawValue);
          }

          console.log("📄 Input 값 계산:", {
            isInteractive,
            hasFormData: !!formData,
            columnName: component.columnName,
            formDataValue: formData?.[component.columnName],
            formDataValueType: typeof formData?.[component.columnName],
            componentValue: component.value,
            autoGeneratedValue,
            finalDisplayValue: displayValue,
            isObject: typeof displayValue === "object",
          });

          return displayValue;
        })()}
        placeholder={
          testAutoGeneration.enabled && testAutoGeneration.type !== "none"
            ? `자동생성: ${AutoGenerationUtils.getTypeDescription(testAutoGeneration.type)}`
            : componentConfig.placeholder || defaultPlaceholder
        }
        pattern={validationPattern}
        title={webType === "tel" ? "전화번호 형식: 010-1234-5678" : undefined}
        disabled={componentConfig.disabled || false}
        required={componentConfig.required || false}
        readOnly={componentConfig.readonly || (testAutoGeneration.enabled && testAutoGeneration.type !== "none")}
        className={`box-border h-full w-full max-w-full rounded-md border px-3 py-2 text-sm shadow-sm transition-all duration-200 outline-none ${isSelected ? "border-blue-500 ring-2 ring-blue-100" : "border-gray-300"} ${componentConfig.disabled ? "bg-gray-100 text-gray-400" : "bg-white text-gray-900"} placeholder:text-gray-400 focus:border-orange-500 focus:ring-2 focus:ring-orange-100 disabled:cursor-not-allowed`}
        onClick={handleClick}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
        onChange={(e) => {
          const newValue = e.target.value;
          // console.log("🎯 TextInputComponent onChange 호출:", {
          //   componentId: component.id,
          //   columnName: component.columnName,
          //   newValue,
          //   isInteractive,
          //   hasOnFormDataChange: !!onFormDataChange,
          //   hasOnChange: !!props.onChange,
          // });

          // isInteractive 모드에서는 formData 업데이트
          if (isInteractive && onFormDataChange && component.columnName) {
            console.log(`✅ TextInputComponent onChange 조건 충족:`, {
              columnName: component.columnName,
              newValue,
              valueType: typeof newValue,
              isInteractive,
              hasOnFormDataChange: !!onFormDataChange,
              onFormDataChangeType: typeof onFormDataChange,
            });
            onFormDataChange(component.columnName, newValue);
            console.log(`✅ onFormDataChange 호출 완료`);
          } else {
            console.log("❌ TextInputComponent onFormDataChange 조건 미충족:", {
              isInteractive,
              hasOnFormDataChange: !!onFormDataChange,
              hasColumnName: !!component.columnName,
              columnName: component.columnName,
            });
          }

          // props.onChange는 DynamicComponentRenderer의 handleChange
          // 이벤트 객체 감지 및 값 추출 로직이 있으므로 안전하게 호출 가능
          if (props.onChange) {
            props.onChange(newValue);
          }
        }}
      />
    </div>
  );
};

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