<script setup>
import { defineProps } from 'vue';
import { useSlots } from "vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ActionSettingsWheelItem from "@/components/displays/buttons/ActionSettingsWheelItem.vue";
import Swal from "sweetalert2";
import { ref } from "vue";
import CustomerModal from "@/components/displays/modals/CustomerModal.vue";
import ActionSettingsWheelItemLabel from "@/components/displays/buttons/ActionSettingsWheelItemLabel.vue";

const props = defineProps({
  icon: {
    type: String,
    default: "fas fa-cog"
  },
  label: {
    type: String,
    default: ""
  },
  user_id: {
    type: Number,
    default: null
  },
  order_id: {
    type: Number,
    default: null
  },
  invoice_collection_id: {
    type: Number,
    default: null
  },
  reg_1: {
    type: String,
    default: null
  },
});

const customerModalVisible = ref(false);

const showSetCustomerPassword = (userId) => {
  Swal.fire({
    title: 'Skift kodeord',
    html: '<input id="swal-input1" class="swal2-input" placeholder="Indtast kodeord">',
    focusConfirm: false,
    preConfirm: () => {
      const password = document.getElementById('swal-input1').value;
      if (password === '') {
        Swal.showValidationMessage('Indtast venligst et kodeord');
      }
      return password;
    }
  }).then((result) => {
    if (result.isConfirmed) {
      const password = result.value;
      // Call the API to set the password
      SessionUser.request(
          '/superuser/user/password',
          'POST',
          {
            user_id: userId,
            password: password,
          }
      ).then(() => {
        Swal.fire({
          title: 'Kodeord ændret',
          text: 'Kodeordet er blevet ændret.',
          icon: 'success',
        });
      }).catch((error) => {
        Swal.fire({
          title: 'Fejl',
          text: 'Der opstod en fejl under ændring af kodeordet.',
          icon: 'error',
        });
      });
    }
  });
}

const redirectSuperUserInvoiceCollectionPage = (invoiceCollectionId) => {
  // Send the user to the invoice collection page (In a new tab)
  window.open(`/superuser/invoices/${invoiceCollectionId}`, '_blank');
};

const redirectDepartmentOrderPage = async (orderId) => {
  // Send the user to the order page (In a new tab)
  // Get the department id from the order
  await SessionUser.objects.orders.functions.get_department_id(props.order_id).then((response) => {
    // Get the department id from the response
    // Send the user to the order page (In a new tab)
    window.open(`/admin/${response}/modules/pos/orders/${orderId}`, '_blank');
  }).catch((error) => {
    console.error(error);
  });
};
</script>

<template>
  <div class="dropdown is-right is-hoverable">
    <div class="dropdown-trigger">
      <button class="button is-small is-dark" aria-haspopup="true" aria-controls="dropdown-menu">
                  <span class="icon">
                    <i :class="props.icon"></i>
                  </span>
        <span v-if="props.label.length > 0" class="ml-2">{{ props.label }}</span>
      </button>
    </div>
    <div class="dropdown-menu" id="dropdown-menu" role="menu">
      <div class="dropdown-content">
        <!-- Actions (If defined) -->
        <template v-if="useSlots().actions">
          <slot name="actions"></slot>
          <!-- If there's a user_id, show the user actions -->
          <template v-if="props.user_id">
            <!-- Label -->
            <ActionSettingsWheelItemLabel
                :label="SessionUser.objects.global.language.customer"
                v-show="SessionUser.canAccessSuperUser()"
            />
            <!-- Se bruger -->
            <ActionSettingsWheelItem
                label="Se kunde i ny fane"
                icon="fas fa-user-edit"
                :click-action="() => SessionUser.functions.redirectTo.superUser('/users/' + props.user_id, true)"
                v-if="SessionUser.canAccessSuperUser()"
            />
            <!-- Log ind som kunde -->
            <ActionSettingsWheelItem
                label="Log ind som kunde"
                icon="fas fa-user-shield"
                :click-action="() => SessionUser.superUser.intimidate.intimidateUser(props.user_id)"
                v-if="SessionUser.canAccessSuperUser()"
            />

            <!-- Set password -->
            <ActionSettingsWheelItem
                label="Skift kodeord"
                icon="fas fa-key"
                :click-action="() => showSetCustomerPassword(props.user_id)"
                v-if="SessionUser.canAccessSuperUser()"
            />
            <!-- Show customer modal -->
            <ActionSettingsWheelItem
                label="Vis kunde"
                icon="fas fa-user"
                :click-action="() => customerModalVisible = true"
                v-if="SessionUser.canAccessSuperUser()"
            />
          </template>
          <!-- If there's an order_id, show the order actions -->
          <template v-if="props.order_id">
            <!-- Label, only if the user is a superuser (Otherwise, the label is redundant) -->
            <action-settings-wheel-item-label
                :label="SessionUser.functions.ucFirst(SessionUser.objects.orders.meta.labels.single)"
                v-show="SessionUser.canAccessSuperUser()"
            />
            <!-- Go to the order page, in a new tab -->
            <action-settings-wheel-item
                v-if="SessionUser.canAccessAdmin() || SessionUser.canAccessSuperUser()"
                label="Se transaktion i ny fane"
                icon="fas fa-external-link-alt"
                :click-action="async () => redirectDepartmentOrderPage(props.order_id)"
                :disabled="false"
            />
            <!-- Go to the user/order/:order_id page, in a new tab -->
            <action-settings-wheel-item
                v-if="!SessionUser.canAccessAdmin() && !SessionUser.canAccessSuperUser()"
                label="Se transaktion i ny fane"
                icon="fas fa-external-link-alt"
                :click-action="() => SessionUser.functions.redirectTo.user('/orders/' + props.order_id, true)"
                :disabled="false"
                />
            <!-- Change the customer (of the order) -->
            <action-settings-wheel-item
                v-if="SessionUser.canAccessSuperUser()"
                label="Skift kunde"
                icon="fas fa-user-edit"
                :click-action="() => SessionUser.objects.orders.functions.showChangeCustomerForm(props.order_id)"
                :disabled="false"
            />
            <!-- Change the invoice collection (of the order) -->
            <action-settings-wheel-item
                v-if="SessionUser.canAccessSuperUser()"
                label="Skift faktura samling"
                icon="fas fa-file-invoice-dollar"
                :click-action="() => SessionUser.objects.orders.functions.showChangeInvoiceCollectionForm(props.order_id)"
                :disabled="false"
            />
          </template>
          <!-- If there is an invoice collection id, show the invoice actions -->
          <template v-if="props.invoice_collection_id">
            <!-- Label -->
            <action-settings-wheel-item-label
              :label="SessionUser.objects.collectedOrderInvoices.meta.title"
              v-show="SessionUser.canAccessSuperUser()"
            />
            <!-- Show the invoice collection, in a new tab -->
            <action-settings-wheel-item
                v-if="SessionUser.canAccessSuperUser()"
                label="Vis faktura samling i ny fane"
                icon="fas fa-file-invoice-dollar"
                :click-action="() => redirectSuperUserInvoiceCollectionPage(props.invoice_collection_id)"
            />
          </template>
          <!-- If there is a reg_1, show the reg_1 actions -->
          <template v-if="props.reg_1">
            <!-- Label -->
            <action-settings-wheel-item-label
                :label="SessionUser.objects.vehicles.meta.labels.single"
                v-show="SessionUser.canAccessSuperUser()"
            />
            <!-- Show the vehicle, in a new tab -->
            <action-settings-wheel-item
                label="Vis køretøj i ny fane"
                icon="fas fa-car"
                v-if="SessionUser.canAccessSuperUser()"
                :click-action="() => SessionUser.functions.redirectTo.superUser('/vehicles/' + props.reg_1, true)"
            />
          </template>
        </template>
        <!-- If no actions are defined, then show that no actions are defined -->
        <template v-else>
          <div class="dropdown-item">
            <p class="has-text-centered">Ingen handlinger defineret</p>
          </div>
        </template>
      </div>
    </div>
    <CustomerModal
        v-if="customerModalVisible"
        :user_id="props.user_id"
        @closeModal="customerModalVisible = false"
    />
  </div>
</template>

<style scoped>

</style>