import { ref, computed, PropType, defineComponent, h, isVNode } from "vue";
import "./index.scss";

export type OptionsType = {
  label?: string;
  value?: string | number;
  icon?: any;
  iconAttrs?: Record<string, any>;
  tip?: string;
  theme?: string;
  disabled?: boolean;
};

const props = {
  options: {
    type: Array as PropType<Array<OptionsType>>,
    default: () => []
  },
  modelValue: {
    type: [String, Number] as PropType<string | number>,
    default: ""
  },
  resize: {
    type: Boolean,
    default: false
  },
  block: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
};

export default defineComponent({
  name: "ReSegmented",
  props,
  emits: ["update:modelValue", "change"],
  setup(props, { emit, slots }) {
    const currentIndex = ref(0);

    function handleClick(index: number, option: OptionsType) {
      if (props.disabled) return;
      currentIndex.value = index;
      emit("update:modelValue", option.value ?? index);
      emit("change", { option, index });
    }

    function handleMouseover(index: number) {
      if (props.disabled) return;
    }

    const curMouseClass = computed(() => {
      return (index: number) => {
        return index === currentIndex.value
          ? "is-selected"
          : index < currentIndex.value
            ? "is-left-selected"
            : "";
      };
    });

    function renderIcon(option: OptionsType) {
      if (!option.icon) return null;
      const iconComponent = option.icon;
      const iconAttrs = option.iconAttrs || {};
      if (typeof iconComponent === "object" || typeof iconComponent === "function") {
        return h(iconComponent, { ...iconAttrs, class: "pure-segmented-item-icon" });
      }
      return null;
    }

    return () => (
      <div
        class={[
          "pure-segmented",
          { "pure-segmented-block": props.block, "pure-segmented-disabled": props.disabled }
        ]}
      >
        <div class="pure-segmented-thumb" />
        <div class="pure-segmented-item-container">
          {props.options.map((option, index) => (
            <div
              key={index}
              class={["pure-segmented-item", curMouseClass.value(index)]}
              onMouseover={() => handleMouseover(index)}
              onClick={() => handleClick(index, option)}
            >
              {renderIcon(option)}
              {option.label && (
                <span class="pure-segmented-item-label">{option.label}</span>
              )}
            </div>
          ))}
        </div>
      </div>
    );
  }
});
