<script setup lang="ts">
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { defaultPhoneIsoForLocale, getPhoneDialFromIso } from '@thebet365/shared';
import { useSmsCode } from '../composables/useSmsCode';
import api from '../api';
import LocaleSwitcher from '../components/LocaleSwitcher.vue';
import PhoneCountrySelect from '../components/PhoneCountrySelect.vue';
import GoldSpinner from '../components/GoldSpinner.vue';
import loginBg from '../assets/images/zt2.webp';

const props = withDefaults(defineProps<{ desktop?: boolean }>(), { desktop: false });

const { t, locale } = useI18n();
const router = useRouter();
const route = useRoute();

const phone = ref('');
const countryIso = ref(defaultPhoneIsoForLocale(locale.value));
const smsCode = ref('');
const password = ref('');
const confirmPassword = ref('');
const error = ref('');
const loading = ref(false);

const { sessionId, countdown, sending, error: smsError, send } = useSmsCode();

async function sendCode() {
  await send(phone.value, getPhoneDialFromIso(countryIso.value), 'reset_password');
}

function mapApiError(code: string | undefined): string {
  if (!code) return t('auth.reset_failed');
  if (code === 'PHONE_NOT_REGISTERED') return t('auth.phone_not_registered');
  if (code === 'PASSWORD_CHANGE_DISABLED') return t('profile.password_unavailable_hint');
  if (code === 'ACCOUNT_DISABLED') return t('auth.login_failed');
  if (code === 'PASSWORD_MIN_LENGTH') return t('auth.password_min_length');
  if (code === 'SMS_CODE_REQUIRED' || code === 'SMS_CODE_INVALID' || code === 'SMS_CODE_EXPIRED') {
    return t('auth.sms_code_required');
  }
  if (code === 'SMS_RATE_LIMIT') return t('auth.send_sms');
  return code;
}

function fieldError(): string {
  if (error.value) return error.value;
  if (smsError.value === 'phone_required') return t('auth.phone_required');
  if (smsError.value === 'PHONE_NOT_REGISTERED') return t('auth.phone_not_registered');
  if (smsError.value) return mapApiError(smsError.value);
  return '';
}

async function submit() {
  if (!sessionId.value) {
    error.value = t('auth.sms_required');
    return;
  }
  if (!smsCode.value.trim()) {
    error.value = t('auth.sms_code_required');
    return;
  }
  if (!password.value || password.value.length < 8) {
    error.value = t('auth.password_min_length');
    return;
  }
  if (password.value !== confirmPassword.value) {
    error.value = t('auth.password_mismatch');
    return;
  }

  loading.value = true;
  error.value = '';
  try {
    await api.post('/player/auth/forgot-password', {
      phone: phone.value.trim(),
      countryCode: getPhoneDialFromIso(countryIso.value),
      smsCode: smsCode.value.trim(),
      sessionId: sessionId.value,
      newPassword: password.value,
    });
    const query: Record<string, string> = { reset: 'success' };
    if (typeof route.query.redirect === 'string' && route.query.redirect) {
      query.redirect = route.query.redirect;
    }
    router.push({ path: '/login', query });
  } catch (e: unknown) {
    const code = (e as { response?: { data?: { error?: string } } })?.response?.data?.error;
    error.value = mapApiError(code);
  } finally {
    loading.value = false;
  }
}

function goLogin() {
  router.push({
    path: '/login',
    query: route.query.redirect ? { redirect: route.query.redirect as string } : {},
  });
}
</script>

<template>
  <div class="login-page" :class="{ 'login-page--desktop': props.desktop }" :style="props.desktop ? undefined : { backgroundImage: `url(${loginBg})` }">
    <div v-if="!props.desktop" class="login-lang">
      <LocaleSwitcher compact />
    </div>
    <div class="login-stack">
      <form @submit.prevent="submit" class="login-form" :class="{ 'ps-gold-frame': !props.desktop, 'is-busy': loading }">
      <div v-if="loading" class="form-busy-overlay" aria-hidden="true">
        <GoldSpinner :size="40" :active="true" />
        <p class="form-busy-text">{{ t('auth.resetting_password') }}</p>
      </div>
      <h2 class="form-title">{{ t('auth.forgot_password_title') }}</h2>

      <div class="field">
        <label>{{ t('auth.phone') }}</label>
        <div class="inline-row">
          <PhoneCountrySelect v-model="countryIso" />
          <input
            v-model="phone"
            class="field-input ps-gold-input"
            type="tel"
            required
            autocomplete="tel-national"
            :disabled="loading"
            :placeholder="t('auth.phone_local_placeholder')"
          />
        </div>
      </div>

      <div class="field">
        <label>{{ t('auth.sms_code') }}</label>
        <div class="inline-row">
          <input
            v-model="smsCode"
            class="field-input ps-gold-input"
            inputmode="numeric"
            maxlength="6"
            autocomplete="one-time-code"
            :disabled="loading"
            :placeholder="t('auth.sms_code_placeholder')"
          />
          <button
            type="button"
            class="btn-secondary"
            :disabled="sending || countdown > 0 || !phone.trim() || loading"
            @click="sendCode"
          >
            {{ countdown > 0 ? `${countdown}s` : t('auth.send_sms') }}
          </button>
        </div>
      </div>

      <div class="field">
        <label>{{ t('auth.password') }}</label>
        <input
          v-model="password"
          class="field-input ps-gold-input"
          type="password"
          required
          autocomplete="new-password"
          minlength="8"
          :disabled="loading"
          :placeholder="t('auth.password_placeholder')"
        />
      </div>

      <div class="field">
        <label>{{ t('auth.confirm_password') }}</label>
        <input
          v-model="confirmPassword"
          class="field-input ps-gold-input"
          type="password"
          required
          autocomplete="new-password"
          minlength="8"
          :disabled="loading"
        />
      </div>

      <p v-if="fieldError()" class="error">{{ fieldError() }}</p>

      <button
        type="submit"
        class="btn-login btn-gold-outline"
        :class="{ 'is-loading': loading }"
        :disabled="loading"
        :aria-busy="loading"
      >
        <span v-if="loading" class="btn-inline-loading">
          <GoldSpinner :size="18" :active="true" />
          {{ t('auth.resetting_password') }}
        </span>
        <span v-else>{{ t('auth.reset_password_btn') }}</span>
      </button>
      <button type="button" class="btn-skip" :disabled="loading" @click="goLogin">
        {{ t('auth.back_to_login') }}
      </button>
      </form>
    </div>
  </div>
</template>

<style scoped>
.login-lang {
  position: absolute;
  top: max(12px, env(safe-area-inset-top));
  right: 16px;
  z-index: 10;
}

.login-page {
  position: relative;
  height: 100%;
  min-height: 100dvh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  padding: 30vh 16px calc(10vh + max(20px, env(safe-area-inset-bottom)));
  background-color: var(--bg-body);
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
}

.login-page--desktop {
  min-height: auto;
  height: auto;
  width: 100%;
  align-items: stretch;
  justify-content: flex-start;
  padding: 0;
  background-color: transparent;
  overflow: visible;
}

.login-page--desktop .login-stack {
  max-width: none;
  width: 100%;
}

.login-stack {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 320px;
}

.login-form {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 14px;
}

.login-form.is-busy {
  pointer-events: none;
}

.form-busy-overlay {
  position: absolute;
  inset: 0;
  z-index: 3;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  border-radius: inherit;
  background: rgba(255, 255, 255, 0.88);
  backdrop-filter: blur(4px);
  pointer-events: all;
}

.form-busy-text {
  margin: 0;
  font-size: 13px;
  font-weight: 700;
  color: var(--primary);
  letter-spacing: 0.04em;
}

.btn-inline-loading {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.login-page--desktop .login-form {
  gap: 10px;
  padding: 0;
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;
}

.form-title {
  margin: 0 0 2px;
  font-size: 16px;
  font-weight: 800;
  color: var(--text);
  text-align: center;
}

.login-page--desktop .form-title {
  margin: 0 0 8px;
  font-size: 18px;
  text-align: left;
  color: var(--primary);
}

.login-page--desktop .field {
  gap: 8px;
}

.login-page--desktop label {
  font-size: 13px;
}

.login-page--desktop .field-input,
.login-page--desktop .btn-secondary {
  height: 46px;
}

.login-page--desktop .btn-login {
  margin-top: 10px;
  min-height: 50px;
  font-size: 15px;
}

.login-page--desktop .btn-skip {
  margin-top: 6px;
  padding: 12px 16px;
  border-radius: var(--radius-sm);
  border: 1px solid var(--border);
  background: var(--bg-card);
}

.login-page--desktop .btn-skip:hover:not(:disabled) {
  border-color: var(--border-active);
  background: var(--surface-accent);
}

.login-page--desktop .error {
  padding: 6px 10px;
  border-radius: var(--radius-sm);
  background: rgba(220, 38, 38, 0.08);
  border-left: 2px solid var(--danger);
}

.btn-login.is-loading:disabled {
  opacity: 1;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

label {
  font-size: 10px;
  color: var(--text-muted);
  font-weight: 600;
  letter-spacing: 0.03em;
}

.field-input {
  width: 100%;
  height: 36px;
  padding: 0 10px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--bg-input);
  color: var(--text);
  font-size: 14px;
  font-family: inherit;
}

.field-input::placeholder {
  color: rgba(0, 0, 0, 0.35);
}

.field-input:focus {
  outline: none;
  border-color: var(--border-gold-soft);
}

.inline-row {
  display: flex;
  gap: 6px;
  align-items: center;
}

.inline-row .field-input {
  flex: 1;
  min-width: 0;
}

.btn-secondary {
  flex-shrink: 0;
  height: 36px;
  padding: 0 10px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--bg-card);
  color: var(--text);
  font-size: 11px;
  font-weight: 600;
  white-space: nowrap;
  cursor: pointer;
}

.btn-secondary:not(:disabled):active {
  border-color: var(--primary);
  background: var(--surface-accent);
  color: var(--text);
}

.btn-secondary:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.btn-login {
  margin-top: 2px;
  padding: 9px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 800;
}

.btn-login:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.btn-skip {
  margin-top: 2px;
  padding: 8px 14px;
  border: none;
  background: transparent;
  color: var(--primary);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
}

.btn-skip:active {
  color: var(--primary-dark);
}

.error {
  margin: 0;
  color: var(--danger);
  font-size: 12px;
  font-weight: 600;
  line-height: 1.3;
}
</style>
