<!-- src/pages/auth/changepassword.vue -->

<template>
  <div class="WrapperPlain">
    <div class="container max-w-3xl mx-auto text-white">

      <div class="mx-auto max-w-lg flex items-center justify-center mb-10 mt-20 px-5">
        <form class="bg-neutral rounded-md px-8 pt-6 pb-8 mb-4 w-full" @submit.prevent="onSubmit">
          <div class="mb-4 text-center text-[28px] ">
            Change Password
          </div>
          <div class="mb-4">
            <label class="block text-white text-sm font-bold mb-2">Enter New Password</label>
            <input v-model="form.new_password" class="rounded w-full py-2 px-3 input-primary text-black" id="password"
              type="password" placeholder="Password" :class="{ 'input-error': v$.form.new_password.$error }" />
            <span v-if="v$.form.new_password.$error" class="text-red-600 text-center">
              {{ v$.form.new_password.$errors[0].$message }}
            </span>
          </div>
          <div class="mb-6">
            <label class="block text-white text-sm font-bold mb-2">Confirm New Password</label>
            <input v-model="form.password_confirm" class="rounded w-full py-2 px-3 input-primary text-black"
              id="passwordtwo" type="password" autocomplete="off" placeholder="Confirm Password"
              :class="{ 'input-error': v$.form.password_confirm.$error }" />
            <span v-if="v$.form.password_confirm.$error" class="text-red-600 text-center">
              {{ v$.form.password_confirm.$errors[0].$message }}
            </span>
          </div>
          <div class="flex items-center justify-center mb-6">
            <button
              class="bg-primary hover:bg-zinc-400 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
              type="submit">
              Update
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { notify } from "@kyvg/vue3-notification"
import { useVuelidate } from '@vuelidate/core'
import { required, minLength, helpers } from "@vuelidate/validators"
import { authService } from '../../services/authService'

const router = useRouter()

// Form state
const form = reactive({
  new_password: '',
  password_confirm: '',
})

// Validation rules
const rules = computed(() => ({
  form: {
    new_password: { required, minLength: minLength(6) },
    password_confirm: {
      required,
      minLength: minLength(6),
      sameAsPassword: helpers.withMessage('Passwords must match', (value: string) => value === form.new_password)
    },
  },
}))

const v$ = useVuelidate(rules, { form })

// Methods
async function checkUserStatus() {
  try {
    const response = await authService.whoami()
    if (!(response.data as any).ok) {
      router.push({ name: "login" })
    }
  } catch (error) {
    router.push({ name: "login" })
  }
}

async function onSubmit() {
  const isValid = await v$.value.$validate()

  if (!isValid) {
    notify({
      title: "Authorization",
      text: "Form Failure",
      type: "error",
    })
    return
  }

  try {
    const response = await authService.changePassword({
      old_password: '', // Note: this endpoint might need adjustment based on actual API
      new_password: form.new_password,
    })

    const data = response.data as any

    if (data.ok) {
      notify({
        title: "Authorization",
        text: "Password changed",
        type: "success",
      })
      router.push({ name: "home" })
    }

    if (data.error) {
      notify({
        title: "Authorization Error",
        text: data.error,
        type: "error",
      })
    }
  } catch (error) {
    notify({
      title: "Authorization",
      text: "Invalid Credentials.",
      type: "error",
    })
  }
}

// Lifecycle
onMounted(() => {
  checkUserStatus()
})
</script>
