<template>
  <v-menu
    v-bind="$attrs"
    v-model="menuOpen"
    :close-on-content-click="false"
    width="492"
    data-testid="menu"
  >
    <template #activator="{ props, isActive }">
      <div class="d-flex">
        <v-btn
          class="rounded-e-0"
          color="primary"
          prepend-icon="auto_awesome"
          variant="outlined"
          @click="checkAndOpenMenu"
          data-testid="openBtn"
        >
          <span class="minsk-900">{{ t('labels.runAiModels') }}</span>
        </v-btn>
        <v-btn
          v-bind="props"
          class="border-s-0 rounded-s-0"
          color="primary"
          size="40"
          variant="outlined"
        >
          <v-icon :icon="isActive ? 'close' : 'arrow_drop_down'" />
        </v-btn>
      </div>
    </template>
    <ai-model-list
      data-testid="modelList"
      v-model:selected="selectedModels"
    />
  </v-menu>
  <AutoAnnotateModal v-model="loading" />
  <AnnotationGeneratedSnackbar v-model="s_annotate" />
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
import { useViewerStore } from '@/stores/viewer.store';
import { useI18n } from 'vue-i18n';

defineOptions({ inheritAttrs: false });

const { t } = useI18n();
const { options } = storeToRefs(useViewerStore());

const selectedModels = ref<string[]>([]);
const loading = ref<boolean>(false);
const s_annotate = ref<boolean>(false);
const done = ref<boolean>(false);
const menuOpen = ref(false);

async function checkAndOpenMenu(): Promise<void> {
  if (selectedModels.value.length === 0) {
    menuOpen.value = true;
  } else {
    await runAiModels();
  }
}

async function runAiModels(): Promise<void> {
  if (options.value.onRunAIModel) {
    loading.value = true;
    await options.value.onRunAIModel(selectedModels.value);
    setTimeout(() => {
      loading.value = false;
      done.value = true;
      s_annotate.value = true;
      selectedModels.value = [];
    }, 4000);
  }
}
defineExpose({
  menuOpen,
  selectedModels,
  runAiModels,
  done,
  loading,
  s_annotate,
  checkAndOpenMenu,
});
</script>
