<template>
  <div class="login-view">
    <form class="login-box" @submit.prevent="handleLogin">
      <div class="locale-switch-row">
        <label class="locale-switch-label" for="login-locale-select">{{ t('语言') }}</label>
        <select id="login-locale-select" class="locale-switch-select" :value="currentLocale"
          @change="handleLocaleChange">
          <option v-for="option in localeOptions" :key="option.value" :value="option.value">
            {{ t(option.label) }}
          </option>
        </select>
      </div>

      <h2>{{ t('客服工作台登录') }}</h2>

      <div class="form-item">
        <label class="form-label" for="sdk-app-id">SDKAppID</label>
        <input id="sdk-app-id" v-model.trim="sdkAppId" class="form-input" type="text" inputmode="numeric"
          :placeholder="t('请输入desk 应用的 SDKAppID')" />
        <p class="form-hint">
          {{ t('开通 desk 应用后，可在控制台、站内信或') }}
          <a class="form-hint-link"
            href="https://qcloudimg.tencent-cloud.cn/image/document/1617a48e7c7a312e35fb253ba7596e81.png"
            target="_blank" rel="noopener noreferrer">{{ t('管理端的 URL') }}</a>
          {{ t('中查看') }}
        </p>
      </div>

      <div class="form-item">
        <label class="form-label" for="seat-user-id">UserID</label>
        <input id="seat-user-id" v-model.trim="userId" class="form-input" type="text" autocomplete="username"
          :placeholder="t('请输入客服账号邮箱/账号')" />
        <p class="form-hint">{{ t('请输入desk应用中已创建的客服邮箱/账号') }}</p>
      </div>

      <div class="form-item">
        <label class="form-label" for="secret-id">SecretId</label>
        <input id="secret-id" v-model.trim="secretId" class="form-input" type="text" autocomplete="off"
          :placeholder="t('请输入腾讯云 API 密钥 SecretId')" />
        <p class="form-hint">
          {{ t('SecretId 及 SecretKey 在') }}
          <a class="form-hint-link" href="https://console.cloud.tencent.com/cam/capi" target="_blank"
            rel="noopener noreferrer">{{ t('访问管理页面') }}</a>
          {{ t('获取') }}
        </p>
      </div>

      <div class="form-item">
        <label class="form-label" for="secret-key">SecretKey</label>
        <input id="secret-key" v-model.trim="secretKey" class="form-input" type="password" autocomplete="new-password"
          :placeholder="t('请输入腾讯云 API 密钥 SecretKey')" />
        <p class="form-hint">
          {{ t('SecretId 及 SecretKey 在') }}
          <a class="form-hint-link" href="https://console.cloud.tencent.com/cam/capi" target="_blank"
            rel="noopener noreferrer">{{ t('访问管理页面') }}</a>
          {{ t('获取') }}
        </p>
      </div>

      <div class="form-item">
        <label class="form-label" for="site-type">{{ t('站点') }}</label>
        <select id="site-type" v-model="siteType" class="form-input form-select">
          <option value="domestic">{{ t('中国站') }}</option>
          <option value="international">{{ t('国际站（新加坡）') }}</option>
        </select>
        <p class="form-hint">{{ t('国际站请求将使用 ap-singapore 地域') }}</p>
      </div>

      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>

      <button class="login-button" type="submit" :disabled="isLoggingIn || !isFormComplete">
        {{ isLoggingIn ? t('登录中...') : t('登录并进入工作台') }}
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import AIDeskCoreInstance from '@tencentcloud/ai-desk-core';
import { getLocale, LOCALE_OPTIONS, setLocale, type AppLocale } from '../../locales';
import { isMobile } from '../../utils/env';

type SiteType = 'domestic' | 'international';

interface LoginResponse {
  sdkUrl?: string;
  errMsg?: string;
}

const router = useRouter();
const { t } = useI18n();

const sdkAppId = ref('');
const userId = ref('');
const secretId = ref('');
const secretKey = ref('');
const siteType = ref<SiteType>('domestic');
const isLoggingIn = ref(false);
const errorMessage = ref('');
const currentLocale = ref<AppLocale>(getLocale());
const localeOptions = LOCALE_OPTIONS.map((value) => ({
  value,
  label: value === 'zh-CN' ? '中文' : '英文',
}));

const isFormComplete = computed(() => Boolean(
  sdkAppId.value.trim()
  && userId.value.trim()
  && secretId.value.trim()
  && secretKey.value.trim()
));

const handleLocaleChange = (event: Event) => {
  const nextLocale = (event.target as HTMLSelectElement | null)?.value as AppLocale;
  if (!LOCALE_OPTIONS.includes(nextLocale)) {
    return;
  }

  currentLocale.value = nextLocale;
  setLocale(nextLocale);
};

const requestSdkUrl = async () => {
  const response = await fetch('/loginTCCC', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      sdkAppId: sdkAppId.value,
      userId: userId.value,
      secretId: secretId.value,
      secretKey: secretKey.value,
      isInternational: siteType.value === 'international',
    }),
  });

  const payload = await response.json() as LoginResponse;
  if (!response.ok) {
    throw new Error(payload.errMsg || t('获取 SDK URL 失败，状态码：{status}', {
      status: response.status,
    }));
  }
  if (!payload.sdkUrl) {
    throw new Error(t('获取 SDK URL 失败：响应中未找到 SDK URL'));
  }

  return payload.sdkUrl;
};

const handleLogin = async () => {
  if (isLoggingIn.value || !isFormComplete.value) {
    return;
  }

  isLoggingIn.value = true;
  errorMessage.value = '';
  try {
    const sdkUrl = await requestSdkUrl();
    await AIDeskCoreInstance.init(sdkUrl);
    if (currentLocale.value !== 'zh-CN') {
      await AIDeskCoreInstance.appSettingService.changeLanguage('en');
    }
    await router.push(isMobile ? '/mobileDesk' : '/PCDesk');
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    errorMessage.value = t('初始化失败：{message}', { message });
    console.error(errorMessage.value);
  } finally {
    isLoggingIn.value = false;
  }
};
</script>

<style scoped>
.login-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
  padding: 32px 16px;
  box-sizing: border-box;
  background: #f0f2f5;
  overflow-y: auto;
}

.login-box {
  width: min(620px, 100%);
  padding: 32px 40px 36px;
  box-sizing: border-box;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-box h2 {
  margin: 4px 0 24px;
  text-align: center;
}

.locale-switch-row {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
}

.locale-switch-label,
.form-hint {
  color: #666;
  font-size: 13px;
}

.locale-switch-select {
  height: 32px;
  padding: 0 10px;
  border: 1px solid #dcdcdc;
  border-radius: 6px;
  background: #fff;
  color: #333;
}

.form-item {
  margin-top: 16px;
}

.form-label {
  display: block;
  margin-bottom: 7px;
  color: #333;
  font-size: 14px;
  font-weight: 600;
  text-align: left;
}

.form-input {
  width: 100%;
  height: 40px;
  padding: 0 12px;
  box-sizing: border-box;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  background: #fff;
  color: #333;
  font-size: 14px;
  outline: none;
}

.form-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.12);
}

.form-select {
  cursor: pointer;
}

.form-hint {
  margin: 6px 0 0;
  line-height: 1.4;
  text-align: left;
}

.form-hint-link {
  color: #1890ff;
  text-decoration: underline;
}

.error-message {
  margin: 16px 0 0;
  color: #d54941;
  font-size: 13px;
  line-height: 1.5;
}

.login-button {
  width: 100%;
  margin-top: 24px;
  padding: 10px 24px;
  border: none;
  border-radius: 4px;
  background: #1890ff;
  color: #fff;
  cursor: pointer;
}

.login-button:disabled {
  background: #b5d7ff;
  cursor: not-allowed;
}

@media (max-width: 520px) {
  .login-view {
    align-items: flex-start;
    padding: 16px;
  }

  .login-box {
    padding: 24px 20px 28px;
  }
}
</style>
