<script setup>
import { useLayoutConfigStore } from "@layouts/stores/config";
import { debounce } from "lodash";
import { useI18n } from "vue-i18n";
import { VDataTableServer } from "vuetify/lib/labs/VDataTable";
const { t } = useI18n();
const configStore = useLayoutConfigStore();
const userData = useCookie("userData").value;

// 👉 Store
const searchQuery = ref("");
const selectedRole = ref();
const selectedDept = ref(userData.deptNo);
const selectedStatus = ref();
const currentRoleList = ref([]);

// Data table options
const itemsPerPage = ref(10);
const page = ref(1);
const sortBy = ref();
const orderBy = ref();

const updateOptions = (options) => {
  page.value = options.page;
  sortBy.value = options.sortBy[0]?.key;
  orderBy.value = options.sortBy[0]?.order;
};

// Headers
const headers = [
  {
    title: "工號",
    key: "UserID",
    width: "5%",
  },
  {
    title: "姓名",
    key: "UserName",
    width: "8%",
  },
  {
    title: "部門",
    key: "DeptName",
    width: "15%",
  },
  {
    title: "角色",
    key: "roles",
  },
];

const { data: usersData, execute: fetchUsers } = await useApi(
  createUrl("/account-panel/users", {
    query: {
      q: searchQuery,
      Disabled: selectedStatus,
      DeptNo: selectedDept,
      role: selectedRole,
      itemsPerPage,
      page,
      sortBy,
      orderBy,
    },
  })
);

const users = computed(() => usersData.value.data);
const totalUsers = computed(() => usersData.value.total);
const rolesData = ref([]);
const deptsData = ref([]);
const currentUserId = ref("");

const fetchRoles = async () => {
  const response = await useApi(createUrl("/account-panel/roles"));
  rolesData.value = response.data.value.map((role) => ({
    title: role.alias,
    value: role.name,
  }));
};

const fetchDepts = async () => {
  const response = await useApi(createUrl("/account-panel/departments"));
  deptsData.value = response.data.value.departments.map((dept) => ({
    title: dept.DeptName,
    value: dept.DeptNo,
  }));
};

// 在 created 或 mounted 鉤子中調用 fetchRoles 以填充 roles 數據
fetchRoles();
fetchDepts();

const Disabled = [
  {
    title: "啟用",
    value: "0",
  },
  {
    title: "禁用",
    value: "1",
  },
];

const resolveUserRoleVariant = (role) => {
  const roleLowerCase = role.toLowerCase();
  if (roleLowerCase.includes("user"))
    return {
      color: "primary",
      icon: "tabler-user",
    };
  if (roleLowerCase.includes("senior"))
    return {
      color: "error",
      icon: "tabler-device-desktop",
    };
  if (roleLowerCase.includes("editor"))
    return {
      color: "warning",
      icon: "tabler-edit",
    };
  if (roleLowerCase === "manager")
    return {
      color: "success",
      icon: "tabler-user-cog",
    };
  if (roleLowerCase === "admin")
    return {
      color: "#A020F0",
      icon: "tabler-crown",
    };

  return {
    color: "primary",
    icon: "tabler-user",
  };
};

const isEditUserVisible = ref(false);
const debouncedFetchUsers = debounce(fetchUsers, 500);

watch(
  selectedRole,
  (newValue) => {
    if (!newValue) {
      selectedRole.value = undefined;
    }
    debouncedFetchUsers();
  },
  { immediate: true }
);

watch(
  selectedDept,
  (newValue) => {
    if (!newValue) {
      selectedDept.value = undefined;
    }
    debouncedFetchUsers();
  },
  { immediate: true }
);

watch(
  selectedStatus,
  (newValue) => {
    if (!newValue) {
      selectedStatus.value = undefined;
    }
    debouncedFetchUsers();
  },
  { immediate: true }
);

const openDialog = (userIdParam, roles) => {
  currentUserId.value = userIdParam;
  currentRoleList.value = roles.map((role) => ({
    title: role.alias,
    value: role.name,
  }));

  isEditUserVisible.value = true;
};

const transformRoleName = (roleName) => {
  const role = rolesData.value.find((role) => role.value === roleName);
  return role ? role.title : roleName; // If the role is found, return its alias (title)
};

definePage({
  meta: {
    action: "read",
    subject: "permission",
  },
});
</script>

<template>
  <section>
    <VCol cols="12">
      <h2 class="text-primary">
        {{ t(configStore.pageTitle) }}
      </h2>
    </VCol>
    <VCard title="篩選" class="mb-6">
      <VCardText>
        <VRow>
          <!-- 👉 Select Role -->
          <VCol cols="12" sm="4">
            <AppSelect
              v-model="selectedRole"
              placeholder="選擇角色"
              :items="rolesData"
              clearable
              clear-icon="tabler-x"
            />
          </VCol>
          <!-- 👉 Select Plan -->
          <VCol cols="12" sm="4">
            <AppSelect
              v-model="selectedDept"
              placeholder="選擇部門"
              :items="deptsData"
              clearable
              clear-icon="tabler-x"
            />
          </VCol>
          <!-- 👉 Select Disabled -->
          <VCol cols="12" sm="4">
            <AppSelect
              v-model="selectedStatus"
              placeholder="選擇狀態"
              :items="Disabled"
              clearable
              clear-icon="tabler-x"
            />
          </VCol>
        </VRow>
      </VCardText>
      <VDivider />
      <VCardText class="d-flex flex-wrap py-4 gap-4">
        <div class="me-3 d-flex gap-3">
          <AppSelect
            :model-value="itemsPerPage"
            :items="[
              { value: 10, title: '10' },
              { value: 25, title: '25' },
              { value: 50, title: '50' },
              { value: 100, title: '100' },
              { value: -1, title: 'All' },
            ]"
            style="inline-size: 6.25rem"
            @update:model-value="itemsPerPage = parseInt($event, 10)"
          />
        </div>
        <VSpacer />

        <div class="app-user-search-filter d-flex align-center flex-wrap gap-4">
          <!-- 👉 Search  -->
          <div style="inline-size: 10rem">
            <AppTextField
              v-model="searchQuery"
              placeholder="搜尋..."
              density="compact"
            />
          </div>
        </div>
      </VCardText>

      <VDivider />

      <!-- SECTION datatable -->
      <VDataTableServer
        v-model:items-per-page="itemsPerPage"
        v-model:page="page"
        :items="users"
        :items-length="totalUsers"
        :headers="headers"
        class="text-no-wrap"
        @update:options="updateOptions"
      >
        <!-- 👉 Role -->
        <template #item.roles="{ item }">
          <div class="d-flex align-items-center gap-2 flex-wrap">
            <VBtn
              v-if="$ability.can('create', 'permission')"
              icon
              size="24"
              color="medium-emphasis"
              variant="text"
              @click="openDialog(item.UserID, item.roles)"
            >
              <VIcon size="24" icon="tabler-edit" />
            </VBtn>
            <template v-for="role in item.roles" :key="role.id">
              <VChip
                :color="resolveUserRoleVariant(role.name).color"
                size="small"
                label
                class="text-capitalize"
              >
                <VIcon
                  :icon="resolveUserRoleVariant(role.name).icon"
                  left
                ></VIcon>
                {{ transformRoleName(role.name) }}
              </VChip>
            </template>
          </div>
        </template>

        <template #item.DeptName="{ item }">
          <div class="truncate">
            {{ item.DeptName }}
          </div>
        </template>

        <!-- pagination -->
        <template #bottom>
          <VDivider />
          <VCardText class="pt-2">
            <div
              class="d-flex flex-wrap justify-center justify-sm-space-between gap-y-2 mt-2"
            >
              <span class="pt-3">共計 {{ totalUsers }} 名用戶</span>

              <VPagination
                v-model="page"
                :total-visible="$vuetify.display.smAndDown ? 5 : 7"
                :length="Math.ceil(totalUsers / itemsPerPage)"
              />
            </div>
          </VCardText>
        </template>
      </VDataTableServer>
      <!-- SECTION -->
    </VCard>
    <!-- 👉 Add New User -->
    <EditUserDialog
      v-model:isDialogVisible="isEditUserVisible"
      v-model:user-id="currentUserId"
      v-model:current-role-list="currentRoleList"
      v-model:role-list="rolesData"
      @user-roles-updated="debouncedFetchUsers"
    />
  </section>
</template>
<style lang="scss">
.truncate {
  overflow: hidden;
  max-inline-size: 150px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
