<template>
  <v-menu data-testid="menu" v-model="menuState" location="top" :close-on-content-click="false">
    <template #activator="{ props: menu }">
      <Action v-bind="menu" :text="text" icon="360" :variant="variant" />
    </template>
    <v-card>
      <v-card-title class="text-body-1">
        <span>{{ text }}</span>
      </v-card-title>
      <v-card-text>
        <v-text-field data-testid="angle" v-model="angle" type="number" variant="outlined" suffix="deg" hide-details />
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn data-testid="rotate" color="primary" @click="rotate">
          <span>{{ t('labels.rotate') }}</span>
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-menu>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { RotationValue, ScanView } from '@3cr/types-ts';
import { useViewer3cr } from '@/composables/useViewer3cr';
import { useI18n } from 'vue-i18n';
import { useViewName } from '@/composables/useViewName';

interface Props {
  view: ScanView;
  variant?: 'button' | 'menu-item';
  modelValue?: boolean;
}

type Emits = {
  'update:modelValue': [value: boolean];
  'update:modal': [value: boolean];
};

const props = withDefaults(defineProps<Props>(), {
  variant: 'button'
});

const emit = defineEmits<Emits>();

const { t } = useI18n();
const { name } = useViewName(props.view);
const viewer3cr = useViewer3cr();

const menu = ref<boolean>(false);
const angle = ref<number>(0);

const text = computed(() => {
  return t('labels.rotateView', { view: name.value });
});

const menuState = computed({
  get(): boolean {
    return menu.value;
  },
  set(value: boolean): void {
    menu.value = value;
    emit('update:modal', value);
  }
});

async function rotate(): Promise<void> {
  const message: RotationValue = {
    Version: '0.0.0',
    View: props.view,
    Angle: angle.value
  };
  await viewer3cr.rotateByDeg({ message });
}
</script>
