import React, {CSSProperties, useMemo} from "react";
import {ColorValue} from "../models/Colors";
import {kelvinToRgbHex} from "../helpers/kelvin";
import {Icon} from "@iconify/react";

import "./Elements.sass";
import {LuciferIcon, toIconify} from "../models/Icons";

function Element({children}: React.PropsWithChildren<{}>) {
  return (
    <div className="Element">{children}</div>
  )
}

interface IconProps {
  icon?: LuciferIcon
  color?: ColorValue | "hs-gradient" | "k-gradient"
}

export function IconBlock({icon, color}: IconProps) {
  const style: CSSProperties = useMemo(() => {
    const s: CSSProperties = {
      backgroundClip: "text",
      // @ts-ignore
      textFillColor: "transparent",
    };

    if (color !== undefined) {
      if (color === "hs-gradient") {
        s.backgroundImage = "linear-gradient(to bottom right, red, yellow, green, blue, violet)";
      } else if (color === "k-gradient") {
        s.backgroundImage = "linear-gradient(to bottom right, #ff9329, #ffd6aa, #fffaf4, #fff, #c9e2ff, #40a3ff)";
      } else if (color.kelvin !== undefined && color.kelvin > 0) {
        s.color = kelvinToRgbHex(color.kelvin);
      } else {
        const hue = color.h || 0;
        const sat = Math.floor((color.s || 0) * 100);

        s.color = `hsl(${hue}, ${sat}%, 50%)`;
      }
    }

    return s;
  }, [color]);

  return (
    <Icon icon={toIconify(icon || LuciferIcon.Square)}
          className="ColorElement-block"
          style={style}
    />
  );
}

interface IconElementProps extends IconProps {
  caption: string
}

export function IconElement({caption, color, icon}: IconElementProps) {
  return (
    <Element>
      <IconBlock icon={icon} color={color}/>
      {caption}
    </Element>
  );
}
