<script>
import { GlDropdown, GlIcon, GlButton } from '@gitlab/ui';
import { VULNERABILITY_STATE_OBJECTS } from '../constants';

export default {
  states: Object.values(VULNERABILITY_STATE_OBJECTS),
  components: { GlDropdown, GlIcon, GlButton },

  props: {
    // Initial vulnerability state from the parent. This is used to disable the Change Status button
    // if the selected value is the initial value, and also used to reset the dropdown back to the
    // initial value if the user closed the dropdown without saving it.
    initialState: { type: String, required: true },
  },

  data() {
    return {
      // Vulnerability state that's picked in the dropdown. Defaults to the passed-in state.
      selected: VULNERABILITY_STATE_OBJECTS[this.initialState],
    };
  },

  computed: {
    initialStateItem() {
      return VULNERABILITY_STATE_OBJECTS[this.initialState];
    },
  },

  watch: {
    // If the initial state was changed by the parent component, re-select the correct state object.
    initialStateItem(newItem) {
      this.selected = newItem;
    },
  },

  methods: {
    changeSelectedState(newState) {
      this.selected = newState;
    },

    closeDropdown() {
      this.$refs.dropdown.hide();
    },

    // Reset the selected dropdown item to what was passed in by the parent.
    resetDropdown() {
      this.selected = this.initialStateItem;
    },

    saveState(selectedState) {
      this.$emit('change', selectedState.action);
      this.closeDropdown();
    },
  },
};
</script>

<template>
  <gl-dropdown
    ref="dropdown"
    menu-class="gl-p-0 dropdown-extended-height"
    toggle-class="text-capitalize"
    :text="initialState"
    :right="true"
    @hide="resetDropdown"
  >
    <li
      v-for="stateItem in $options.states"
      :key="stateItem.action"
      class="py-3 px-2 dropdown-item cursor-pointer border-bottom"
      :class="{ selected: selected === stateItem }"
      @click="changeSelectedState(stateItem)"
    >
      <div class="d-flex align-items-center">
        <gl-icon
          v-if="selected === stateItem"
          class="selected-icon position-absolute"
          name="status_success_borderless"
          :size="24"
        />
        <div class="pl-4 font-weight-bold">{{ stateItem.displayName }}</div>
      </div>
      <div class="pl-4">{{ stateItem.description }}</div>
    </li>

    <div class="text-right p-3">
      <gl-button ref="cancel-button" class="mr-2" @click="closeDropdown">
        {{ __('Cancel') }}
      </gl-button>
      <gl-button
        ref="save-button"
        variant="success"
        :disabled="selected === initialStateItem"
        @click="saveState(selected)"
      >
        {{ s__('VulnerabilityManagement|Change status') }}
      </gl-button>
    </div>
  </gl-dropdown>
</template>
