"use client";

import React from "react";
import { Input } from "@/components/ui/input";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { WidgetComponent, NumberTypeConfig } from "@/types/screen";
import { formatNumber as formatNum, formatCurrency } from "@/lib/formatting";

export const NumberWidget: React.FC<WebTypeComponentProps> = ({ component, value, onChange, readonly = false }) => {
  const widget = component as WidgetComponent;
  const { placeholder, required, style } = widget;
  const config = widget.webTypeConfig as NumberTypeConfig | undefined;

  // 사용자가 테두리를 설정했는지 확인
  const hasCustomBorder = style && (style.borderWidth || style.borderStyle || style.borderColor || style.border);
  const borderClass = hasCustomBorder ? "!border-0" : "";

  // 숫자 포맷팅 함수
  const formatNumber = (val: string | number) => {
    if (!val) return "";
    const numValue = typeof val === "string" ? parseFloat(val) : val;
    if (isNaN(numValue)) return "";

    if (config?.format === "currency") {
      return formatCurrency(numValue);
    }

    if (config?.format === "percentage") {
      return `${numValue}%`;
    }

    if (config?.thousandSeparator) {
      return formatNum(numValue);
    }

    return numValue.toString();
  };

  // 입력값 처리
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let inputValue = e.target.value;

    // 숫자가 아닌 문자 제거 (소수점과 마이너스 제외)
    if (widget.widgetType === "number") {
      inputValue = inputValue.replace(/[^0-9-]/g, "");
    } else if (widget.widgetType === "decimal") {
      inputValue = inputValue.replace(/[^0-9.-]/g, "");
    }

    // 범위 검증
    if (config?.min !== undefined || config?.max !== undefined) {
      const numValue = parseFloat(inputValue);
      if (!isNaN(numValue)) {
        if (config.min !== undefined && numValue < config.min) {
          inputValue = config.min.toString();
        }
        if (config.max !== undefined && numValue > config.max) {
          inputValue = config.max.toString();
        }
      }
    }

    onChange?.(inputValue);
  };

  // 웹타입에 따른 input type과 step 결정
  const getInputProps = () => {
    if (widget.widgetType === "decimal") {
      return {
        type: "number",
        step: config?.step || 0.01,
      };
    }
    return {
      type: "number",
      step: config?.step || 1,
    };
  };

  const inputProps = getInputProps();

  return (
    <Input
      {...inputProps}
      value={value || ""}
      placeholder={placeholder || config?.placeholder || "숫자를 입력하세요..."}
      onChange={handleChange}
      disabled={readonly}
      required={required}
      className={`h-full w-full ${borderClass}`}
      min={config?.min}
      max={config?.max}
    />
  );
};

NumberWidget.displayName = "NumberWidget";


