<template>
  <div class="dashboard-header box-shadow">
    <img 
      src="@/assets/images/logo-pajakio.png" 
      alt="logo-pajak_io" 
      class="cursor-pointer"
      @click="actionRoute('home')"
    />
    <dropdown-company
      v-if="showCompany"
      :options="companyList"
      style="width: 100%; max-width: 350px"
      id="select-company-navbar"
      :onChange="setSelectedCompany"
      cardStyle
      :searchAble="['companyName', 'companyNpwp']"
      emptyListMsg="Perusahaan tidak ditemukan"
    >
      <template v-slot:list="{ item }">
        <p
          class="text-regular mb-1 break-words"
          style="color: #505154; font-weight: bold"
        >
          {{ item.companyName }}
        </p>
        <p class="text-regular">
          {{ item.companyNpwp }}
        </p>
      </template>
      <template v-slot:label="slotProps">
        <div
          class="flex flex-row justify-content-between items-center"
        >
          <div class="w-full">
            <p
              class="text-regular break-words"
              style="color: #14375e; font-weight: bold"
            >
              {{ selectedCompany.companyName }}
            </p>
            <p class="text-regular">
              {{ selectedCompany.companyNpwp }}
            </p>
          </div>
          <svg
            style="transition: all 0.3s ease; margin-left: 24px"
            xmlns="http://www.w3.org/2000/svg"
            height="24"
            viewBox="0 0 24 24"
            width="24"
            :transform="slotProps.opened ? 'rotate(180)' : ''"
          >
            <path
              d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"
            />
            <path d="M0 0h24v24H0V0z" fill="none" />
          </svg>
        </div>
      </template>
    </dropdown-company>
    <div class="action-menu" >
      <div 
        class="initial-name cursor-pointer"
        @click="show = !show"
      >{{ initialName }}</div>
      <base-icon
        iconName="expand_more"
        class="ml-1 cursor-pointer"
        @click="show = !show"
      />
      <div 
        v-if="show"
        class="
          flex
          relative
        "
      >
        <div 
          class="
            box-shadow
            absolute top-30 right-0
            bg-white
            w-250
            z-2"
        >
          <div class="flex flex-col">
            <div 
              class="flex flex-col p-3"
              style="border-bottom: 1px solid #DDDDDD;"
            >
              <div class="flex flex-row items-center mb-4">
                <div class="initial-name mr-3">{{ initialName }}</div>
                <div>
                  <typo-text variant="body-1-bold" class="capitalize">
                    {{this.userName}}
                  </typo-text>
                  <typo-text v-if="this.userEmail" variant="body-2-regular" color="#A9B0B8">
                    {{this.userEmail}}
                  </typo-text>
                </div>
              </div>
              <base-button 
                variant="secondary" 
                class="justify-center"
                @click="actionRoute('edit-profile')"
              >
                Ubah Profil
              </base-button>
            </div>
            <div class="flex flex-col">
              <div
                v-for="(item, index) in menuNavbar"
                :key="index"
                class="p-4 cursor-pointer item-menu"
                @click="actionRoute(item.slug)"
              >
                <base-icon
                  v-if="item.icon"
                  :iconName="item.icon" 
                  class="mr-2"
                /> {{item.name}}
              </div>
            </div>
          </div>
        </div>
        <div 
          class="
            w-full h-screen
            fixed top-0 left-0
            z-1
          "
        @click="show = !show"
        >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BaseIcon from "@/components/Base/BaseIcon";
import DropdownCompany from "@/components/Dropdown/DropdownCompany";
import TypoText from "@/components/Typography/TypoText";
import BaseButton from "@/components/Base/BaseButton";
import Cookies from "js-cookie";

export default {
  components: {
    BaseIcon,
    DropdownCompany,
    TypoText,
    BaseButton
  },
  props: {
    menuNavbar: {
      type: Object,
    },
    showCompany: {
      type: Boolean,
    },
    name: {
      type: [String],
    },
    companyList: {
      type: [Array, Function],
      default: () => [],
    },
    selectedCompany: {
      type: [Object],
    },
    userName: {
      type: [String],
      default: "",
    },
    userEmail: {
      type: [String],
      default: "",
    },
    moduleApp: {
      type: [String],
      default: "http://my.staging.pajak.io/",
    },
    apiApp: {
      type: [String],
      default: "http://api.staging.pajak.io/",
    }
  },
  data() {
    return {
      show: false,
      logoutTimeout: null,
    };
  },
  computed: {
    initialName() {
      let initials;
      let fullName = this.userName.split(" ");
      if (this.userName) {
        if (fullName.length > 1) {
          initials = fullName.shift().charAt(0) + fullName.pop().charAt(0);
        } else {
          initials = fullName.shift().slice(0, 2);
        }
        initials = initials.toUpperCase();
      }
      return initials;
    },
  },
  watch: {
    selectedCompany() {
      this.setLogoutTimer()
    }
  },
  mounted() {
    document.addEventListener('mousemove', () => {
      clearTimeout(this.logoutTimeout)
      this.setLogoutTimer()
    });
  },
  methods: {
    actionRoute(value){
      this.$emit("actionRoute", value)
      this.show = false
    },
    setSelectedCompany(value) {
      this.$emit("setSelectedCompany", value)
    },
    formatNpwp(val) {
      if (!val) return "";
      return val.replace(
        /(\d{2})(\d{3})(\d{3})(\d{1})(\d{3})(\d{3})/,
        "$1.$2.$3.$4-$5.$6"
      );
    },
    async logout(isAuto = false, shouldEmit = false) {
      this.show = false
      if (shouldEmit) {
        this.$emit("actionRoute", "logout")
      }
      clearTimeout(this.logoutTimeout)
      try {
        await this.requestSignOut()
      } catch (error) {
        console.error("Failed to call signout API", error)
      } finally {
        this.clearSession(isAuto)
      }
    },
    async requestSignOut() {
      const token = this.getAuthToken()
      if (!token) return

      const authHeader = token.startsWith("Bearer ") ? token : `Bearer ${token}`
      const baseUrl = this.apiApp.endsWith("/") ? this.apiApp : `${this.apiApp}/`
      const url = `${baseUrl}users/signout`

      await fetch(url, {
        method: "POST",
        headers: {
          Authorization: authHeader,
        },
      })
    },
    getAuthToken() {
      const cookieValue = Cookies.get("pajakio")
      if (!cookieValue) return ""

      try {
        const parsedCookie = JSON.parse(cookieValue)
        return (
          parsedCookie.token ||
          parsedCookie.accessToken ||
          parsedCookie.authorization ||
          cookieValue
        )
      } catch (error) {
        return cookieValue
      }
    },
    clearSession(isAuto = false) {
      Cookies.remove("pajakio");
      Cookies.remove("expired-token-pajakio");
      Cookies.remove("lastSelectedCompany");
      const redirectPath = this.$route && this.$route.href ? this.$route.href.slice(1) : "";
      const baseUrl = this.moduleApp.endsWith("/") ? this.moduleApp : `${this.moduleApp}/`
      window.location.href = `${baseUrl}login?logoutTimer=${isAuto}&redirect=${redirectPath}`;
    },
    setLogoutTimer() {
      if (this.selectedCompany.logoutTimer) {
        this.logoutTimeout = setTimeout(() => {
          this.logout(true)
        }, this.selectedCompany.logoutTimer);
      } else {
        clearTimeout(this.logoutTimeout)
      }
    }
  },
};
</script>

<style lang="scss">
@use "@/assets/style/_color.scss" as *;

.dashboard-header {
  position: relative;
  width: 100%;
  background: $neutral-0;
  padding: 0 25px;
  min-height: 95px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .select-box {
    max-width: 249px;
    font-size: 12px;
    font-weight: bold;

    svg {
      height: 24px;
      width: 24px;
    }

    &__current {
      box-shadow: none;
    }

    &__input {
      &:checked + .select-box__input-text {
        display: flex;
        flex-flow: column;
      }
    }

    &__list {
      min-width: max-content;
    }

    &__item-name {
      padding-left: 20px;
    }
  }

  .action-menu {
    display: flex;
    align-items: center;
    position: relative;

    .body-1-bold {
      line-height: normal;
    }

    .initial-name {
      height: 40px;
      width: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      font-size: 14px;
      color: $neutral-0;
      background: $clear-blue-4;
    }

    .item-menu {
      background: #FFFFFF;
      display: flex;
      align-items: center;

      &:hover {
        background-color: rgba(62, 125, 192, 0.2);
      }
    }
  }

  .active {
    svg {
      transform: rotate(180deg);
    }
  }
}
</style>
