"use client";

import React from "react";
import { Input } from "@/components/ui/input";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { WidgetComponent, TextTypeConfig } from "@/types/screen";

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

  // 입력 타입에 따른 처리
  const isAutoInput = widget?.inputType === "auto";

  // 자동 값 생성 함수
  const getAutoValue = (autoValueType: string) => {
    switch (autoValueType) {
      case "current_datetime":
        return new Date().toLocaleString("ko-KR");
      case "current_date":
        return new Date().toLocaleDateString("ko-KR");
      case "current_time":
        return new Date().toLocaleTimeString("ko-KR");
      case "current_user":
        return "현재사용자";
      case "uuid":
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
          const r = (Math.random() * 16) | 0;
          const v = c === "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        });
      case "sequence":
        return "SEQ_001";
      case "user_defined":
        return "사용자정의값";
      default:
        return "자동생성값";
    }
  };

  // 자동 값 플레이스홀더 생성 함수
  const getAutoPlaceholder = (autoValueType: string) => {
    switch (autoValueType) {
      case "current_datetime":
        return "현재 날짜시간";
      case "current_date":
        return "현재 날짜";
      case "current_time":
        return "현재 시간";
      case "current_user":
        return "현재 사용자";
      case "uuid":
        return "UUID";
      case "sequence":
        return "시퀀스";
      case "user_defined":
        return "사용자 정의";
      default:
        return "자동 생성됨";
    }
  };

  // 플레이스홀더 처리
  const finalPlaceholder = isAutoInput
    ? getAutoPlaceholder(widget?.autoValueType || "")
    : placeholder || config?.placeholder || "입력하세요...";

  // 값 처리
  const finalValue = isAutoInput ? getAutoValue(widget?.autoValueType || "") : value || "";

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

  // 기본 테두리 제거 여부 결정 - Shadcn UI 기본 border 클래스를 덮어쓰기
  const borderClass = hasCustomBorder ? "!border-0" : "";

  // 웹타입에 따른 input type 결정
  const getInputType = () => {
    switch (widget?.widgetType) {
      case "email":
        return "email";
      case "tel":
        return "tel";
      case "text":
      default:
        return "text";
    }
  };

  return (
    <Input
      type={getInputType()}
      value={finalValue}
      placeholder={finalPlaceholder}
      onChange={(e) => onChange?.(e.target.value)}
      disabled={readonly || isAutoInput}
      required={required}
      className={`w-full ${borderClass}`}
      maxLength={config?.maxLength}
      minLength={config?.minLength}
      pattern={config?.pattern}
      autoComplete={config?.autoComplete}
    />
  );
};

TextWidget.displayName = "TextWidget";
