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

import { computed, markRaw } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { z } from '@vben-core/form-ui';
import AuthenticationLogin from '@vben/common-ui/es/authentication/login';
import SliderCaptcha from '@vben/common-ui/es/captcha/slider-captcha';
import { $t } from '@vben/locales';

import { useAuthStore } from '#/store';
import { normalizeHomePath } from '#/utils/legacy-home';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();
const route = useRoute();
const router = useRouter();

async function handleLogin(params: Record<string, any>) {
  const redirect = route.query.redirect as string | undefined;

  if (redirect) {
    await authStore.authLogin(params, async () => {
      await router.push(normalizeHomePath(redirect));
    });
    return;
  }

  await authStore.authLogin(params);
}

const formSchema = computed((): VbenFormSchema[] => [
  {
    component: 'VbenInput',
    componentProps: {
      autocomplete: 'username',
      placeholder: $t('authentication.usernameTip'),
    },
    defaultValue: '',
    fieldName: 'username',
    label: $t('authentication.username'),
    rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
  },
  {
    component: 'VbenInputPassword',
    componentProps: {
      autocomplete: 'current-password',
      placeholder: $t('authentication.passwordTip'),
    },
    defaultValue: '',
    fieldName: 'password',
    label: $t('authentication.password'),
    rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
  },
  {
    component: markRaw(SliderCaptcha),
    fieldName: 'captcha',
    rules: z.boolean().refine((value) => value, {
      message: $t('authentication.verifyRequiredTip'),
    }),
  },
]);
</script>

<template>
  <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    :show-third-party-login="false"
    @submit="handleLogin"
  />
</template>
