<template>
  <div class="sick-page">
    <div class="card">
      <!-- Formular zum Erstellen eines neuen Krankheitseintrags -->
      <form @submit.prevent="createSick" class="sick-form">
        <div class="form-row">
          <div class="form-group">
            <label for="startDate">Erster Krankheitstag</label>
            <input 
              type="date" 
              id="startDate" 
              v-model="form.startDate" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="endDate">Letzter Krankheitstag</label>
            <input 
              type="date" 
              id="endDate" 
              v-model="form.endDate"
            >
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="sickType">Wer war krank?</label>
            <select 
              id="sickType" 
              v-model="form.sickTypeId" 
              required
            >
              <option value="">Bitte wählen...</option>
              <option 
                v-for="type in sickTypes" 
                :key="type.id" 
                :value="type.id"
              >
                {{ type.name }}
              </option>
            </select>
          </div>

          <div class="form-group">
            <button type="submit" class="btn btn-primary" :disabled="loading">
              {{ loading ? 'Wird gespeichert...' : 'Erkrankung eintragen' }}
            </button>
          </div>
        </div>
      </form>

      <hr>

      <!-- Tabelle mit bestehenden Krankheitseinträgen -->
      <table class="sick-table">
        <thead>
          <tr>
            <th>Erster Krankheitstag</th>
            <th>Letzter Krankheitstag</th>
            <th>Wer war krank?</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="sickEntries.length === 0">
            <td colspan="4" class="no-data">Keine Krankheitseinträge vorhanden</td>
          </tr>
          <tr v-for="sick in sickEntries" :key="sick.id">
            <td>{{ formatDate(sick.startDate) }}</td>
            <td>{{ formatDate(sick.endDate) }}</td>
            <td>{{ sick.sickTypeName }}</td>
            <td>
              <button 
                @click="deleteSick(sick.id)" 
                class="btn btn-delete"
                :disabled="loading"
              >
                Löschen
              </button>
            </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 sickEntries = ref([])
const sickTypes = ref([])
const loading = ref(false)

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

const form = ref({
  startDate: new Date().toISOString().split('T')[0],
  endDate: '',
  sickTypeId: ''
})

// Lade alle Krankheitseinträge
async function loadSickEntries() {
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/sick`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('Fehler beim Laden der Krankheitseinträge')
    }
    
    sickEntries.value = await response.json()
  } catch (error) {
    console.error('Fehler beim Laden der Krankheitseinträge:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

// Lade alle Krankheitstypen
async function loadSickTypes() {
  try {
    const response = await fetch(`${API_URL}/sick/types`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('Fehler beim Laden der Krankheitstypen')
    }
    
    sickTypes.value = await response.json()
  } catch (error) {
    console.error('Fehler beim Laden der Krankheitstypen:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  }
}

// Erstelle neuen Krankheitseintrag
async function createSick() {
  if (!form.value.startDate || !form.value.sickTypeId || form.value.sickTypeId === '') {
    await alert('Bitte füllen Sie alle Pflichtfelder aus', 'Fehlende Angaben')
    return
  }
  
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/sick`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: JSON.stringify({
        sickTypeId: form.value.sickTypeId, // Sende gehashte ID
        startDate: form.value.startDate,
        endDate: form.value.endDate || form.value.startDate
      })
    })
    
    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Fehler beim Erstellen des Krankheitseintrags')
    }
    
    // Formular zurücksetzen
    resetForm()
    
    // Liste neu laden
    await loadSickEntries()
  } catch (error) {
    console.error('Fehler beim Erstellen des Krankheitseintrags:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

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

// Formatiere Datum für Anzeige (DD.MM.YYYY)
function formatDate(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr + 'T00:00:00')
  return date.toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

// Formular zurücksetzen
function resetForm() {
  form.value = {
    startDate: new Date().toISOString().split('T')[0],
    endDate: '',
    sickTypeId: ''
  }
}

// Initiales Laden
onMounted(async () => {
  await Promise.all([
    loadSickTypes(),
    loadSickEntries()
  ])
})
</script>

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

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

.sick-form {
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  align-items: flex-end;
}

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

.form-group label {
  font-weight: 500;
  margin-bottom: 6px;
  font-size: 13px;
  color: #333;
}

.form-group input,
.form-group select {
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 13px;
  font-family: inherit;
}

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

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

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

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

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

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

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

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  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);
}

.btn-delete {
  background: #f44336;
  color: white;
  padding: 6px 12px;
  font-size: 12px;
}

.btn-delete:hover:not(:disabled) {
  background: #da190b;
}
</style>

