<script setup lang="ts">
import type { Recordable } from '@easyflow/types';

import type { EasyFlowFormSchema } from '@easyflow-core/form-ui';

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

import { $t } from '@easyflow/locales';

import { useEasyFlowForm } from '@easyflow-core/form-ui';
import { EasyFlowButton } from '@easyflow-core/shadcn-ui';

import Title from './auth-title.vue';

interface Props {
  formSchema: EasyFlowFormSchema[];
  /**
   * @zh_CN 是否处于加载处理状态
   */
  loading?: boolean;
  /**
   * @zh_CN 登录路径
   */
  loginPath?: string;
  /**
   * @zh_CN 标题
   */
  title?: string;
  /**
   * @zh_CN 描述
   */
  subTitle?: string;
  /**
   * @zh_CN 按钮文本
   */
  submitButtonText?: string;
  /**
   * @zh_CN 是否显示返回按钮
   */
  showBack?: boolean;
}

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

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  showBack: true,
  loginPath: '/auth/login',
  submitButtonText: '',
  subTitle: '',
  title: '',
});

const emit = defineEmits<{
  submit: [Recordable<any>];
}>();

const router = useRouter();

const [Form, formApi] = useEasyFlowForm(
  reactive({
    commonConfig: {
      hideLabel: true,
      hideRequiredMark: true,
    },
    schema: computed(() => props.formSchema),
    showDefaultActions: false,
  }),
);

async function handleSubmit() {
  const { valid } = await formApi.validate();
  const values = await formApi.getValues();
  if (valid) {
    emit('submit', values);
  }
}

function goToLogin() {
  router.push(props.loginPath);
}

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

<template>
  <div class="auth-code-login">
    <Title>
      <slot name="title">
        {{ title || $t('authentication.welcomeBack') }}
      </slot>
      <template #desc>
        <span class="text-muted-foreground">
          <slot name="subTitle">
            {{ subTitle || $t('authentication.codeSubtitle') }}
          </slot>
        </span>
      </template>
    </Title>
    <div class="auth-form-group">
      <Form />
    </div>
    <EasyFlowButton
      :class="{
        'cursor-wait': loading,
      }"
      :loading="loading"
      class="mt-6 h-11 w-full rounded-xl text-base font-medium"
      @click="handleSubmit"
    >
      <slot name="submitButtonText">
        {{ submitButtonText || $t('common.login') }}
      </slot>
    </EasyFlowButton>
    <EasyFlowButton
      v-if="showBack"
      class="mt-3 h-11 w-full rounded-xl"
      variant="outline"
      @click="goToLogin()"
    >
      {{ $t('common.back') }}
    </EasyFlowButton>
  </div>
</template>

<style scoped>
.auth-form-group :deep(.easyflow-form-ui + .easyflow-form-ui) {
  margin-top: 0.95rem;
}
</style>
