<template>
  <div class="vacation-container">
    <Modal 
      :show="showModal"
      :title="modalConfig.title"
      :message="modalConfig.message"
      :type="modalConfig.type"
      :confirmText="modalConfig.confirmText"
      :cancelText="modalConfig.cancelText"
      @confirm="onConfirm"
      @cancel="onCancel"
    />
    <!-- Formular für neuen Urlaubseintrag -->
    <div class="card form-card">
      <form @submit.prevent="createVacation" class="vacation-form">
        <div class="form-group">
          <label for="vacationType">Umfang</label>
          <select 
            id="vacationType" 
            v-model="form.vacationType"
            @change="onTypeChange"
            required
          >
            <option :value="0">Zeitraum</option>
            <option :value="1">Halber Tag</option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="startDate">Urlaubsbeginn</label>
          <input 
            type="date" 
            id="startDate" 
            v-model="form.startDate"
            @change="onStartDateChange"
            required
          />
        </div>
        
        <div class="form-group">
          <label for="endDate">Urlaubsende</label>
          <input 
            type="date" 
            id="endDate" 
            v-model="form.endDate"
            :disabled="form.vacationType === 1"
            :required="form.vacationType === 0"
          />
        </div>
        
        <div class="form-group">
          <button type="submit" class="btn btn-primary" :disabled="loading">
            {{ loading ? 'Wird gespeichert...' : 'Urlaub eintragen' }}
          </button>
        </div>
      </form>
    </div>
    
    <hr class="separator" />
    
    <!-- Tabelle der Urlaubseinträge -->
    <div class="card table-card">
      <div v-if="loading && vacations.length === 0" class="loading">
        Lade Urlaubseinträge...
      </div>
      
      <div v-else-if="vacations.length === 0" class="empty-state">
        Keine Urlaubseinträge vorhanden.
      </div>
      
      <table v-else class="vacation-table">
        <thead>
          <tr>
            <th>Umfang</th>
            <th>Urlaubsbeginn</th>
            <th>Urlaubsende</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="vacation in vacations" :key="vacation.id">
            <td>{{ vacation.type }}</td>
            <td>{{ formatDate(vacation.startDate) }}</td>
            <td>{{ formatDate(vacation.endDate) }}</td>
            <td class="actions">
              <button 
                @click="deleteVacation(vacation.id)"
                class="btn btn-danger btn-small"
                title="Urlaubseintrag löschen"
              >
                Löschen
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </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 vacations = ref([])
const loading = ref(false)

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

const form = ref({
  vacationType: 0, // 0 = Zeitraum, 1 = Halber Tag
  startDate: '',
  endDate: ''
})

// Wenn Typ geändert wird
function onTypeChange() {
  if (form.value.vacationType === 1) {
    // Halber Tag: endDate = startDate
    form.value.endDate = form.value.startDate
  }
}

// Wenn Startdatum geändert wird bei "Halber Tag"
function onStartDateChange() {
  if (form.value.vacationType === 1) {
    form.value.endDate = form.value.startDate
  }
}

// Lade alle Urlaubseinträge
async function loadVacations() {
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/vacation`, {
      headers: authStore.getAuthHeaders()
    })
    
    if (!response.ok) throw new Error('Fehler beim Laden der Urlaubseinträge')
    
    vacations.value = await response.json()
  } catch (error) {
    console.error('Fehler beim Laden der Urlaubseinträge:', error)
    await alert('Fehler beim Laden der Urlaubseinträge', 'Fehler')
  } finally {
    loading.value = false
  }
}

// Erstelle neuen Urlaubseintrag
async function createVacation() {
  if (!form.value.startDate || (form.value.vacationType === 0 && !form.value.endDate)) {
    await alert('Bitte füllen Sie alle Felder aus')
    return
  }
  
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/vacation`, {
      method: 'POST',
      headers: {
        ...authStore.getAuthHeaders(),
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        vacationType: form.value.vacationType,
        startDate: form.value.startDate,
        endDate: form.value.endDate
      })
    })
    
    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Fehler beim Erstellen des Urlaubseintrags')
    }
    
    resetForm()
    await loadVacations()
  } catch (error) {
    console.error('Fehler beim Erstellen des Urlaubseintrags:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

// Lösche Urlaubseintrag
async function deleteVacation(id) {
  const confirmed = await confirm('Möchten Sie diesen Urlaubseintrag wirklich löschen?', 'Urlaubseintrag löschen')
  
  if (!confirmed) {
    return
  }
  
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/vacation/${id}`, {
      method: 'DELETE',
      headers: authStore.getAuthHeaders()
    })
    
    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Fehler beim Löschen des Urlaubseintrags')
    }
    
    await loadVacations()
  } catch (error) {
    console.error('Fehler beim Löschen des Urlaubseintrags:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

// Formatiere Datum
function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString + 'T00:00:00')
  return date.toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

// Formular zurücksetzen
function resetForm() {
  form.value = {
    vacationType: 0,
    startDate: '',
    endDate: ''
  }
}

onMounted(() => {
  loadVacations()
})
</script>

<style scoped>
.vacation-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

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

.separator {
  border: none;
  border-top: 1px solid #e0e0e0;
  margin: 24px 0;
}

/* Formular */
.vacation-form {
  display: flex;
  gap: 16px;
  align-items: flex-end;
}

.form-group {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.form-group:last-child {
  flex: 0;
}

label {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
  color: #555;
}

input, select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

input:focus, select:focus {
  outline: none;
  border-color: #4CAF50;
}

input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

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

.btn-primary {
  background: #4CAF50;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #45a049;
}

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

/* Tabelle */
.vacation-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.vacation-table thead {
  background: #f8f9fa;
}

.vacation-table th {
  padding: 12px;
  text-align: left;
  font-weight: 600;
  color: #555;
  border-bottom: 2px solid #ddd;
}

.vacation-table td {
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.vacation-table tbody tr:hover {
  background: #f8f9fa;
}

.vacation-table .actions {
  text-align: center;
  width: 120px;
}

.btn-small {
  padding: 6px 12px;
  font-size: 13px;
}

.btn-danger {
  background: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background: #c0392b;
}

.loading, .empty-state {
  text-align: center;
  padding: 40px;
  color: #7f8c8d;
}
</style>

