<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { NButton, NCard, NForm, NFormItem, NIcon, NInput, NModal, NText } from 'naive-ui';
import { $t } from '@/locales';
import { useAuthStore } from '@/store/modules/auth';
import { useReauthStore } from '@/store/modules/reauth';
defineOptions({
  name: 'ReauthModal'
});

interface Props {
  show: boolean;
}

interface Emits {
  (e: 'update:show', value: boolean): void;
  (e: 'success'): void;
  (e: 'cancel'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const authStore = useAuthStore();
const reauthStore = useReauthStore();
const formRef = ref<FormInst | null>(null);
const loading = ref(false);

const visible = computed({
  get: () => props.show,
  set: (value: boolean) => emit('update:show', value)
});

const formData = reactive({
  userName: '',
  password: ''
});

const rules: FormRules = {
  userName: {
    required: true,
    message: $t('form.userName.required'),
    trigger: 'blur'
  },
  password: {
    required: true,
    message: $t('form.pwd.required'),
    trigger: 'blur'
  }
};

async function handleSubmit() {
  if (!formRef.value) return;

  await formRef.value.validate();

  loading.value = true;

  try {
    await authStore.login(formData.userName, formData.password, false);

    // 重置表单
    formData.userName = '';
    formData.password = '';

    // 标记重新认证成功
    reauthStore.reauthSuccess();

    emit('success');
    visible.value = false;

    window.$message?.success($t('page.login.common.loginSuccess'));
  } catch (error) {
    console.error('Re-authentication failed:', error);

    // 标记重新认证失败
    reauthStore.reauthFailed();

    window.$message?.error($t('common.error'));
  } finally {
    loading.value = false;
  }
}

function handleCancel() {
  // 重置表单
  formData.userName = '';
  formData.password = '';

  // 标记重新认证失败
  reauthStore.reauthFailed();

  emit('cancel');
  visible.value = false;

  // 如果用户取消，则执行登出
  authStore.resetStore();
}
</script>

<template>
  <NModal v-model:show="visible" :mask-closable="false" :closable="false" :auto-focus="false">
    <NCard
      style="width: 400px"
      :title="$t('page.login.common.loginOrRegister')"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <div class="mb-4">
        <NText type="warning">
          {{ $t('request.tokenExpired') }}
        </NText>
      </div>

      <NForm
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="large"
        :show-label="false"
        @submit.prevent="handleSubmit"
      >
        <NFormItem path="userName">
          <NInput
            v-model:value="formData.userName"
            :placeholder="$t('page.login.common.userNamePlaceholder')"
            :input-props="{ autocomplete: 'username' }"
          >
            <template #prefix>
              <NIcon :size="18" color="var(--text-color-3)">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path
                    fill="currentColor"
                    d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"
                  />
                </svg>
              </NIcon>
            </template>
          </NInput>
        </NFormItem>

        <NFormItem path="password">
          <NInput
            v-model:value="formData.password"
            type="password"
            show-password-on="mousedown"
            :placeholder="$t('page.login.common.passwordPlaceholder')"
            :input-props="{ autocomplete: 'current-password' }"
            @keydown.enter="handleSubmit"
          >
            <template #prefix>
              <NIcon :size="18" color="var(--text-color-3)">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                  <path
                    fill="currentColor"
                    d="M12.65 10C11.83 7.67 9.61 6 7 6c-3.31 0-6 2.69-6 6s2.69 6 6 6c2.61 0 4.83-1.67 5.65-4H17v4h4v-4h2v-4H12.65zM7 14c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"
                  />
                </svg>
              </NIcon>
            </template>
          </NInput>
        </NFormItem>
      </NForm>

      <template #footer>
        <div class="flex justify-end space-x-3">
          <NButton @click="handleCancel">
            {{ $t('common.cancel') }}
          </NButton>
          <NButton type="primary" :loading="loading" @click="handleSubmit">
            {{ $t('common.confirm') }}
          </NButton>
        </div>
      </template>
    </NCard>
  </NModal>
</template>

<style scoped>
.space-x-3 > * + * {
  margin-left: 0.75rem;
}
</style>
