<script lang="ts" setup>
import type { AuthApi } from '#/api/core/auth';

import { onBeforeUnmount, ref } from 'vue';

import { DEFAULT_HOME_PATH } from '@vben/constants';
import { useUserStore } from '@vben/stores';

import {
  getSiblingAccountsApi,
  switchAccountApi,
} from '#/api/core/auth';
import { useAuthStore } from '#/store';
import { message, Modal } from 'ant-design-vue';

import AccountOptionList from '#/views/_core/authentication/AccountOptionList.vue';

defineOptions({ name: 'SwitchAccountModal' });

const visible = defineModel<boolean>('open', { default: false });

const authStore = useAuthStore();

const accounts = ref<AuthApi.AccountOption[]>([]);
const selectedKey = ref<string | null>(null);
const loading = ref(false);

const successVisible = ref(false);
const countdown = ref(5);
let countdownTimer: ReturnType<typeof setInterval> | null = null;

function accountKey(item: AuthApi.AccountOption): string {
  return `${item.account_type || 'admin'}-${item.id}-${item.store_name || ''}`;
}

function resolveInitialKey(list: AuthApi.AccountOption[]): string | null {
  if (!list.length) {
    return null;
  }
  const current = list.find((item) => item.is_current);
  if (current) {
    return accountKey(current);
  }
  return accountKey(list[0]);
}

function clearCountdownTimer() {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
}

function reloadPage() {
  clearCountdownTimer();
  const userStore = useUserStore();
  const home = userStore.userInfo?.home_path || DEFAULT_HOME_PATH;
  window.location.href = home;
}

function openSuccessModal() {
  successVisible.value = true;
  countdown.value = 5;
  clearCountdownTimer();
  countdownTimer = setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0) {
      reloadPage();
    }
  }, 1000);
}

async function openModal() {
  visible.value = true;
  loading.value = true;
  try {
    accounts.value = await getSiblingAccountsApi();
    selectedKey.value = resolveInitialKey(accounts.value);
  } catch (error: any) {
    message.error(error.message || '获取账号列表失败');
    visible.value = false;
  } finally {
    loading.value = false;
  }
}

async function handleSwitch() {
  if (!selectedKey.value) {
    message.error('请选择要切换的账号');
    return;
  }

  const selected = accounts.value.find(
    (item) => accountKey(item) === selectedKey.value,
  );
  if (!selected) {
    message.error('请选择要切换的账号');
    return;
  }

  if (selected.is_current) {
    message.info('已是当前账号');
    return;
  }

  loading.value = true;
  try {
    const result = await switchAccountApi({
      admin_id: selected.id,
    });
    if (!result?.token) {
      message.error('切换失败');
      return;
    }
    await authStore.applySwitchSession(result.token);
    visible.value = false;
    openSuccessModal();
  } catch (error: any) {
    message.error(error.message || '切换失败');
  } finally {
    loading.value = false;
  }
}

onBeforeUnmount(() => {
  clearCountdownTimer();
});

defineExpose({ openModal });
</script>

<template>
  <Modal
    v-model:open="visible"
    title="切换账号"
    ok-text="确认切换"
    cancel-text="取消"
    :mask-closable="false"
    :keyboard="false"
    :confirm-loading="loading"
    @ok="handleSwitch"
  >
    <AccountOptionList
      :accounts="accounts"
      :selected-key="selectedKey"
      @select="selectedKey = $event"
    />
  </Modal>

  <Modal
    v-model:open="successVisible"
    title="切换成功"
    :closable="false"
    :mask-closable="false"
    :keyboard="false"
    :cancel-button-props="{ style: { display: 'none' } }"
    :ok-text="countdown > 0 ? `确认 (${countdown}s)` : '确认'"
    @ok="reloadPage"
  >
    <div class="text-muted-foreground text-sm">
      账号已切换成功，页面将在 {{ countdown > 0 ? countdown : 0 }} 秒后自动刷新。
    </div>
  </Modal>
</template>
