<script setup lang="ts">
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, reactive, ref, watch } from 'vue';

import { useVbenForm, useVbenModal, VbenButton, z } from '@vben/common-ui';

defineOptions({
  name: 'LoginComponent',
});

const emit = defineEmits(['goToForgetPassword', 'goToRegister', 'submit']);
const loading = ref(false);
const [Modal, modalApi] = useVbenModal();

const REMEMBER_ME_KEY = `REMEMBER_ME_USERNAME_${location.hostname}`;
const localUsername = localStorage.getItem(REMEMBER_ME_KEY) || '';
const rememberMe = ref(!!localUsername);
const open = defineModel<boolean>('open', { default: false });

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '',
      },
      fieldName: 'username',
      label: 'Login Name',
      rules: z.string().min(1, { message: '请输入用户名' }),
      defaultValue: localUsername,
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '',
      },
      fieldName: 'password',
      label: 'Password',
      rules: z.string().min(1, { message: '请输入密码' }),
    },
  ];
});

const [Form, formApi] = useVbenForm(
  reactive({
    commonConfig: {
      hideLabel: false,
      hideRequiredMark: true,
    },
    layout: 'vertical',
    schema: formSchema,
    showDefaultActions: false,
    wrapperClass: 'text-[12px]',
  }),
);

watch(
  () => open.value,
  (val) => {
    modalApi.setState({ isOpen: val });
  },
  { immediate: true },
);

function handleClose() {
  open.value = false;
}

async function handleSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    localStorage.setItem(
      REMEMBER_ME_KEY,
      rememberMe.value ? values?.username : '',
    );
    emit('submit', values);
    open.value = false;
  }
}

function handleGoToForgetPassword() {
  emit('goToForgetPassword');
}

function handleGoToRegister() {
  emit('goToRegister');
}

defineExpose({
  getFormApi: () => formApi,
});
</script>

<template>
  <div>
    <Modal
      id="loginModal"
      :bordered="false"
      :closable="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :footer="false"
      :fullscreen-button="false"
      :header="false"
      class="relative sm:w-[940px]"
      content-class="p-0"
      @update:open="handleClose"
    >
      <div class="relative flex">
        <div class="hidden w-[470px] sm:flex">
          <img
            alt="login"
            class="w-[470px] object-contain"
            src="@/assets/image/login-banner.png"
          />
        </div>
        <div class="w-full px-[86px] py-[55px] sm:w-1/2">
          <div class="mb-6">
            <h2 class="text-[21px] font-bold">Login</h2>
            <p class="text-muted-foreground mt-2 text-sm">
              New user?
              <span class="cursor-pointer text-[#8B0046]" href="">
                Create an account
              </span>
            </p>
          </div>

          <div class="my-[20px] h-[1px] w-auto bg-[#E5E5E5]"></div>

          <Form />

          <!-- showRememberMe || showForgetPassword -->
          <div v-if="false" class="mb-6 flex justify-between">
            <label v-if="false" class="flex cursor-pointer items-center">
              <input
                v-model="rememberMe"
                class="mr-2 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-600"
                name="rememberMe"
                type="checkbox"
              />
              <span class="text-sm">记住我</span>
            </label>

            <span
              v-if="false"
              class="cursor-pointer text-sm font-normal text-blue-600 hover:underline"
              @click="handleGoToForgetPassword"
            >
              忘记密码？
            </span>
          </div>

          <VbenButton
            :class="{ 'cursor-wait': loading }"
            :loading="loading"
            aria-label="login"
            class="m-auto mt-[39px] flex h-[50px] w-full cursor-pointer items-center justify-center rounded-[25px] bg-gradient-to-b from-[#8B0046] to-[#460023] text-[16px] text-white"
            @click="handleSubmit"
          >
            Login
          </VbenButton>

          <div
            v-if="true"
            class="mt-4 cursor-pointer text-sm text-[#7D7D7D] hover:underline"
            @click="handleGoToRegister"
          >
            Forgot Password?
          </div>
        </div>
        <div class="absolute right-[20px] top-[24px] h-[44px] w-[59.12px]">
          <img alt="" class="" src="@/assets/image/system-logo.png" />
        </div>
      </div>
      <div
        class="fixed right-[-80px] top-[0] flex h-[34px] w-[34px] cursor-pointer items-center justify-center rounded-[50%] bg-[#fff] text-[#000] transition-opacity hover:opacity-80"
        @click="handleClose"
      >
        X
      </div>
    </Modal>
  </div>
</template>
