import {
  FunctionalComponent,
  h, useProp,
} from "atomico";
import { useStylesheet } from "@caedman/kit/dist/use-stylesheet";
import { Option } from "funfix";

import "lazyload-image";

import "../kun-icon/kun-icon";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

const KunImage: FunctionalComponent = () => {
  const [url] = useProp<string>("url");
  const [heightP] = useProp<number>("height");
  const [widthP] = useProp<number>("width");
  const [className] = useProp<string>("cls");

  const height = Option.of(heightP).map((str1) => `${str1}px`).getOrElse("100%");
  const width = Option.of(widthP).map((str1) => `${str1}px`).getOrElse("100%");

  const style1 = `
    .kun-image-avatar {
      --lazy-image-border-radius: 50%;
    }
    
    .kun-custom-image1 {
      width: ${width};
      height: ${height};
      object-fit: fill;
      --lazy-image-fit: fill;
    }
    img[aria-hidden="true"] {
      display: none;
    }
  `;

  useStylesheet(style1);

  return (
    <host shadowDom>
      <div class="w-full h-full">
        {
          url == null && (
          <kun-icon slot="placeholder" iconType="preload-image" iconWidth={widthP} iconHeight={heightP} />
          )
        }
        {
          url != null && (
          <lazy-image
            className={`${className} kun-custom-image1`}
            src={url}
            lazy-image-width={width}
            lazy-image-height={height}
            lazyImageWidth={width}
            lazyImageHeight={height}
          >
            <kun-icon slot="placeholder" iconType="preload-image" iconWidth={widthP} iconHeight={heightP} />
          </lazy-image>
          )
        }
      </div>
    </host>
  );
};

KunImage.props = {
  height: {
    type: Number,
  },
  cls: {
    type: String,
  },
  width: {
    type: Number,
  },
  url: {
    type: String,
    reflect: true,
  },
};

export default getComponentOrDefine("kun-image", KunImage);
