import { cn } from "@/lib/utils";
import { ButtonDecorator, ButtonDecoratorPos } from "@/types/external/shadcn";
import { IconDefinition } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";

export const getIcon = (
  icon: IconDefinition,
  position: ButtonDecoratorPos,
  hasChildren?: boolean,
) => {
  return (
    <FontAwesomeIcon
      icon={icon}
      className={cn(hasChildren && (position === "start" ? "mr-1" : "ml-1"))}
    />
  );
};

export const renderDecorator = (
  position: ButtonDecoratorPos,
  decorator: ButtonDecorator,
  hasChildren?: boolean,
) => {
  if (!decorator) return null;

  let content: IconDefinition | React.ReactNode;
  let pos = "start";

  const _getIcon = (icon: any) => getIcon(icon, position, hasChildren);

  if (React.isValidElement(decorator) || typeof decorator === "string") {
    content = decorator;
  } else if (typeof decorator === "object" && "content" in decorator) {
    content = decorator.content;
    pos = decorator.pos || "start";
  } else if (typeof decorator === "object" && "icon" in decorator) {
    content = _getIcon(decorator);
  } else {
    return null;
  }

  if (typeof content === "object" && "icon" in content) {
    content = _getIcon(content);
  }

  if (position !== pos) return null;

  return content;
};
