<script setup>
const props = defineProps({
  isDialogVisible: {
    type: Boolean,
    required: true,
  },
  permissionId: {
    type: Number,
    required: false,
    default: 0,
  },
  permissionName: {
    type: String,
    required: false,
    default: "",
  },
});

const emit = defineEmits(["update:isDialogVisible", "update:permissionName"]);

const currentPermissionName = ref("");

const onReset = () => {
  emit("update:isDialogVisible", false);
  currentPermissionName.value = "";
};

const onSubmit = async () => {
  const apiEndpoint = props.permissionId
    ? `/account-panel/permissions/${props.permissionId}`
    : "/account-panel/permissions";

  const method = props.permissionName ? "put" : "post";
  try {
    const response = await $api(apiEndpoint, {
      method: method,
      body: {
        name: currentPermissionName.value,
      },
    });

    emit("update:isDialogVisible", false);
    emit("permission-updated");
  } catch (error) {
    console.error(error);
  }
};

watch(props, () => {
  currentPermissionName.value = props.permissionName;
});
</script>

<template>
  <VDialog
    :width="$vuetify.display.smAndDown ? 'auto' : 600"
    :model-value="props.isDialogVisible"
    @update:model-value="onReset"
  >
    <!-- 👉 dialog close btn -->
    <DialogCloseBtn @click="onReset" />

    <VCard class="pa-sm-8 pa-5">
      <!-- 👉 Title -->
      <VCardItem class="text-center">
        <VCardTitle class="text-h5">
          {{ props.permissionName ? "編輯" : "新增" }}權限
        </VCardTitle>
        <VCardSubtitle>
          根據您的需求{{ props.permissionName ? "編輯" : "新增" }}權限
        </VCardSubtitle>
      </VCardItem>

      <VCardText class="mt-1">
        <!-- 👉 Form -->
        <VForm>
          <VAlert type="warning" title="警告!" variant="tonal" class="mb-6">
            編輯權限名稱可能會破壞系統權限的功能。請在進行前確保您已經完全確定。
          </VAlert>

          <!-- 👉 Role name -->
          <div class="d-flex align-end gap-3 mb-3">
            <AppTextField
              v-model="currentPermissionName"
              density="compact"
              label="權限(action subject)"
              placeholder="action subject"
            />

            <VBtn @click="onSubmit"> 更新 </VBtn>
          </div>
          <!-- 
          <VCheckbox label="Set as core permission" /> -->
        </VForm>
      </VCardText>
    </VCard>
  </VDialog>
</template>

<style lang="scss">
.permission-table {
  td {
    border-block-end: 1px solid
      rgba(var(--v-border-color), var(--v-border-opacity));
    padding-block: 0.5rem;
    padding-inline: 0;
  }
}
</style>
