<template>
  <div class="min-h-screen bg-base-100 p-4 md:p-6">
    <BreadcrumbHeader />

    <div class="max-w-3xl mx-auto">
      <div class="mb-6 text-center md:text-left">
        <h1 class="text-2xl font-semibold text-base-content">
          Create New Token
        </h1>
        <p class="text-sm text-base-content/70 mt-1">
          Enter the token's details below.
        </p>
      </div>

      <div v-if="error" role="alert" class="alert shadow-lg bg-rose-100">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current" fill="none" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <div>
          <span>Error! {{ error }}</span>
        </div>
        <button class="btn btn-sm" @click="error = null">X</button>
      </div>

      <div class="card border border-base-300/40 shadow-sm">
        <form @submit.prevent="createToken" class="card-body space-y-5">
          <div class="space-y-4">
            <h2 class="text-base font-medium text-base-content border-b border-base-300/30 pb-2 mb-4">
              Basic Information
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-4">
              <div class="form-control">
                <label for="username" class="label">
                  <span class="label-text">
                    Name <span class="text-red-500">*</span>
                  </span>
                </label>
                <input id="username" type="text" v-model="newToken.name" placeholder="Select a username"
                  class="input input-sm input-bordered w-full" required />
              </div>

              <div class="form-control">
                <label for="password" class="label">
                  <span class="label-text">
                    Key
                  </span>
                </label>
                <div class="relative">
                  <input id="password" :type="isPasswordVisible ? 'text' : 'password'" v-model="newToken.key"
                    class="input input-sm input-bordered w-full" />
                  <button type="button" @click="togglePasswordVisibility"
                    class="absolute inset-y-0 right-0 px-3 flex items-center text-base-content/60 hover:text-base-content/80 focus:outline-none focus:ring-0 rounded-r-md"
                    id="password-visibility-toggle">

                    <template v-if="!isPasswordVisible">
                      <EyeOff class="w-5 h-5" />
                    </template>
                    <template v-else>
                      <Eye class="w-5 h-5" />
                    </template>

                  </button>
                </div>
              </div>

            </div>
          </div>

          <div class="collapse collapse-arrow">
            <input type="checkbox" v-model="showAdvancedOptions" value="false" class="min-h-0 py-2" />
            <div class="collapse-title text-base font-medium min-h-0 py-1 px-0">
              Advanced Options
            </div>
            <div class="collapse-content px-0">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-4 pt-3">
                <div class="form-control">
                  <label class="label label-text text-xs">Expired at</label>
                  <div class="flex items-center space-x-3">
                    <input type="date" v-model="newToken.format_expired_at" class="input input-bordered input-sm w-full"
                      placeholder="年/月/日"  :disabled="newToken.never_expired"/>
                    <label class="flex items-center space-x-2 cursor-pointer whitespace-nowrap">
                      <input type="checkbox" v-model="newToken.never_expired" class="checkbox checkbox-sm" />
                      <span class="text-sm text-base-content/90">Never</span>
                    </label>
                  </div>
                </div>
                
                <div class="form-control">
                  <label for="quota" class="label">
                    <span class="label-text">Quota</span>
                  </label>
                  <div class="flex items-center space-x-3">
                    <input id="quota" type="number" v-model="newToken.quota" placeholder="Enter quota amount"
                      class="input input-sm input-bordered flex-grow" :disabled="newToken.unlimited_quota" />
                    <label class="flex items-center space-x-2 cursor-pointer whitespace-nowrap">
                      <input type="checkbox" v-model="newToken.unlimited_quota" class="checkbox checkbox-sm" />
                      <span class="text-sm text-base-content/90">Unlimited</span>
                    </label>
                  </div>
                </div>

                <div class="md:col-span-2 form-control">
                  <label class="label">
                    <span class="label-text">Status</span>
                  </label>
                  <div class="flex items-center space-x-3 h-9">
                    <input type="checkbox" v-model="newToken.active"
                      :class="`toggle toggle-sm ${newToken.active ? 'toggle-success' : 'toggle-error'}`" />
                    <span class="text-sm text-base-content/90">
                      {{ newToken.active ? 'Active' : 'Inactive' }}
                    </span>
                  </div>
                </div>
                
              </div>
            </div>
          </div>

          <div class="flex justify-end pt-4 gap-5">
            <button type="button" class="btn btn-outline btn-error btn-sm h-9 px-4 text-sm font-medium" @click="cancel">
              Cancel
            </button>
            <button type="submit" class="btn btn-outline btn-sm h-9 px-4 text-sm font-medium" :disabled="!isFormValid">
              Create
            </button>
          </div>
        </form>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject ,watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import BreadcrumbHeader from '@/components/dashboard/BreadcrumbHeader.vue';
import { Eye, EyeOff } from 'lucide-vue-next'
import { dateToUnix } from '@/utils/format-date.js'

const router = useRouter()
const authStore = useAuthStore()
const { setToast } = inject('toast')
const error = ref(null)
const user = computed(() =>authStore.user);

const showAdvancedOptions = ref(false)


const newToken = ref({
  name: '',
  key: '',
  user_id: user.user_id,
  active: true,  
  quota: 0,      
  unlimited_quota: true,
  expired_at: 0, 
  format_expired_at: '',
  never_expired:true,
})

const resetnewToken = () => {
  newToken.value = {
    name: '',
    key: '',
    user_id: '',
    active: true, 
    quota: 0,      
    unlimited_quota: true, 
    expired_at: 0,
    format_expired_at: '', 
    never_expired:true,
  }
}

watch(
  () => newToken.value.never_expired,
  (newNeverExpiredValue) => {
    if (newNeverExpiredValue) {
      newToken.value.expired_at = 0;
    }
  }
);
watch(
  () =>newToken.value.format_expired_at,
  (format_expired_at)=> {
    if(!newToken.value.never_expired && format_expired_at) {
      newToken.value.expired_at = dateToUnix(format_expired_at);
    }else{
      newToken.value.expired_at = 0;
    }
  }
)

const isFormValid = computed(() => {
  return newToken.value.name
})

const createToken = async () => {
  if (!isFormValid.value) {
    setToast('Please fill in all required fields Name.', 'error')
    return
  }

  try {
    const res = await authStore.createToken(newToken.value)
    if (res.data?.code === 200) {
      error.value = null;
      resetnewToken();
      setToast(`Token ${newToken.value.name} created`, 'success')
      emit('closeModal', true)
    } else {
      console.log(res)
      error.value = res.data?.error || 'Failed to create token'
    }
  } catch (err) {
    error.value = err.response?.data?.error || 'Failed to create token'

  }
}

const cancel = () => {
  resetnewToken()
  emit('closeModal', false)
}

const deleteToken = async (id) => {
  console.log(id)
}

// 显示密码
const isPasswordVisible = ref(false);

function togglePasswordVisibility() {
  isPasswordVisible.value = !isPasswordVisible.value;
}

const emit = defineEmits(['closeModal'])

</script>

<style scoped>
/* Minimal custom styles if absolutely necessary */
.collapse .collapse-title {
  min-height: 0;
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}
</style>