<script setup>
import { useLayoutConfigStore } from "@layouts/stores/config";
import { useI18n } from "vue-i18n";
import { VDataTableServer } from "vuetify/lib/labs/VDataTable";
const ability = useAbility();
const { t } = useI18n();

const configStore = useLayoutConfigStore();

const formattedTime = (dateString) =>
  new Intl.DateTimeFormat("zh-tw", {
    year: "numeric",
    month: "long",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: true,
  }).format(new Date(dateString));

// 👉 headers
const headers = computed(() => {
  const baseHeaders = [
    { title: "ID", key: "id" },
    { title: "權限名稱", key: "name" },
    { title: "建立時間", key: "created_at", sortable: false },
    { title: "更新時間", key: "updated_at", sortable: false },
  ];

  // 如果用户具有创建权限的能力，则添加动作列
  if (ability.can("create", "admin")) {
    baseHeaders.push({ title: "動作", key: "actions", sortable: false });
  }

  return baseHeaders;
});
const search = ref("");
const itemsPerPage = ref(10);
const page = ref(1);
const sortBy = ref(null);
const orderBy = ref(null);
const updateSignal = ref(0);

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

const isPermissionDialogVisible = ref(false);
const isAddPermissionDialogVisible = ref(false);
const permissionName = ref("");
const selectedPermissionId = ref(null);
const isDeleteDialogVisible = ref(false);

const { data: permissionsData } = await useApi(
  createUrl("/account-panel/permissions", {
    query: {
      q: search,
      itemsPerPage,
      page,
      sortBy,
      orderBy,
      updateSignal,
    },
  })
);

const permissions = computed(() => permissionsData.value.data);
const totalPermissions = computed(() => permissionsData.value.total);

const openDialog = (permission, id, type) => {
  permissionName.value = permission;
  selectedPermissionId.value = id;
  type == "edit"
    ? (isPermissionDialogVisible.value = true)
    : (isDeleteDialogVisible.value = true);
};

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

<template>
  <VRow>
    <VCol cols="12">
      <h2 class="text-primary">
        {{ t(configStore.pageTitle) }}
      </h2>
    </VCol>

    <VCol cols="12">
      <VCard>
        <VCardText
          class="d-flex align-center justify-space-between flex-wrap gap-4"
        >
          <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: 5rem"
            @update:model-value="itemsPerPage = parseInt($event, 10)"
          />

          <div class="d-flex align-center gap-4 flex-wrap">
            <AppTextField
              v-model="search"
              placeholder="搜尋..."
              density="compact"
              style="inline-size: 12.5rem"
            />
            <VBtn
              density="default"
              @click="isAddPermissionDialogVisible = true"
            >
              新增權限
            </VBtn>
          </div>
        </VCardText>

        <VDivider />

        <VDataTableServer
          v-model:items-per-page="itemsPerPage"
          v-model:page="page"
          :items-length="totalPermissions"
          :items-per-page-options="[
            { value: 5, title: '5' },
            { value: 10, title: '10' },
            { value: -1, title: '$vuetify.dataFooter.itemsPerPageAll' },
          ]"
          :headers="headers"
          :items="permissions"
          class="text-no-wrap"
          @update:options="updateOptions"
        >
          <template #bottom>
            <VDivider />

            <div
              class="d-flex align-center justify-space-between flex-wrap gap-3 pa-5 pt-3"
            >
              <p class="text-sm text-medium-emphasis mb-0"></p>

              <VPagination
                v-model="page"
                :length="Math.ceil(totalPermissions / itemsPerPage)"
                :total-visible="
                  $vuetify.display.xs
                    ? 1
                    : Math.min(Math.ceil(totalPermissions / itemsPerPage), 5)
                "
              >
                <template #prev="slotProps">
                  <VBtn
                    variant="tonal"
                    color="default"
                    v-bind="slotProps"
                    :icon="false"
                  >
                    <VIcon icon="tabler-caret-left" size="20" />
                  </VBtn>
                </template>

                <template #next="slotProps">
                  <VBtn
                    variant="tonal"
                    color="default"
                    v-bind="slotProps"
                    :icon="false"
                  >
                    <VIcon icon="tabler-caret-right" size="20" />
                  </VBtn>
                </template>
              </VPagination>
            </div>
          </template>

          <template #item.created_at="{ item }">
            <span>{{ formattedTime(item.created_at) }}</span>
          </template>

          <template #item.updated_at="{ item }">
            <span>{{ formattedTime(item.updated_at) }}</span>
          </template>

          <!-- Actions -->
          <template #item.actions="{ item }">
            <VBtn
              icon
              size="small"
              color="medium-emphasis"
              variant="text"
              @click="openDialog(item.name, item.id, 'edit')"
            >
              <VIcon size="22" icon="tabler-edit" />
            </VBtn>
            <VBtn
              icon
              size="small"
              variant="text"
              color="medium-emphasis"
              @click="openDialog(item.name, item.id, 'delete')"
            >
              <VIcon size="22" icon="tabler-trash" />
            </VBtn>
          </template>
        </VDataTableServer>
      </VCard>
    </VCol>
  </VRow>
  <AddEditPermissionDialog
    v-model:isDialogVisible="isPermissionDialogVisible"
    v-model:permission-name="permissionName"
    v-model:permission-id="selectedPermissionId"
    @permission-updated="updateSignal++"
  />
  <AddEditPermissionDialog
    v-model:isDialogVisible="isAddPermissionDialogVisible"
    @permission-updated="updateSignal++"
  />
  <DeletePermissionDialog
    v-model:isDeleteDialogVisible="isDeleteDialogVisible"
    v-model:permission-name="permissionName"
    v-model:permission-id="selectedPermissionId"
    @permission-updated="updateSignal++"
  />
</template>
