import { Button } from "@progress/kendo-react-buttons";
import { Style } from "../../DomainProps";
import withLabel from "../../../hoc/withLabel";
import withHelperText from "../../../hoc/withHelperText";
import withToolTip from "../../../hoc/withToolTip";
import withValidations from "../../../hoc/withValidations";

interface ButtonProps {
  widgetStyle?: Style;
  title?: string;
  icon?: string;
  iconClass?: string;
  imageUrl?: string;
  defaultImageUrl: string;
  imageAlt?: string;
  togglable: boolean;
  fillMode: "solid" | "link" | "outline" | "flat";
  role: "button" | "icon" | "image";
  type: "button" | "submit" | "reset";
  onClick: (e: any) => void;
  onBlur: (e: any) => void;
}

const ButtonView = ({
  widgetStyle,
  title,
  onClick,
  onBlur,
  icon,
  iconClass,
  imageUrl,
  defaultImageUrl,
  imageAlt,
  role,
  fillMode,
  ...rest
}: ButtonProps) => {
  // Handle image rendering with fallback
  const renderContent = () => {
    if (role === "image" && imageUrl) {
      return (
        <img 
          src={imageUrl} 
          alt={imageAlt} 
          onError={({ currentTarget }) => {
            currentTarget.onerror = null;
            currentTarget.src = defaultImageUrl;
          }}
        />
      );
    }
    
    if (role === "icon" && (icon || iconClass)) {
      // If using Kendo icons
      if (icon) {
        return <span className={`k-icon k-i-${icon}`} />;
      }
      // If using custom icon classes
      if (iconClass) {
        return <span className={iconClass} />;
      }
    }
    
    return title;
  };

  // Handle fillMode to ensure it's a valid value
  const validFillMode = fillMode && ["solid", "link", "outline", "flat"].includes(fillMode) ? fillMode : undefined;

  return (
    <Button
      onClick={onClick}
      onBlur={onBlur}
      style={widgetStyle?.inline ?? undefined}
      id={widgetStyle?.id}
      className={widgetStyle?.className}
      fillMode={validFillMode}
      {...rest}
    >
      {renderContent()}
    </Button>
  );
};

export default withValidations(
  withToolTip(withHelperText(withLabel(ButtonView)))
);