<script setup>
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import UserDashboardPageWrapper from "@/views/dashboards/userDashboard/UserDashboardPageWrapper.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import ConfigurationSelect from "@/components/displays/superuser/configuration/ConfigurationSelect.vue";
import ConfigurationInput from "@/components/displays/superuser/configuration/ConfigurationInput.vue";

import {ref} from 'vue';
import Swal from "sweetalert2";
import MicrosoftAuthenticationBox
  from "@/views/dashboards/userDashboard/profile/displays/MicrosoftAuthentication/MicrosoftAuthenticationBox.vue";
import ShowErrorField from "@/components/global/ShowErrorField.vue";
import { parseError, removeError, addError } from "@/components/request/HandleGlobalError.vue";

const isLoading = ref(false);

const onClickSaveEmail = async () => {
  // Get the password from Swal
  await Swal.fire({
    title: 'Indtast din adgangskode',
    input: 'password',
    inputPlaceholder: 'Adgangskode',
    showCancelButton: true,
    preConfirm: () => {
      const value = Swal.getInput().value;
      if (!value) {
        Swal.showValidationMessage('Indtast venligst din adgangskode 1');
        return;
      }
      Swal.showLoading();
      return value;
    },
    inputAttributes: {
      'aria-label': 'Adgangskode',
    },
    inputValidator: async (value) => {
      if (!value) {
        return 'Indtast venligst din adgangskode 2';
      }
      // Validate the password
      await SessionUser.request(
          '/account/security/validate-password',
          'POST',
          {
            password: value,
          }
      ).then((result) => {
        if (result.status === 200) {
          // Show the email input dialog
          onSaveEmail(value);
        } else {
          Swal.fire({
            title: 'Fejl',
            text: 'Der opstod en fejl under validering af adgangskoden.',
            icon: 'error',
          })
        }
      }).catch((error) => {
        Swal.fire({
          title: 'Fejl',
          text: SessionUser.functions.parseErrorMessage(error),
          icon: 'error',
        });
      }).finally(() => {
        isLoading.value = false;
      });
    },
    allowOutsideClick: () => !Swal.isLoading(),
    showLoaderOnConfirm: true,
  })
}
const onSaveEmail = async (password) => {
  // Show the confirmation dialog
  await Swal.fire({
    title: 'Hvilken e-mailadresse vil du bruge?',
    text: 'Indtast venligst din nye e-mailadresse.',
    icon: 'warning',
    input: 'text',
    inputLabel: 'E-mailadresse',
    showCancelButton: true,
    preConfirm: () => {
      const value = Swal.getInput().value;
      if (!value) {
        Swal.showValidationMessage('Indtast venligst din e-mailadresse');
        return;
      }
      // Validate the email address
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(value)) {
        Swal.showValidationMessage('Indtast venligst en gyldig e-mailadresse');
        return;
      }
      isLoading.value = true;
      Swal.showLoading();
      SessionUser.request(
          '/account/security/change-email',
          'POST',
          {
            email: value,
            password: password,
          }
      ).then((result) => {
        if (result.status === 200) {
          Swal.fire({
            title: 'E-mailadresse gemt',
            text: 'Din e-mailadresse er blevet gemt.',
            icon: 'success',
          });
          SessionUser.getSessionData();
        } else {
          Swal.fire({
            title: 'Fejl',
            text: 'Der opstod en fejl under gemme af e-mailadressen.',
            icon: 'error',
          });
        }
      }).catch((error) => {
        Swal.fire({
          title: 'Fejl',
          text: SessionUser.functions.parseErrorMessage(error),
          icon: 'error',
        });
        // Reset the password
      }).finally(() => {
        isLoading.value = false;
      });
    },
  })
}

const defaultDepartment = ref(null);
const departmentOptions = ref([]);
const getDefaultDepartment = async () => {
  // Clear error field
  removeError('error_default_department');
  // Check if the user has a customer number
  //console.log('Check if user has customer number', SessionUser.user.customer_number);
  if (!SessionUser.user.customer_number) {
    defaultDepartment.value = null;
    addError('Du har ikke et kundenummer, du kan derfor ikke vælge en standard afdeling.', 'error_default_department');
  } else {
    // Get the default department for the user
    await SessionUser.request(
        '/customer/department/default',
        'GET',
    ).then((response) => {
      const responseData = response.data.data;
      //console.log(responseData, 'Default department');
      defaultDepartment.value = responseData.department;
    }).catch((error) => {
      parseError(error, 'error_default_department');
      console.error(error);
    });
  }
}
const deleteDefaultDepartment = async () => {
  // Remove any existing error
  removeError('error_default_department');
  // Check if the customer number is 0
  if (!SessionUser.user.customer_number) {
    addError('Du har ikke et kundenummer, du kan derfor ikke vælge en standard afdeling.', 'error_default_department');
  } else {
    // Delete the default department for the user
    await SessionUser.request(
        '/customer/department/default',
        'DELETE',
    ).then(() => {
      //console.log(response.data.data, 'Deleted default department');
      defaultDepartment.value = null;
    }).catch((error) => {
      parseError(error, 'error_default_department');
    });
  }
}
const setDefaultDepartment = async (value) => {
  // Remove any existing error
  removeError('error_default_department');
  // Check if the customer number is 0
  if (!SessionUser.user.customer_number) {
    addError('Du har ikke et kundenummer, du kan derfor ikke vælge en standard afdeling.', 'error_default_department');
  } else {
    // Check if the user already has a default department (if so, delete it first)
    if (defaultDepartment.value) {
      await deleteDefaultDepartment();
    }
    // Set the default department for the user
    await SessionUser.request(
        '/customer/department/default',
        'POST',
        {
          department: value,
        }
    ).then((response) => {
      const responseData = response.data.data;
      //console.log(responseData, 'Set default department');
      defaultDepartment.value = responseData.department;
    }).catch((error) => {
      parseError(error, 'error_default_department');
    });
  }
}
const getDepartmentOptions = async () => {
  // Get the department options for the user
  await SessionUser.objects.departments.get.all().then((departments) => {
    departmentOptions.value = departments.map((department) => {
      return {
        label: department.name,
        value: department.id,
      }
    });
  }).catch((error) => {
    Swal.fire({
      title: 'Fejl',
      text: SessionUser.functions.parseErrorMessage(error),
      icon: 'error',
    });
  });
}
getDefaultDepartment();
getDepartmentOptions();



</script>

<template>
  <div v-if="!isLoading">
    <UserDashboardPageWrapper title="Brugerprofil">
      <!-- Invoicing -->
      <ConfigurationCategory
          class="mt-2"
          module="Brugerprofil"
          title="Fakturaoplysninger"
          description="Dine fakturaoplysninger"
          icon="fas fa-user"
      >
        <!-- Konto navn -->
        <ConfigurationInput
            :title="SessionUser.objects.global.language.customer_name"
            description="Kundekonto navn"
            v-bind:value="SessionUser.user.display_name"
            :disabled="true"
        />
        <!-- Konto nummer -->
        <ConfigurationInput
            :title="SessionUser.objects.global.language.customer_number"
            description="Kundekonto nummer"
            v-bind:value="SessionUser.user.customer_number"
            :disabled="true"
        />
      </ConfigurationCategory>
      <!-- Security -->
      <ConfigurationCategory
          class="mt-2"
          module="Brugerprofil"
          title="Sikkerhed"
          description="Dine sikkerhedsindstillinger"
          icon="fas fa-lock"
      >
        <!-- E-mail -->
        <ConfigurationInput
            :title="SessionUser.objects.global.language.email"
            description="Vi bruger denne e-mail til at nulstille din adgangskode"
            v-bind:value="SessionUser.user.email"
            :disabled="true"
        />
        <button
            class="button is-link is-small mt-2"
            @click="onClickSaveEmail"
            :disabled="isLoading"
        >
          <span>
            <i class="fas fa-edit"></i>
            <span class="ml-2">Rediger e-mail</span>
          </span>
        </button>
        <!-- Telefonnummer -->
        <ConfigurationInput
            :title="SessionUser.objects.global.language.phone_number"
            description="Telefonnummer"
            v-bind:value="SessionUser.user.phone.phone"
            :disabled="true"
        />
      </ConfigurationCategory>
      <!-- Microsoft -->
      <ConfigurationCategory
          class="mt-2"
          module="Brugerprofil"
          title="Microsoft"
          description="Dine Microsoft indstillinger"
          icon="fab fa-microsoft"
      >
        <MicrosoftAuthenticationBox/>
      </ConfigurationCategory>
      <!-- Default department -->
      <ConfigurationCategory
          v-if="SessionUser.user.customer_number.value > 0"
          class="mt-2"
          module="Brugerprofil"
          title="Standard afdeling"
          description="Din standard afdeling"
          icon="fas fa-building"
      >
        <ConfigurationSelect
            :icon="SessionUser.objects.departments.meta.icon"
            :title="SessionUser.objects.departments.meta.labels.single"
            v-bind:value="defaultDepartment"
            :options="departmentOptions"
            :on-select="(value) => setDefaultDepartment(value)"
            v-bind:disabled="SessionUser.user.customer_number.value === 0"
        >
          <template #after-select>
            <ShowErrorField error="error_default_department"/>
          </template>
        </ConfigurationSelect>
      </ConfigurationCategory>
    </UserDashboardPageWrapper>
  </div>
</template>

<style scoped>

</style>