<template>
  <div class="timewish-page">
    <div class="card">
      <!-- Formular zum Erstellen eines Zeitwunsches -->
      <form @submit.prevent="createTimewish" class="timewish-form">
        <h3>Zeitwunsch hinzufügen</h3>
        
        <div class="form-row">
          <div class="form-group">
            <label for="day">Wochentag</label>
            <select 
              id="day" 
              v-model.number="form.day" 
              required
            >
              <option :value="1">Montag</option>
              <option :value="2">Dienstag</option>
              <option :value="3">Mittwoch</option>
              <option :value="4">Donnerstag</option>
              <option :value="5">Freitag</option>
              <option :value="6">Samstag</option>
              <option :value="7">Sonntag</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="wishtype">Typ</label>
            <select 
              id="wishtype" 
              v-model.number="form.wishtype" 
              required
              @change="onWishtypeChange"
            >
              <option :value="0">Kein Wunsch</option>
              <option :value="1">Frei</option>
              <option :value="2">Arbeit</option>
            </select>
          </div>

          <div class="form-group" v-if="form.wishtype === 2">
            <label for="hours">Stunden</label>
            <input 
              type="number" 
              id="hours" 
              v-model.number="form.hours" 
              min="0"
              max="24"
              step="0.5"
              :required="form.wishtype === 2"
            >
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="startDate">Gültig ab</label>
            <input 
              type="date" 
              id="startDate" 
              v-model="form.startDate" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="endDate">Gültig bis (optional)</label>
            <input 
              type="date" 
              id="endDate" 
              v-model="form.endDate"
            >
            <small class="help-text">Leer lassen für unbegrenzten Zeitraum</small>
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-primary" :disabled="loading">
            {{ loading ? 'Wird gespeichert...' : 'Zeitwunsch hinzufügen' }}
          </button>
        </div>
      </form>

      <hr>

      <!-- Tabelle mit bestehenden Zeitwünschen -->
      <table class="timewish-table">
        <thead>
          <tr>
            <th>Wochentag</th>
            <th>Typ</th>
            <th>Stunden</th>
            <th>Gültig ab</th>
            <th>Gültig bis</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="timewishes.length === 0">
            <td colspan="6" class="no-data">Keine Zeitwünsche definiert</td>
          </tr>
          <tr v-for="timewish in timewishes" :key="timewish.id">
            <td>{{ timewish.dayName }}</td>
            <td>{{ timewish.wishtypeName }}</td>
            <td>{{ timewish.wishtype === 2 ? timewish.hours : '—' }}</td>
            <td>{{ formatDate(timewish.startDate) }}</td>
            <td>{{ timewish.endDate ? formatDate(timewish.endDate) : 'unbegrenzt' }}</td>
            <td>
              <button 
                @click="deleteTimewish(timewish.id)" 
                class="btn btn-delete-small"
                :disabled="loading"
              >
                ×
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="info-box">
        <h4>Hinweise:</h4>
        <ul>
          <li><strong>Typ "Arbeit"</strong>: Legt fest, wie viele Stunden an diesem Wochentag gearbeitet werden sollen</li>
          <li><strong>Typ "Frei"</strong>: Markiert diesen Wochentag als arbeitsfrei (z.B. für 4-Tage-Woche)</li>
          <li><strong>Typ "Kein Wunsch"</strong>: Verwendet den Grundwert aus den persönlichen Einstellungen</li>
          <li><strong>Zeitraum</strong>: Zeitwünsche können zeitlich begrenzt werden (z.B. Sommermonate, Teilzeit-Phase)</li>
          <li><strong>Überschneidungen</strong>: Pro Wochentag kann es keine überlappenden Zeiträume geben</li>
        </ul>
      </div>
    </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 timewishes = ref([])
const loading = ref(false)

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

const form = ref({
  day: 1,
  wishtype: 2,
  hours: 8,
  startDate: new Date().toISOString().split('T')[0],
  endDate: ''
})

// Wenn Wishtype geändert wird
function onWishtypeChange() {
  if (form.value.wishtype !== 2) {
    form.value.hours = 0
  } else {
    form.value.hours = 8
  }
}

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

// Erstelle neuen Zeitwunsch
async function createTimewish() {
  if (form.value.wishtype === 2 && (!form.value.hours || form.value.hours <= 0)) {
    await alert('Bitte geben Sie die Arbeitsstunden an', 'Fehlende Angaben')
    return
  }
  
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/timewish`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: JSON.stringify({
        day: form.value.day,
        wishtype: form.value.wishtype,
        hours: form.value.hours,
        startDate: form.value.startDate,
        endDate: form.value.endDate || null
      })
    })
    
    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Fehler beim Erstellen des Zeitwunsches')
    }
    
    // Formular zurücksetzen
    resetForm()
    
    // Liste neu laden
    await loadTimewishes()
  } catch (error) {
    console.error('Fehler beim Erstellen des Zeitwunsches:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

// Lösche Zeitwunsch
async function deleteTimewish(id) {
  const confirmed = await confirm('Möchten Sie diesen Zeitwunsch wirklich löschen?', 'Zeitwunsch löschen')
  
  if (!confirmed) {
    return
  }
  
  try {
    loading.value = true
    const response = await fetch(`${API_URL}/timewish/${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 Zeitwunsches')
    }
    
    await loadTimewishes()
  } catch (error) {
    console.error('Fehler beim Löschen des Zeitwunsches:', 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 = {
    day: 1,
    wishtype: 2,
    hours: 8,
    startDate: new Date().toISOString().split('T')[0],
    endDate: ''
  }
}

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

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

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

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

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

.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);
}

.help-text {
  font-size: 11px;
  color: #666;
  font-style: italic;
  margin-top: 2px;
}

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

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

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

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

.timewish-table th:last-child {
  width: 40px;
}

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

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

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

.info-box {
  background: #f0f8ff;
  border: 1px solid #d0e8ff;
  border-radius: 4px;
  padding: 16px;
  margin-top: 20px;
}

.info-box h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #1976d2;
}

.info-box ul {
  margin: 0;
  padding-left: 20px;
}

.info-box li {
  margin: 6px 0;
  font-size: 13px;
  color: #555;
  line-height: 1.5;
}

.info-box strong {
  color: #333;
}

.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-small {
  background: #f44336;
  color: white;
  padding: 4px 8px;
  font-size: 16px;
  line-height: 1;
  border-radius: 3px;
}

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

