<script setup lang="ts">
/**
 * @file register.vue
 * @description User Registration Page.
 * Features a multi-step style form (though currently single view) for creating a new account.
 * Updated to match the Dark Theme design.
 */

definePageMeta({
  layout: "auth",
  middleware: "auth",
});

useHead({
  title: "สมัครสมาชิก - e-Learning",
});

const router = useRouter();
const { register } = useAuth();
const { errors, validate, clearFieldError } = useFormValidation();

const isLoading = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);

const registerForm = reactive({
  prefix: "นาย",
  username: "",
  firstName: "",
  lastName: "",
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
});

const registerRules = {
  username: { 
    rules: { 
      required: true, 
      minLength: 4,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null
    }, 
    label: "ชื่อผู้ใช้" 
  },
  firstName: { 
    rules: { 
      required: true, 
      minLength: 2,
      custom: (val: string) => /\d/.test(val) ? 'ห้ามใส่ตัวเลข' : null
    }, 
    label: "ชื่อ" 
  },
  lastName: { 
    rules: { 
      required: true, 
      minLength: 2,
      custom: (val: string) => /\d/.test(val) ? 'ห้ามใส่ตัวเลข' : null
    }, 
    label: "นามสกุล" 
  },
  phone: {
    rules: { 
      required: true, 
      pattern: /^0[0-9]{8,9}$/,
      custom: (val: string) => /\D/.test(val) ? 'กรุณากรอกเฉพาะตัวเลข' : null
    },
    label: "เบอร์โทรศัพท์",
  },
  email: { 
    rules: { 
      required: true, 
      email: true,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null 
    }, 
    label: "อีเมล" 
  },
  password: { 
    rules: { 
      required: true, 
      minLength: 8,
      custom: (val: string) => /[\u0E00-\u0E7F]/.test(val) ? 'ห้ามใส่ภาษาไทย' : null 
    }, 
    label: "รหัสผ่าน" 
  },
  confirmPassword: {
    rules: { required: true, match: "password" },
    label: "ยืนยันรหัสผ่าน",
  },
};

const prefixOptions = ['นาย', 'นาง', 'นางสาว']

// handlers
const onUsernameInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.username = value;
  if (/[\u0E00-\u0E7F]/.test(value)) {
    errors.value.username = 'ห้ามใส่ภาษาไทย';
  } else {
    if (errors.value.username === 'ห้ามใส่ภาษาไทย') clearFieldError('username');
  }
};

const onPhoneInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.phone = value;
  if (/\D/.test(value)) {
    errors.value.phone = 'กรุณากรอกเฉพาะตัวเลข';
  } else {
    if (errors.value.phone === 'กรุณากรอกเฉพาะตัวเลข') clearFieldError('phone');
  }
};

const onEmailInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.email = value;
  if (/[\u0E00-\u0E7F]/.test(value)) {
    errors.value.email = 'ห้ามใส่ภาษาไทย';
  } else {
    if (errors.value.email === 'ห้ามใส่ภาษาไทย') clearFieldError('email');
  }
};

const onPasswordInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.password = value;
  if (/[\u0E00-\u0E7F]/.test(value)) {
    errors.value.password = 'ห้ามใส่ภาษาไทย';
  } else {
    if (errors.value.password === 'ห้ามใส่ภาษาไทย') clearFieldError('password');
  }
};

const onFirstNameInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.firstName = value;
  if (/\d/.test(value)) {
    errors.value.firstName = 'ห้ามใส่ตัวเลข';
  } else {
    if (errors.value.firstName === 'ห้ามใส่ตัวเลข') clearFieldError('firstName');
  }
};

const onLastNameInput = (val: string | number | null) => {
  const value = String(val || '')
  registerForm.lastName = value;
  if (/\d/.test(value)) {
    errors.value.lastName = 'ห้ามใส่ตัวเลข';
  } else {
    if (errors.value.lastName === 'ห้ามใส่ตัวเลข') clearFieldError('lastName');
  }
};

const handleRegister = async () => {
  if (!validate(registerForm, registerRules)) return;

  isLoading.value = true;

  const prefixMap: Record<string, string> = {
    'นาย': 'Mr.',
    'นาง': 'Mrs.',
    'นางสาว': 'Ms.'
  };

  const payload = {
    username: registerForm.username,
    email: registerForm.email,
    password: registerForm.password,
    first_name: registerForm.firstName,
    last_name: registerForm.lastName,
    prefix: {
        th: registerForm.prefix,
        en: prefixMap[registerForm.prefix] || 'Mr.'
    },
    phone: registerForm.phone
  };

  const result = await register(payload);

  isLoading.value = false;

  if (result.success) {
      alert('สมัครสมาชิกสำเร็จ! กรุณาเข้าสู่ระบบ');
      router.push("/auth/login");
  } else {
      alert(result.error || 'การลงทะเบียนล้มเหลว');
  }
};
</script>

<template>
  <div class="flex items-center justify-center min-h-screen bg-slate-900 font-inter p-4 relative overflow-hidden">
    
    <!-- Background Decoration -->
    <div class="absolute top-[-20%] left-[-10%] w-[600px] h-[600px] bg-blue-600/5 rounded-full blur-[120px] pointer-events-none"></div>
    <div class="absolute bottom-[-20%] right-[-10%] w-[600px] h-[600px] bg-indigo-600/5 rounded-full blur-[120px] pointer-events-none"></div>

    <q-card class="w-full max-w-[740px] shadow-2xl rounded-2xl bg-slate-800 text-white border border-slate-700 relative z-10 q-pa-xl">

      <!-- Header -->
      <div class="flex flex-col items-center mb-10">
        <div class="w-14 h-14 bg-white text-blue-600 rounded-2xl flex items-center justify-center font-extrabold text-3xl mb-6 shadow-lg shadow-white/10">
          E
        </div>
        <h1 class="text-3xl font-bold text-white mb-3">e-Learning Platform</h1>
        <p class="text-slate-400 text-base">สร้างบัญชีผู้ใช้งานใหม่</p>
      </div>

      <form @submit.prevent="handleRegister" class="flex flex-col gap-5">
        
        <!-- Username -->
        <div>
           <div class="text-base font-semibold text-slate-300 mb-2 ml-1">ชื่อผู้ใช้ <span class="text-red-500">*</span></div>
           <q-input
              :model-value="registerForm.username"
              outlined
              dense
              dark
              placeholder="username"
              class="rounded-lg custom-dark-input"
              color="primary"
              :error="!!errors.username"
              :error-message="errors.username"
              @update:model-value="onUsernameInput"
              hide-bottom-space
           />
        </div>

        <!-- Email -->
        <div>
           <div class="text-base font-semibold text-slate-300 mb-2 ml-1">อีเมล <span class="text-red-500">*</span></div>
           <q-input
              :model-value="registerForm.email"
              outlined
              dense
              dark
              type="email"
              placeholder="student@example.com"
              class="rounded-lg custom-dark-input"
              color="primary"
              :error="!!errors.email"
              :error-message="errors.email"
              @update:model-value="onEmailInput"
              hide-bottom-space
           />
        </div>

        <!-- Password -->
        <div>
           <div class="text-base font-semibold text-slate-300 mb-2 ml-1">รหัสผ่าน <span class="text-red-500">*</span></div>
           <q-input
              :model-value="registerForm.password"
              outlined
              dense
              dark
              :type="showPassword ? 'text' : 'password'"
              placeholder="สร้างรหัสผ่าน (อย่างน้อย 8 ตัวอักษร)"
              class="rounded-lg custom-dark-input"
              color="primary"
              :error="!!errors.password"
              :error-message="errors.password"
              @update:model-value="onPasswordInput"
              hide-bottom-space
           >
             <template v-slot:append>
                <q-icon
                  :name="showPassword ? 'visibility_off' : 'visibility'"
                  class="cursor-pointer text-slate-400 hover:text-white transition-colors"
                  @click="showPassword = !showPassword"
                />
             </template>
           </q-input>
        </div>

        <!-- Confirm Password -->
        <div>
           <div class="text-base font-semibold text-slate-300 mb-2 ml-1">ยืนยันรหัสผ่าน <span class="text-red-500">*</span></div>
           <q-input
              v-model="registerForm.confirmPassword"
              outlined
              dense
              dark
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="ยืนยันรหัสผ่านอีกครั้ง"
              class="rounded-lg custom-dark-input"
              color="primary"
              :error="!!errors.confirmPassword"
              :error-message="errors.confirmPassword"
              @update:model-value="clearFieldError('confirmPassword')"
              hide-bottom-space
           >
             <template v-slot:append>
                <q-icon
                  :name="showConfirmPassword ? 'visibility_off' : 'visibility'"
                  class="cursor-pointer text-slate-400 hover:text-white transition-colors"
                  @click="showConfirmPassword = !showConfirmPassword"
                />
             </template>
           </q-input>
        </div>

        <!-- Name Section -->
        <div class="grid grid-cols-12 gap-4">
          <!-- Prefix -->
          <div class="col-span-4">
             <div class="text-base font-semibold text-slate-300 mb-2 ml-1">คำนำหน้า</div>
             <q-select
                v-model="registerForm.prefix"
                :options="prefixOptions"
                outlined
                dense
                dark
                class="rounded-lg custom-dark-input"
                color="primary"
                options-cover
             />
          </div>
          <!-- First Name -->
          <div class="col-span-8">
             <div class="text-base font-semibold text-slate-300 mb-2 ml-1">ชื่อ <span class="text-red-500">*</span></div>
             <q-input
                :model-value="registerForm.firstName"
                outlined
                dense
                dark
                placeholder=""
                class="rounded-lg custom-dark-input"
                color="primary"
                :error="!!errors.firstName"
                :error-message="errors.firstName"
                @update:model-value="onFirstNameInput"
                hide-bottom-space
             />
          </div>
        </div>

        <!-- Last Name -->
        <div>
           <div class="text-base font-semibold text-slate-300 mb-2 ml-1">นามสกุล <span class="text-red-500">*</span></div>
           <q-input
              :model-value="registerForm.lastName"
              outlined
              dense
              dark
              placeholder=""
              class="rounded-lg custom-dark-input"
              color="primary"
              :error="!!errors.lastName"
              :error-message="errors.lastName"
              @update:model-value="onLastNameInput"
              hide-bottom-space
           />
        </div>

        <!-- Phone -->
        <div>
           <div class="text-base font-semibold text-slate-300 mb-2 ml-1">เบอร์โทรศัพท์ <span class="text-red-500">*</span></div>
           <q-input
              :model-value="registerForm.phone"
              outlined
              dense
              dark
              type="tel"
              placeholder=""
              class="rounded-lg custom-dark-input"
              color="primary"
              :error="!!errors.phone"
              :error-message="errors.phone"
              @update:model-value="onPhoneInput"
              hide-bottom-space
           />
        </div>

        <!-- Submit Button -->
        <q-btn
          type="submit"
          unelevated
          rounded
          color="primary"
          class="w-full h-12 text-lg font-bold shadow-lg shadow-blue-500/20 bg-blue-600 hover:bg-blue-500 mt-4"
          :loading="isLoading"
        >
          สร้างบัญชี
          <template v-slot:loading>
            <q-spinner-dots color="white" />
          </template>
        </q-btn>

        <!-- Login Link -->
        <div class="text-center pt-6 border-t border-slate-700 mt-2 text-base text-slate-400">
           มีบัญชีอยู่แล้ว? 
           <NuxtLink to="/auth/login" class="font-bold text-blue-400 hover:text-blue-300 transition-colors ml-1">
             เข้าสู่ระบบ
           </NuxtLink>
        </div>

      </form>
    </q-card>
  </div>
</template>

<style scoped>
.font-inter {
  font-family: 'Inter', 'Prompt', sans-serif;
}

/* Custom dark input styling */
.custom-dark-input :deep(.q-field__control) {
  background: #334155 !important;
  border-radius: 8px;
}
.custom-dark-input :deep(.q-field__control:before) {
  border-color: #475569;
}
.custom-dark-input :deep(.q-field--focused .q-field__control:after) {
  border-color: #3b82f6;
}

/* Adjust QSelect to match */
.custom-dark-input :deep(.q-field__native) {
  color: white;
}
</style>
