"use client";

import React from "react";
import { WebTypeComponentProps } from "@/lib/registry/types";
import { ButtonIconRenderer } from "@/lib/button-icon-map";

export const ButtonWidget: React.FC<WebTypeComponentProps> = ({
  config,
  value,
  onChange,
  onBlur,
  disabled,
  readonly,
  placeholder,
  required,
  className,
  style,
  isDesignMode = false,
  ...restProps
}) => {
  const handleClick = (e: React.MouseEvent) => {
    if (isDesignMode) {
      return;
    }

    console.log("Button clicked:", config);

    if (onChange) {
      onChange("clicked");
    }
  };

  const hasCustomBg = config?.backgroundColor || style?.backgroundColor;
  const hasCustomColor = config?.textColor || style?.color;
  const hasCustomColors = hasCustomBg || hasCustomColor;
  
  const bgColor = config?.backgroundColor || style?.backgroundColor;
  const textColor = config?.textColor || style?.color;

  const fallbackLabel = config?.label || config?.text || (value as string) || placeholder || "버튼";

  if (isDesignMode) {
    return (
      <div
        onClick={handleClick}
        className={`flex items-center justify-center rounded-md px-4 text-sm font-medium ${
          hasCustomColors ? '' : 'bg-primary text-white'
        } ${className || ""}`}
        style={{
          ...style,
          backgroundColor: bgColor,
          color: textColor,
          width: "100%",
          height: "100%",
          cursor: "pointer",
        }}
      >
        <ButtonIconRenderer componentConfig={config} fallbackLabel={fallbackLabel} />
      </div>
    );
  }

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={disabled || readonly}
      className={`flex items-center justify-center rounded-md px-4 text-sm font-medium transition-colors duration-200 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:bg-muted/60 disabled:text-muted-foreground ${
        hasCustomColors ? '' : 'bg-primary text-white hover:bg-primary/90'
      } ${className || ""}`}
      style={{
        ...style,
        backgroundColor: bgColor,
        color: textColor,
        width: "100%",
        height: "100%",
      }}
    >
      <ButtonIconRenderer componentConfig={config} fallbackLabel={fallbackLabel} />
    </button>
  );
};
