import { defineComponent, ref, watch } from 'vue';
import { loadIcon } from '@iconify/vue';
import SvgIcon from '@/components/custom/svg-icon.vue';

export default defineComponent({
  name: 'MenuIconCell',
  props: {
    icon: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const failed = ref(false);

    watch(
      () => props.icon,
      (value, _, onCleanup) => {
        const icon = value.trim();

        failed.value = !icon;

        if (!icon) {
          return;
        }

        let active = true;

        onCleanup(() => {
          active = false;
        });

        loadIcon(icon)
          .then(() => {
            if (active) {
              failed.value = false;
            }
          })
          .catch(() => {
            if (active) {
              failed.value = true;
            }
          });
      },
      { immediate: true }
    );

    return () => {
      const icon = props.icon.trim();

      if (!icon || failed.value) {
        return <div class="flex-center text-[#909399]">--</div>;
      }

      return (
        <div class="flex-center">
          <SvgIcon icon={icon} class="text-18px text-[#303133]" />
        </div>
      );
    };
  }
});
