<template>
  <div class="invite-page">
    <div class="card">
      <!-- Formular zum Senden einer Einladung -->
      <form @submit.prevent="sendInvite" class="invite-form">
        <h3>Einladung versenden</h3>
        
        <div class="form-group">
          <label for="email">Email-Adresse</label>
          <input 
            type="email" 
            id="email" 
            v-model="form.email"
            placeholder="name@beispiel.de"
            required
          >
          <small class="help-text">
            Der Empfänger erhält eine Email mit einem Registrierungslink, der 7 Tage gültig ist.
          </small>
        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-primary" :disabled="loading">
            {{ loading ? 'Wird gesendet...' : 'Einladung senden' }}
          </button>
        </div>
      </form>

      <hr>

      <!-- Tabelle mit gesendeten Einladungen -->
      <h3>Gesendete Einladungen</h3>
      <table class="invitations-table">
        <thead>
          <tr>
            <th>Email-Adresse</th>
            <th>Gesendet am</th>
            <th>Gültig bis</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="invitations.length === 0">
            <td colspan="4" class="no-data">Keine Einladungen versendet</td>
          </tr>
          <tr v-for="invitation in invitations" :key="invitation.id">
            <td>{{ invitation.email }}</td>
            <td>{{ formatDateTime(invitation.createdAt) }}</td>
            <td>{{ formatDateTime(invitation.expiresAt) }}</td>
            <td>
              <span class="status-badge" :class="getStatusClass(invitation)">
                {{ getStatusText(invitation) }}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Modal-Komponente -->
    <Modal 
      v-if="showModal"
      :show="showModal"
      :title="modalConfig.title"
      :message="modalConfig.message"
      :type="modalConfig.type"
      :confirmText="modalConfig.confirmText"
      :cancelText="modalConfig.cancelText"
      @confirm="onConfirm" 
      @cancel="onCancel" 
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../stores/authStore'
import { useModal } from '../composables/useModal'
import Modal from '../components/Modal.vue'
import { API_BASE_URL } from '@/config/api'

const API_URL = API_BASE_URL
const authStore = useAuthStore()
const invitations = ref([])
const loading = ref(false)

const { showModal, modalConfig, alert, confirm, onConfirm, onCancel } = useModal()

const form = ref({
  email: ''
})

// Lade alle Einladungen
async function loadInvitations() {
  try {
    const response = await fetch(`${API_URL}/invite`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('Fehler beim Laden der Einladungen')
    }
    
    invitations.value = await response.json()
  } catch (error) {
    console.error('Fehler beim Laden der Einladungen:', error)
  }
}

// Sende Einladung
async function sendInvite() {
  if (!form.value.email) {
    await alert('Bitte geben Sie eine Email-Adresse ein', 'Fehlende Angaben')
    return
  }
  
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/invite`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: JSON.stringify({
        email: form.value.email
      })
    })
    
    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Fehler beim Senden der Einladung')
    }
    
    await alert('Einladung erfolgreich versendet!', 'Erfolg')
    
    // Formular zurücksetzen
    form.value.email = ''
    
    // Liste neu laden
    await loadInvitations()
  } catch (error) {
    console.error('Fehler beim Senden der Einladung:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

// Formatiere Datum und Zeit
function formatDateTime(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// Status-Text ermitteln
function getStatusText(invitation) {
  if (invitation.status === 'accepted') {
    return 'Angenommen'
  }
  if (invitation.isExpired) {
    return 'Abgelaufen'
  }
  return 'Ausstehend'
}

// Status-CSS-Klasse ermitteln
function getStatusClass(invitation) {
  if (invitation.status === 'accepted') {
    return 'accepted'
  }
  if (invitation.isExpired) {
    return 'expired'
  }
  return 'pending'
}

// Initiales Laden
onMounted(() => {
  loadInvitations()
})
</script>

<style scoped>
.invite-page {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.invite-form h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 16px;
}

.form-group label {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.form-group input {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
}

.form-group input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
}

.help-text {
  font-size: 12px;
  color: #666;
  font-style: italic;
}

.form-actions {
  margin-top: 8px;
}

hr {
  border: none;
  border-top: 1px solid #eee;
  margin: 24px 0;
}

h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
}

.invitations-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

.invitations-table th {
  text-align: left;
  padding: 10px 8px;
  background: #f5f5f5;
  border-bottom: 2px solid #ddd;
  font-weight: 600;
  font-size: 12px;
  color: #666;
}

.invitations-table td {
  padding: 10px 8px;
  border-bottom: 1px solid #eee;
}

.invitations-table tbody tr:hover {
  background: #f9f9f9;
}

.no-data {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 20px !important;
}

.status-badge {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
}

.status-badge.pending {
  background: #fff3cd;
  color: #856404;
}

.status-badge.accepted {
  background: #d4edda;
  color: #155724;
}

.status-badge.expired {
  background: #f8d7da;
  color: #721c24;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  font-family: inherit;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  box-shadow: 0 2px 4px rgba(76, 175, 80, 0.3);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(76, 175, 80, 0.4);
}
</style>

