<script setup lang="ts">
import { useUserStore } from '@/stores/modules/user'

const { isLoginModalOpen, closeLoginModal } = useLoginModal()

const userStore = useUserStore()
const { login } = userStore

const loginForm = ref({
  email: '',
  password: '',
})
const error = ref(false)
const isLoading = ref(false)

const route = useRoute()

watch(() => route.path, () => {
  if (isLoginModalOpen.value)
    closeLoginModal({ status: false, error: '用户取消登录' })
})

async function handleLogin() {
  error.value = false
  isLoading.value = true
  try {
    await login(loginForm.value)
    closeLoginModal({ status: true, isFirstLogin: true })
  }
  catch (err) {
    error.value = true
  }
  finally {
    isLoading.value = false
  }
}

function handleClose() {
  closeLoginModal({ status: false, error: '用户取消登录' })
}
</script>

<template>
  <el-dialog
    v-model="isLoginModalOpen"
    :append-to-body="true"
    width="580"
    @close="handleClose"
  >
    <div class="p-24px pt-26px text-center ">
      <h2 class="fw-500 text-20px text-#333">
        Shop Quality Wholesale Online
      </h2>
      <div class="mt-10px mb-30px text-#666666 text-14px">
        Slgn in to wholesale from over 2,000+ premium brands!
      </div>
      <el-form :model="loginForm">
        <el-form-item label="" class="!mb-20px">
          <el-input v-model.trim="loginForm.email" class="!h-50px !text-18px" placeholder="Email" />
        </el-form-item>
        <el-form-item label="">
          <el-input v-model.trim="loginForm.password" :show-password="true" class="!h-50px !text-18px" type="password" placeholder="Password" @press-enter="handleLogin" />
        </el-form-item>

        <div class="flex justify-between mt-10px mb-30px text-18px">
          <div v-if="error" class="text-#D2161F text-16px">
            Username or password is incorrect
          </div>
          <div v-else />
          <div class="hover:underline text-14px">
            <nuxt-link to="/forgot">
              Forget Password?
            </nuxt-link>
          </div>
        </div>

        <el-button :disabled="!(loginForm.email && loginForm.password)" class="!bg-#292F36 !text-#fff !b-#292F36 !w-full !h-50px !text-16px !fw-500 !b-rd-6px" @click="handleLogin">
          LOG IN
        </el-button>
        <el-button class="!bg-#CC9879 !text-#fff !w-full !h-50px !text-16px !fw-500 !b-rd-6px !ml-0 mt-16px">
          <nuxt-link to="/register">
            No account? SIGN UP
          </nuxt-link>
        </el-button>
      </el-form>
    </div>
  </el-dialog>
</template>

<style lang="less">
 .el-dialog {
    border-radius: 10px;
    .el-dialog__header{
        &.show-close{
            .el-dialog__headerbtn{
                width: 60px;
                height: 60px;
                .el-dialog__close{
                    font-size: 30px;
                    color: #000;
                }
            }
        }
    }
}
</style>
