<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useMainStore } from "@/stores/store";
import axios from "axios";

const store = useMainStore();
const emit = defineEmits(["close"]);
const emailRegex = /^(?:\s*|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/;
let tab = ref("");

function close() {
  emit("close", false);
}

// Google Login
const handleSignIn = async (response) => {
  const credential = response.credential;
  const profile = JSON.parse(
    decodeURIComponent(
      escape(
        window.atob(
          credential.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")
        )
      )
    )
  );

  console.log("profile", profile);

  if (profile) {
    let data = {
      username: profile.name,
      password: "googleLogin",
      email: profile.email,
    };

    const formData = new FormData();
    for (const key in data) {
      formData.append(key, data[key]);
    }

    formData.forEach((value, key) => {
      console.log(`${key}: ${value}`);
    });

    try {
      const response = await axios.post(
        `${store.apiUrl}/api/login/google/access-token`,
        formData
      );
      console.log("response", response);
      console.log("response access_token", response.data.access_token);
      if (response.data.access_token) {
        alertText.value = "登入成功";
        loginAlert.value = true;
        isLoading.value = false;
        alertClose(2000);

        setTimeout(() => {
          localStorage.setItem("token", response.data.access_token);
          store.loginState = true;
          window.location.reload();
        }, 1500);
      }
    } catch (error) {
      console.log("google login error");
      console.log(error);
    }
  }
};

let isLoading = ref(false);
let loginAlert = ref(false);
let userLogin = reactive({
  username: "",
  password: "",
});

// 登入
async function login() {
  if (!emailRegex.test(userLogin.username)) {
    alertText.value = "請檢查 E-mail 格式";
    loginAlert.value = true;
    alertClose(1500);
    return;
  }

  const formData = new FormData();
  for (const key in userLogin) {
    formData.append(key, userLogin[key]);
  }

  try {
    isLoading.value = true;
    const response = await axios.post(`${store.apiUrl}/api/login`, formData);
    console.log("登入 response", response);

    if (response.data.message === "查無此人") {
      alertText.value = "此帳號不存在，請先完成註冊";
      loginAlert.value = true;
      isLoading.value = false;
      alertClose(2000);

      return;
    } else if (response.data.message === "Invalid username or password") {
      alertText.value = "帳號或密碼錯誤";
      loginAlert.value = true;
      isLoading.value = false;
      alertClose(2000);

      return;
    } else if (response.data.msg) {
      alertText.value = response.data.msg;
      loginAlert.value = true;
      isLoading.value = false;
      alertClose(2000);

      setTimeout(() => {
        localStorage.setItem("token", response.data.access_token);
        store.loginState = true;
        window.location.reload();
      }, 1500);
    }

    // setTimeout(() => {
    //   localStorage.setItem("token", response.data.access_token);
    //   store.loginState = true;
    //   window.location.reload();
    // }, 1500);
  } catch (error) {
    console.error(error);
  }
}

let userRegister = reactive({
  email: "",
  username: "",
  password: "",
  re_password: "",
});

// 註冊
async function register() {
  const formData = new FormData();
  for (const key in userRegister) {
    formData.append(key, userRegister[key]);
  }

  try {
    isLoading.value = true;
    const response = await axios.post(`${store.apiUrl}/api/add`, formData);
    console.log("response", response);
    if (response.data.msg) {
      alertText.value = response.data.msg;
      registerAlert.value = true;
      alertClose(2000);
    }
    isLoading.value = false;
    if (response.data.code === 200) {
      setTimeout(() => {
        tab.value = 1;
      }, 3000);
    }
  } catch (error) {
    console.error(error);
  }
}

// 檢查欄位是否為空
function checkEmptyFields() {
  for (const key in userRegister) {
    if (userRegister[key] === "") {
      return false;
    }
  }
  return true;
}

let registerAlert = ref(false);
let alertText = ref("");

// 檢查註冊欄位
function validateRegister() {
  const isValid = checkEmptyFields();
  if (!isValid) {
    return;
  }

  if (!emailRegex.test(userRegister.email)) {
    alertText.value = "請檢查 E-mail 格式";
    registerAlert.value = true;
    alertClose(1500);
    return;
  }

  if (userRegister.password !== userRegister.re_password) {
    alertText.value = "密碼與確認密碼不相符";
    registerAlert.value = true;
    alertClose(1500);
    return;
  }

  register();
}

function alertClose(second) {
  setTimeout(() => {
    loginAlert.value = false;
    registerAlert.value = false;
  }, second);
}

onMounted(() => {
  const script = document.createElement("script");
  script.src = "https://accounts.google.com/gsi/client";
  script.async = true;
  script.defer = true;
  document.head.appendChild(script);

  window.onSignIn1 = handleSignIn;
});

let showLogin = ref(false);

function toggleLoginInput() {
  console.log("showLogin");
  showLogin.value = !showLogin.value;
}
</script>

<template>
  <v-card class="login-card">
    <div class="d-flex justify-end pa-3">
      <v-icon
        size="large"
        icon="mdi-close"
        color="gray"
        @click.prevent="close()"
      ></v-icon>
    </div>
    <v-tabs v-model="tab" color="primary" align-tabs="center">
      <v-tab :value="1" class="me-5">登入</v-tab>
      <v-tab :value="2">註冊</v-tab>
    </v-tabs>
    <v-window v-model="tab">
      <v-window-item :value="1">
        <div class="px-15 pt-10 d-flex flex-column align-center">
          <div
            id="g_id_onload"
            data-client_id="1019468024352-ktbehd28aia7gjcl53sgaid1ucqb8gcd.apps.googleusercontent.com"
            data-callback="onSignIn1"
          ></div>
          <div
            class="g_id_signin"
            data-type="standard"
            data-theme="outline"
            data-size="large"
            data-logo_alignment="left"
          ></div>

          <!-- <p class="text-center my-7">使用平台帳號登入</p> -->

          <v-btn
            @click="toggleLoginInput()"
            class="login-btn"
            variant="outlined"
            color="primary"
          >
            使用平台帳號登入
          </v-btn>

          <!-- <v-text-field
            v-model="testAccount"
            label="測試帳號"
            prepend-inner-icon="mdi-account"
            variant="solo"
            density="compact"
            hide-details
            class="w-50 mt-5"
          ></v-text-field> -->

          <a
            href="https://member.moc.gov.tw/MOCMC/A0001/list?SYS_ID=CRAFT_NTCRI"
            >測試連結</a
          >
          <Transition>
            <v-form v-if="showLogin" @submit.prevent class="mt-7">
              <v-text-field
                v-model="userLogin.username"
                label="信箱"
                :rules="[(v) => !!v || '請輸入您的信箱']"
                prepend-inner-icon="mdi-account"
                variant="solo"
                density="compact"
              ></v-text-field>
              <v-text-field
                v-model="userLogin.password"
                label="密碼"
                :rules="[(v) => !!v || '請輸入您的密碼']"
                prepend-inner-icon="mdi-lock"
                variant="solo"
                density="compact"
                type="password"
              ></v-text-field>
              <v-btn
                type="submit"
                size="large"
                color="primary"
                block
                @click="login()"
                :loading="isLoading"
                >登入</v-btn
              >
            </v-form>
          </Transition>

          <div class="alert" v-if="loginAlert">
            <v-alert border="start" border-color="primary" elevation="2">
              {{ alertText }}
            </v-alert>
          </div>
        </div>
      </v-window-item>
      <v-window-item :value="2">
        <div class="d-flex flex-column align-center px-15 pt-10">
          <v-form @submit.prevent>
            <!-- <v-select
              label="身份"
              :items="['學習者', '開課工藝教育者', '其他']"
              variant="solo"
              density="compact"
            ></v-select> -->
            <v-text-field
              v-model="userRegister.email"
              label="信箱"
              :rules="[(v) => !!v || '請輸入您的信箱']"
              prepend-inner-icon="mdi-email"
              variant="solo"
              density="compact"
            ></v-text-field>
            <v-text-field
              v-model="userRegister.username"
              label="帳號"
              :rules="[(v) => !!v || '請輸入您的帳號']"
              prepend-inner-icon="mdi-account"
              variant="solo"
              density="compact"
            ></v-text-field>
            <v-text-field
              v-model="userRegister.password"
              label="密碼"
              :rules="[(v) => !!v || '請輸入您的密碼']"
              prepend-inner-icon="mdi-lock"
              variant="solo"
              density="compact"
              type="password"
            ></v-text-field>
            <v-text-field
              v-model="userRegister.re_password"
              label="確認密碼"
              :rules="[(v) => !!v || '請輸入確認密碼']"
              prepend-inner-icon="mdi-lock-check"
              variant="solo"
              density="compact"
              type="password"
            ></v-text-field>
            <v-btn
              block
              type="submit"
              size="large"
              color="primary"
              @click="validateRegister()"
              :loading="isLoading"
              >註冊</v-btn
            >
          </v-form>
          <div class="alert" v-if="registerAlert">
            <v-alert border="start" border-color="primary" elevation="2">
              {{ alertText }}
            </v-alert>
          </div>
        </div>
      </v-window-item>
    </v-window>

    <v-card-actions class="d-flex flex-column py-10 forget">
      <p class="directions">
        登入會員後、凡報名課程即可享有學習護照的點數累積、兌換精美好禮，系統會紀錄您的選課與開課、輕鬆開啟您的工藝學習旅程。
      </p>
      <div class="d-flex justify-center pt-10">
        <a href="">忘記密碼</a><span class="mx-1">／</span
        ><a href="">忘記帳號</a>
      </div>
    </v-card-actions>
  </v-card>
</template>

<style lang="scss">
.login-btn {
  width: 11.875em;
  margin-top: 1.25em;
}
.login-card {
  .v-tab {
    padding-bottom: 1.25em;
    font-size: 1.75em;
  }
  .v-form {
    width: 100%;
  }
  .tab {
    button {
      margin: 0 1.25em;
      padding-bottom: 1.25em;
      font-size: 1.75em;
      font-weight: 500;
      text-align: center;
      color: #d9d9d9;
      border-bottom: 0.1875em solid transparent;
      transition: all 0.3s;
      &.active {
        color: var(--main-color);
        border-bottom: 0.1875em solid var(--main-color);
      }
    }
  }
  h3,
  p {
    color: #595959;
  }
  .google-btn {
    width: 8.125em;
    margin: auto;
  }
  .v-text-field .v-input__details {
    position: relative;
    top: -0.25em;
  }
  .forget {
    a,
    span {
      color: #969696;
    }
    a {
      transition: all 0.3s;
      &:hover {
        opacity: 0.8;
      }
    }
  }

  .alert {
    top: 50%;
    position: absolute;
    z-index: 1;
    .v-alert {
      color: var(--main-color);
      background-color: #fff;
      letter-spacing: 0.0625em;
    }
  }

  .directions {
    padding: 0 30px 0;
    line-height: 1.5;
    letter-spacing: 1px;
    text-align: justify;
    color: #969696;
  }
}
</style>
