"use client";

import React from "react";
import { Textarea } from "@/components/ui/textarea";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { WidgetComponent, TextareaTypeConfig } from "@/types/screen";

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

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

  // 글자 수 계산
  const currentLength = (value || "").length;
  const maxLength = config?.maxLength;
  const showCounter = maxLength && maxLength > 0;

  return (
    <div className="relative h-full w-full">
      <Textarea
        value={value || ""}
        placeholder={placeholder || config?.placeholder || "내용을 입력하세요..."}
        onChange={(e) => onChange?.(e.target.value)}
        disabled={readonly}
        required={required}
        className={`h-full w-full resize-none ${borderClass} ${showCounter ? "pb-6" : ""}`}
        maxLength={maxLength}
        minLength={config?.minLength}
        rows={config?.rows || 3}
      />

      {/* 글자 수 카운터 */}
      {showCounter && (
        <div className="text-muted-foreground absolute right-2 bottom-1 text-xs">
          {currentLength} / {maxLength}
        </div>
      )}
    </div>
  );
};

TextareaWidget.displayName = "TextareaWidget";


