<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 loginBg from '../assets/images/h5bg.webp';

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" :style="{ backgroundImage: `url(${loginBg})` }">
    <div class="login-lang">
      <LocaleSwitcher compact />
    </div>
    <form @submit.prevent="submit" class="login-form ps-gold-frame">
      <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"
            type="tel"
            required
            autocomplete="tel-national"
            :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"
            inputmode="numeric"
            maxlength="6"
            autocomplete="one-time-code"
            :placeholder="t('auth.sms_code_placeholder')"
          />
          <button
            type="button"
            class="btn-secondary"
            :disabled="sending || countdown > 0 || !phone.trim()"
            @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"
          type="password"
          required
          autocomplete="new-password"
          minlength="8"
          :placeholder="t('auth.password_placeholder')"
        />
      </div>

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

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

      <button type="submit" class="btn-login btn-gold-outline" :disabled="loading">
        {{ t('auth.reset_password_btn') }}
      </button>
      <button type="button" class="btn-skip" @click="goLogin">
        {{ t('auth.back_to_login') }}
      </button>
    </form>
  </div>
</template>

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

.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(--tertiary);
  background-size: cover;
  background-position: center top;
  background-repeat: no-repeat;
}

.login-form {
  width: 100%;
  max-width: 320px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
}

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

.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: #0d0d0d;
  color: var(--text);
  font-size: 14px;
  font-family: inherit;
}

.field-input::placeholder {
  color: rgba(255, 255, 255, 0.32);
}

.field-input:focus {
  outline: none;
  border-color: #555;
}

.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: #141414;
  color: var(--text);
  font-size: 11px;
  font-weight: 600;
  white-space: nowrap;
  cursor: pointer;
}

.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: rgba(255, 255, 255, 0.55);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
}

.btn-skip:active {
  color: rgba(255, 255, 255, 0.75);
}

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