<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">Accesso</div>
          <div class="text-h4">Login</div>
          <div class="text-body2 text-grey-7">Accedi con email e password.</div>
        </q-card-section>

        <q-separator />

        <q-card-section>
          <q-form class="auth-form" @submit.prevent="submit">
            <q-input
              v-model="form.username"
              outlined
              type="email"
              label="Email"
              autocomplete="username"
            />
            <q-input
              v-model="form.password"
              outlined
              :type="showPassword ? 'text' : 'password'"
              label="Password"
              autocomplete="current-password"
            >
              <template #append>
                <q-icon
                  :name="showPassword ? 'visibility_off' : 'visibility'"
                  class="cursor-pointer"
                  @click="showPassword = !showPassword"
                />
              </template>
            </q-input>
            <q-btn color="primary" label="Accedi" type="submit" :loading="loading" />
          </q-form>
        </q-card-section>

        <q-separator />

        <q-card-section class="auth-links">
          <router-link to="/recoverpassword">Password dimenticata?</router-link>
          <router-link to="/signup">Crea account</router-link>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { login } from 'src/api/api';

const router = useRouter();
const $q = useQuasar();
const loading = ref(false);
const showPassword = ref(false);
const form = reactive({
  username: '',
  password: '',
});

async function submit(): Promise<void> {
  loading.value = true;
  try {
    const response = await login({
      username: form.username.trim(),
      password: form.password,
    });
    if (response.error) {
      throw new Error(response.error);
    }
    $q.notify({ type: 'positive', message: 'Login effettuato.' });
    await router.push('/');
  } 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: space-between;
  gap: 12px;
}
</style>
