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

export default {
  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.
    state: { type: String, required: true },
  },

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

  computed: {
    // Alias for this.state, since using 'state' can get confusing within this component.
    initialState() {
      return VULNERABILITY_STATES[this.state];
    },
  },

  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.initialState;
    },

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

<template>
  <gl-dropdown
    ref="dropdown"
    menu-class="p-0"
    toggle-class="text-capitalize"
    :text="state"
    :right="true"
    @hide="resetDropdown"
  >
    <li
      v-for="stateItem in states"
      :key="stateItem.action"
      class="py-3 px-2 dropdown-item cursor-pointer border-bottom"
      :class="[stateItem.action, { 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 === initialState"
        @click="saveState(selected)"
        >{{ s__('VulnerabilityManagement|Change status') }}
      </gl-button>
    </div>
  </gl-dropdown>
</template>
