<template>
  <q-page class="auth-page">
    <div class="auth-shell">
      <q-card flat bordered class="auth-card">
        <q-card-section>
          <div class="text-overline text-primary">Recupero</div>
          <div class="text-h4">Recover password</div>
          <div class="text-body2 text-grey-7">Invia la mail di recupero password.</div>
        </q-card-section>

        <q-separator />

        <q-card-section>
          <q-form v-if="!sent" class="auth-form" @submit.prevent="submit">
            <q-input
              v-model="email"
              outlined
              type="email"
              label="Email"
              autocomplete="email"
            />
            <q-btn color="primary" label="Invia email" type="submit" :loading="loading" />
          </q-form>

          <div v-else class="success-state">
            <q-icon name="mark_email_read" size="56px" color="positive" />
            <div class="text-h6">Email inviata</div>
            <div class="text-body2 text-grey-7">
              Se l'indirizzo esiste, riceverai un messaggio con le istruzioni per reimpostare la password.
            </div>
            <q-btn color="primary" label="Home" to="/" />
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section v-if="!sent" class="auth-links">
          <router-link to="/login">Torna al login</router-link>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { forgotPassword } from 'src/api/api';

const $q = useQuasar();
const loading = ref(false);
const email = ref('');
const sent = ref(false);

async function submit(): Promise<void> {
  loading.value = true;
  try {
    const response = await forgotPassword({ email: email.value.trim() });
    if (response.error) {
      throw new Error(response.error);
    }
    sent.value = true;
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: error instanceof Error ? error.message : String(error),
    });
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.auth-page {
  background: linear-gradient(180deg, #f7fafc 0%, #e9f0f7 100%);
}

.auth-shell {
  max-width: 520px;
  margin: 0 auto;
  padding: 40px 20px;
}

.auth-card {
  border-radius: 24px;
}

.auth-form {
  display: grid;
  gap: 14px;
}

.auth-links {
  display: flex;
  justify-content: flex-end;
}

.success-state {
  display: grid;
  justify-items: center;
  gap: 12px;
  text-align: center;
  padding: 12px 0;
}
</style>
