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

const { t } = useI18n();
const valid = ref(true);
const fullName = ref("");
const email = ref("");
const form = ref(null);

const mainStore = useMainStore();
const mainStoreRef = storeToRefs(mainStore);
const userProfile = mainStoreRef.readUserProfile;
if (userProfile) {
  if (typeof userProfile.value?.full_name === "string") {
    fullName.value = userProfile.value.full_name;
  } else {
    fullName.value = "";
  }
  email.value = userProfile.value!.email;
}

function reset() {
  if (userProfile) {
    if (typeof userProfile.value?.full_name === "string") {
      fullName.value = userProfile.value.full_name;
    } else {
      fullName.value = "";
    }
    email.value = userProfile.value!.email;
  }
}

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

async function submit() {
  await (form as any).value.validate();
  if (valid.value) {
    const updateProfile: IUserProfileUpdate = {};
    if (fullName.value) {
      updateProfile.full_name = fullName.value;
    }
    if (email.value) {
      updateProfile.email = email.value;
    }
    await mainStore.updateUserProfile(updateProfile);
    router.push("/main/profile");
  }
}

onMounted(() => {
  (form as any).value.validate();
});
</script>

<template>
  <v-container fluid>
    <v-card class="ma-3 pa-3">
      <v-card-title>
        <h3 class="card-title">{{ t("editUserProfile") }}</h3>
      </v-card-title>
      <v-card-text class="pt-3">
        <v-form v-model="valid" ref="form">
          <v-text-field
            :label="$t('userName')"
            v-model="fullName"
            :rules="nameRules"
            required
          ></v-text-field>
          <v-text-field
            :label="$t('emailAddress')"
            type="email"
            v-model="email"
            :rules="emailRules"
            required
          ></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("reset") }}</v-btn>
        <v-btn @click="submit" :disabled="!valid">{{ t("save") }}</v-btn>
      </v-card-actions>
    </v-card>
  </v-container>
</template>

<style lang="scss" scoped>
// .v-card-title {
//   h3 {
//     letter-spacing: 1px !important;
//   }
// }
</style>
