<script setup>
import { ref } from "vue";
import { useLight } from "#imports";
import m from "../../composables/m";
const light = useLight();
const token = ref(null);
const expiresOptions = [
  { label: "7 \u65E5", value: 7 * 24 * 60 * 60 },
  { label: "30 \u65E5", value: 30 * 24 * 60 * 60 },
  { label: "3 \u500B\u6708", value: 90 * 24 * 60 * 60 },
  { label: "\u4E0D\u9650\u6642\u9593", value: 0 }
];
const onSubmit = async (data) => {
  token.value = null;
  try {
    const result = await m("createAccessToken", {
      name: data.name,
      expired_time: data.expired_time
    });
    token.value = result;
  } catch (e) {
    light.notify({ type: "negative", message: "\u5EFA\u7ACB\u5931\u6557" });
  }
};
const copyToken = () => {
  if (!token.value) return;
  navigator.clipboard.writeText(token.value);
  light.notify({ type: "positive", message: "\u5DF2\u8907\u88FD\u5230\u526A\u8CBC\u7C3F" });
};
const reset = () => {
  token.value = null;
};
</script>

<template>
    <l-page title="Create Access Token" :back-btn="true">
        <div style="max-width: 560px;">
            <form-kit type="l-form" :disabled="!!token" @submit="onSubmit">
                <form-kit type="l-input" name="name" label="Token Name" validation="required" />
                <form-kit type="l-select" name="expired_time" label="Expiration" :options="expiresOptions"
                    validation="required" />
            </form-kit>
        </div>

        <!-- Token result -->
        <q-card v-if="token" flat bordered class="q-pa-md q-mt-md" style="max-width: 560px;">
            <q-card-section>
                <div class="text-subtitle1 q-mb-sm text-positive">Token Created</div>
                <div class="text-caption text-grey q-mb-sm">Please copy and save this token immediately. It will only be
                    shown once.</div>
                <q-input :model-value="token" v-bind="light.styles.input" readonly type="textarea" autogrow>
                    <template #append>
                        <q-btn flat round icon="content_copy" @click="copyToken">
                            <q-tooltip>複製</q-tooltip>
                        </q-btn>
                    </template>
                </q-input>
            </q-card-section>
            <q-card-actions>
                <q-btn flat label="建立另一個" @click="reset" />
            </q-card-actions>
        </q-card>
    </l-page>
</template>
