<template>
  <q-page class="reset-password-page">
    <div class="page-shell">
      <q-card flat bordered class="reset-card">
        <q-card-section class="card-head">
          <p class="eyebrow">Account security</p>
          <h1>Reset Password</h1>
          <p class="subtitle">Imposta una nuova password usando il token ricevuto via email.</p>
        </q-card-section>

        <q-separator />

        <q-card-section class="card-body">
          <q-input
            v-model="token"
            label="Token"
            outlined
            autogrow
            type="textarea"
            :hint="tokenHint"
          />

          <q-input
            v-model="password"
            label="Nuova password"
            outlined
            :type="showPassword ? 'text' : 'password'"
          >
            <template #append>
              <q-icon
                :name="showPassword ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="showPassword = !showPassword"
              />
            </template>
          </q-input>

          <q-input
            v-model="confirmPassword"
            label="Conferma password"
            outlined
            :type="showConfirmPassword ? 'text' : 'password'"
          >
            <template #append>
              <q-icon
                :name="showConfirmPassword ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="showConfirmPassword = !showConfirmPassword"
              />
            </template>
          </q-input>

          <div v-if="errorMessage" class="msg msg-error">
            {{ errorMessage }}
          </div>

          <div v-if="successMessage" class="msg msg-success">
            {{ successMessage }}
          </div>
        </q-card-section>

        <q-card-actions align="right" class="card-actions">
          <q-btn
            color="primary"
            icon="lock_reset"
            label="Aggiorna password"
            :loading="loading"
            @click="submitReset"
          />
        </q-card-actions>
      </q-card>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { resetPassword } from 'src/api/api';

const route = useRoute();

const token = ref(getTokenFromRoute());
const password = ref('');
const confirmPassword = ref('');
const loading = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const errorMessage = ref('');
const successMessage = ref('');

const tokenHint = computed(() => {
  return token.value.trim().length > 0
    ? 'Token caricato da URL, puoi comunque modificarlo.'
    : 'Inserisci il token ricevuto via email.';
});

function getTokenFromRoute(): string {
  const routeToken = route.query.token;
  if (typeof routeToken === 'string') {
    return routeToken;
  }

  if (Array.isArray(routeToken) && routeToken.length > 0) {
    return String(routeToken[0]);
  }

  return '';
}

function validateForm(): boolean {
  errorMessage.value = '';
  successMessage.value = '';

  if (!token.value.trim()) {
    errorMessage.value = 'Token mancante.';
    return false;
  }

  if (!password.value) {
    errorMessage.value = 'Inserisci una nuova password.';
    return false;
  }

  if (password.value.length < 8) {
    errorMessage.value = 'La password deve avere almeno 8 caratteri.';
    return false;
  }

  if (password.value !== confirmPassword.value) {
    errorMessage.value = 'Le password non coincidono.';
    return false;
  }

  return true;
}

async function submitReset(): Promise<void> {
  if (!validateForm()) {
    return;
  }

  loading.value = true;
  errorMessage.value = '';
  successMessage.value = '';

  try {
    const response = await resetPassword({
      token: token.value.trim(),
      password: password.value,
    });

    if (response.error) {
      errorMessage.value = response.error;
      return;
    }

    successMessage.value = response.data?.message || 'Password aggiornata con successo.';
    password.value = '';
    confirmPassword.value = '';
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : String(error);
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.reset-password-page {
  min-height: 100vh;
  padding: 24px 14px;
  background:
    radial-gradient(circle at 88% 15%, #f8dfd0 0%, transparent 32%),
    radial-gradient(circle at 15% 10%, #d9f6f2 0%, transparent 36%),
    linear-gradient(140deg, #f6f3ee 0%, #edf8f8 100%);
}

.page-shell {
  max-width: 640px;
  margin: 0 auto;
}

.reset-card {
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.86);
}

.card-head {
  padding-bottom: 10px;
}

.eyebrow {
  margin: 0;
  letter-spacing: 0.18em;
  text-transform: uppercase;
  color: #345569;
  font-size: 11px;
  font-weight: 700;
}

.card-head h1 {
  margin: 4px 0;
  font-family: 'Space Grotesk', sans-serif;
  font-size: clamp(1.5rem, 2.6vw, 2rem);
}

.subtitle {
  margin: 0;
  color: #536979;
}

.card-body {
  display: grid;
  gap: 12px;
}

.msg {
  border-radius: 10px;
  padding: 10px 12px;
  font-size: 0.95rem;
}

.msg-error {
  background: #fdeceb;
  color: #8f2222;
}

.msg-success {
  background: #e9f8ef;
  color: #1f6a3f;
}

.card-actions {
  padding: 8px 16px 16px;
}
</style>
