<template>
  <div class="forgot-password-container">
    <h2>{{ $t('auth.forgotPassword') }}</h2>
    <p class="description">{{ $t('auth.forgotPasswordDescription') }}</p>

    <form v-if="!emailSent" @submit.prevent="submitRequest">
      <input
        v-model="email"
        type="email"
        :placeholder="$t('auth.email')"
        required
        :disabled="loading"
      />
      <button type="submit" :disabled="loading">
        {{ loading ? $t('auth.sending') : $t('auth.sendResetLink') }}
      </button>
    </form>

    <div v-else class="success-message">
      <p>{{ $t('auth.resetEmailSent') }}</p>
    </div>

    <div class="back-to-login">
      <router-link to="/login">← {{ $t('auth.toLogin') }}</router-link>
    </div>

    <!-- Info Dialog -->
    <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
    />
  </div>
</template>

<script>
import apiClient from '../apiClient.js';
import InfoDialog from '../components/InfoDialog.vue';
import { buildInfoConfig, safeErrorMessage } from '../utils/dialogUtils.js';

export default {
  components: { InfoDialog },
  data() {
    return {
      email: '',
      loading: false,
      emailSent: false,
      infoDialog: {
        isOpen: false,
        title: '',
        message: '',
        details: '',
        type: 'info'
      }
    };
  },
  methods: {
    async showInfo(title, message, details = '', type = 'info') {
      this.infoDialog = buildInfoConfig({ title, message, details, type });
    },
    async submitRequest() {
      this.loading = true;
      try {
        await apiClient.post('/auth/forgot-password', { email: this.email });
        this.emailSent = true;
      } catch (error) {
        const message = safeErrorMessage(error, this.$t('auth.resetRequestFailed'));
        await this.showInfo(this.$t('messages.error'), message, '', 'error');
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.forgot-password-container {
  max-width: 400px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.description {
  color: #666;
  margin-bottom: 1.5rem;
  line-height: 1.5;
}

.success-message {
  background-color: #e8f5e9;
  border: 1px solid #4caf50;
  border-radius: 6px;
  padding: 1rem;
  color: #2e7d32;
  line-height: 1.5;
}

.back-to-login {
  margin-top: 1.5rem;
  text-align: center;
}

.back-to-login a {
  color: #1976d2;
  text-decoration: none;
}

.back-to-login a:hover {
  text-decoration: underline;
}

form input {
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 1rem;
}

form button {
  width: 100%;
}

form button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
