<script setup lang="ts">
import { ref } from "vue";
import { useMainStore } from "@/stores/main";
import { storeToRefs } from "pinia";
import router from "@/router";
import { password1Rules, usePassword2Rules } from "@/utils";
import type { IUserProfileUpdate } from "@/interfaces";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const valid = ref(true);
const password1 = ref("");
const password2 = ref("");
const form = ref(null);
const mainStore = useMainStore();
const mainStoreRef = storeToRefs(mainStore);
const userProfile = mainStoreRef.readUserProfile;

const password2Rules = usePassword2Rules(password1);

function reset() {
  password1.value = "";
  password2.value = "";
}

function cancel() {
  router.back();
}

async function submit() {
  await (form as any).value.validate();
  if (valid.value) {
    const updatedProfile: IUserProfileUpdate = {};
    updatedProfile.password = password1.value;
    await mainStore.updateUserProfile(updatedProfile);
    router.push("/main/profile");
  }
}
</script>

<template>
  <v-container fluid>
    <v-card class="ma-3 pa-3">
      <v-card-title primary-title class="mb-3">
        <h3 class="headline primary--text">{{ t("changePassword") }}</h3>
      </v-card-title>
      <v-card-text>
        <!-- <div class="my-3">
          <div class="subheading secondary--text text--lighten-2">User</div>
          <div
            class="title primary--text text--darken-2"
            v-if="userProfile && userProfile.full_name"
          >
            {{ userProfile.full_name }}
          </div>
          <div class="title primary--text text--darken-2" v-else>
            {{ userProfile!.email }}
          </div>
        </div> -->
        <v-form ref="form" v-model="valid">
          <v-text-field
            type="password"
            ref="password"
            :label="$t('password')"
            v-model="password1"
            :rules="password1Rules"
          >
          </v-text-field>
          <v-text-field
            type="password"
            :label="$t('confirmPassword')"
            :rules="password2Rules"
            v-model="password2"
          >
          </v-text-field>
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="cancel">{{ t("cancel") }}</v-btn>
        <v-btn @click="reset">{{ t("clear") }}</v-btn>
        <v-btn @click="submit" :disabled="!valid">{{ t("save") }}</v-btn>
      </v-card-actions>
    </v-card>
  </v-container>
</template>
