<template>
  <div class="min-h-screen bg-base-100 p-2 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 User
        </h1>
        <p class="text-sm text-base-content/70 mt-1">
          Enter the user'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="createUser" class="card-body space-y-5 p-3 sm:p-8">
          <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">
                    Username <span class="text-red-500">*</span>
                  </span>
                </label>
                <input id="username" type="text" v-model="newUser.username" 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">
                    Password <span class="text-red-500">*</span>
                  </span>
                </label>
                <div class="relative">
                  <input id="password" :type="isPasswordVisible ? 'text' : 'password'" v-model="newUser.password"
                    class="input input-sm input-bordered w-full" required />
                  <button type="button" @click="togglePasswordVisibility" tabindex="-1"
                    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 class="form-control">
                <label for="name" class="label">
                  <span class="label-text">Name</span>
                </label>
                <input id="name" type="text" v-model="newUser.name" placeholder="Full name"
                  class="input input-sm input-bordered w-full" />
              </div>

              <div class="form-control">
                <label for="email" class="label">
                  <span class="label-text">Email Address</span>
                </label>
                <input id="email" type="email" v-model="newUser.email" placeholder="email@example.com"
                  class="input input-sm input-bordered w-full" />
              </div>

            </div>
          </div>

          <div class="collapse collapse-arrow">
            <input type="checkbox" v-model="showAdvancedOptions" 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 for="role" class="label">
                    <span class="label-text">Role</span>
                  </label>
                  <select id="role" v-model="newUser.role" class="select select-sm select-bordered w-full">
                    <option :value="0">User</option>
                    <option :value="10">Admin</option>
                  </select>
                </div>

                <div class="form-control">
                  <label for="language" class="label">
                    <span class="label-text">Language</span>
                  </label>
                  <select id="language" v-model="newUser.language" class="select select-sm select-bordered w-full">
                    <option value="en">English</option>
                    <option value="zh">中文</option>
                  </select>
                </div>

                <div class="md:col-span-2 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="newUser.quota" placeholder="Enter quota amount"
                      class="input input-sm input-bordered flex-grow" :disabled="newUser.unlimited_quota" />
                    <label class="flex items-center space-x-2 cursor-pointer whitespace-nowrap">
                      <input type="checkbox" v-model="newUser.unlimited_quota" class="checkbox checkbox-sm" />
                      <span class="text-sm text-base-content/90">Unlimited</span>
                    </label>
                  </div>
                </div>

                <div class="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="newUser.active"
                      :class="`toggle toggle-sm ${newUser.active ? 'toggle-success' : 'toggle-error'}`" />
                    <span class="text-sm text-base-content/90">
                      {{ newUser.active ? 'Active' : 'Inactive' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="flex justify-end pt-4">
            <button type="submit" class="btn btn-outline btn-sm h-9 px-4 text-sm font-medium" :disabled="!isFormValid">
              Create User
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import BreadcrumbHeader from '@/components/dashboard/BreadcrumbHeader.vue';
import { Eye, EyeOff } from 'lucide-vue-next'

const router = useRouter()
const userStore = useUserStore()
const { setToast } = inject('toast')
const error = ref(null)

// Control advanced options visibility
const showAdvancedOptions = ref(false)

// Initialize user object
const newUser = ref({
  name: '',
  username: '',
  email: '',
  password: '',
  role: 0,        // Default to Regular User
  active: true,   // Default to Active
  quota: 0,       // Default quota value (relevant if not unlimited)
  unlimited_quota: true, // Default to unlimited
  language: 'en', // Default language
})

const resetNewUser = () => {
  newUser.value = {
    name: '',
    username: '',
    email: '',
    password: '',
    role: 0,        // Default to Regular User
    active: true,   // Default to Active
    quota: 0,       // Default quota value (relevant if not unlimited)
    unlimitedQuota: true, // Default to unlimited
    language: 'en', // Default language
  }
}

// Form validation
const isFormValid = computed(() => {
  return newUser.value.username &&
    newUser.value.password  // Password is required for creation
})

// Create user method
const createUser = async () => {
  if (!isFormValid.value) {
    setToast('Please fill in all required fields (Username, Password).', 'error')
    return
  }

  try {
    const res = await userStore.createUser({
      username: newUser.value.username,
      password: newUser.value.password,
      email: newUser.value.email,
      name: newUser.value.name || newUser.value.username, // Use username if name is empty
      role: newUser.value.role,
      active: newUser.value.active,
      quota: newUser.value.quota,
      unlimited_quota: newUser.value.unlimited_quota,
      language: newUser.value.language
    });

    if (res.data?.code === 200) {
      error.value = null;
      resetNewUser();
      setToast('User created successfully', 'success')
      // Optionally navigate or reset form
      emit('closeModal', true)
    } else {
      setToast(res.error || res.data?.message || 'Failed to create user', 'error')
    }
  } catch (err) {
    error.value = err.response?.data?.error || 'Failed to create user'
    // setToast(error.response?.data?.error || 'Failed to create user', 'error')
  }
}

// 显示密码
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>