<template>
  <div class="week-overview">
    <div class="card">

      <div v-if="loading" class="loading">
        Lade Daten...
      </div>

      <div v-else class="week-content">
        <div class="week-header">
          <button @click="previousWeek" class="btn btn-secondary">← Vorherige Woche</button>
          <h3>{{ weekRange }}</h3>
          <button @click="nextWeek" class="btn btn-secondary">Nächste Woche →</button>
        </div>

        <table class="week-table">
          <thead>
            <tr>
              <th>Tag</th>
              <th>Datum</th>
              <th>Zeiten</th>
              <th>Arbeitszeit</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="day in weekDays" :key="day.date" :class="{ 'current-day': day.isToday }">
              <td class="day-name">{{ day.name }}</td>
              <td>{{ day.date }}</td>
              <td class="times-cell">
                <!-- Mehrere Arbeitsblöcke unterstützen -->
                <template v-if="day.workBlocks && day.workBlocks.length > 0">
                  <div v-for="(block, blockIndex) in day.workBlocks" :key="blockIndex" class="work-block">
                    <div class="time-entry">
                      <strong v-if="day.workBlocks.length > 1">Arbeitszeit {{ blockIndex + 1 }}: </strong>
                      <strong v-else>Arbeitszeit: </strong>
                      <template v-if="block.workTimeFixed && block.workTimeOriginal">
                        <span 
                          class="time-fixed" 
                          :title="`Original: ${block.workTimeOriginal}`"
                        >
                          {{ block.workTime }}
                        </span>
                      </template>
                      <template v-else>
                        {{ block.workTime }}
                      </template>
                    </div>
                    <div v-for="(pause, pIndex) in block.pauses" :key="pIndex" class="time-entry pause-entry">
                      <template v-if="block.pauses.length > 1">Pause {{ pIndex + 1 }}: </template>
                      <template v-else>Pause: </template>
                      <template v-if="pause.fixed && pause.original">
                        <span 
                          class="time-fixed" 
                          :title="`Original: ${pause.original}`"
                        >
                          {{ pause.time || pause }}
                        </span>
                      </template>
                      <template v-else>
                        {{ pause.time || pause }}
                      </template>
                    </div>
                  </div>
                </template>
                <!-- Fallback für alte Datenstruktur -->
                <template v-else-if="day.workTime">
                  <div class="time-entry">
                    <strong>Arbeitszeit:</strong> 
                    <template v-if="day.workTimeFixed && day.workTimeOriginal">
                      <span 
                        class="time-fixed" 
                        :title="`Original: ${day.workTimeOriginal}`"
                      >
                        {{ day.workTime }}
                      </span>
                    </template>
                    <template v-else>
                      {{ day.workTime }}
                    </template>
                  </div>
                  <div v-for="(pause, index) in day.pauses" :key="index" class="time-entry pause-entry">
                    <template v-if="day.pauses.length > 1">Pause {{ index + 1 }}: </template>
                    <template v-else>Pause: </template>
                    <template v-if="pause.fixed && pause.original">
                      <span 
                        class="time-fixed" 
                        :title="`Original: ${pause.original}`"
                      >
                        {{ pause.time || pause }}
                      </span>
                    </template>
                    <template v-else>
                      {{ pause.time || pause }}
                    </template>
                  </div>
                </template>
              </td>
              <td class="total-cell">
                <!-- Wenn workBlocks vorhanden sind, zeige Block-basierte Werte -->
                <template v-if="day.workBlocks && day.workBlocks.length > 0">
                  <template v-for="(block, blockIndex) in day.workBlocks" :key="blockIndex">
                    <div v-if="block.totalWorkTime" class="total-work-time">
                      {{ block.totalWorkTime }}
                    </div>
                    <div v-for="(pauseTime, pIndex) in block.pauseTimes" :key="`${blockIndex}-${pIndex}`" class="total-pause-time">
                      - <span 
                          :class="{ 'time-fixed': pauseTime.fixed }" 
                          :title="pauseTime.original ? `Original: ${pauseTime.original}` : ''"
                        >
                          {{ pauseTime.time || pauseTime }}
                        </span>
                    </div>
                    <div v-if="block.netWorkTime" class="net-work-time">
                      = <strong>{{ block.netWorkTime }}</strong>
                    </div>
                  </template>
                  
                  <!-- Gesamt-Nettozeit (falls mehrere Blöcke) -->
                  <div v-if="day.workBlocks.length > 1 && day.netWorkTime" class="total-net-work-time">
                    <strong>Gesamt: {{ day.netWorkTime }}</strong>
                  </div>
                </template>
                
                <!-- Fallback für alte Struktur -->
                <template v-else>
                  <div v-if="day.totalWorkTime" class="total-work-time">
                    {{ day.totalWorkTime }}
                  </div>
                  <div v-for="(pauseTime, index) in day.pauseTimes" :key="index" class="total-pause-time">
                    - <span 
                        :class="{ 'time-fixed': pauseTime.fixed }" 
                        :title="pauseTime.original ? `Original: ${pauseTime.original}` : ''"
                      >
                        {{ pauseTime.time || pauseTime }}
                      </span>
                  </div>
                  <div v-if="day.netWorkTime" class="net-work-time">
                    = <strong>{{ day.netWorkTime }}</strong>
                  </div>
                </template>
                
                <!-- Vacation, Sick und Holiday werden immer angezeigt -->
                <div v-if="day.holiday" class="holiday-time">
                  + {{ day.holiday.hours }}:00 Feiertag
                </div>
                <div v-if="day.vacation" class="vacation-time">
                  + {{ day.vacation.hours }}:00 Urlaub
                </div>
                <div v-if="day.sick" class="sick-time">
                  8:00 ({{ day.sick.type === 'self' ? 'Krank' : day.sick.type === 'child' ? 'Kind krank' : day.sick.type === 'parents' ? 'Eltern krank' : 'Partner krank' }})
                </div>
              </td>
              <td>
                <span v-if="day.status" class="status-badge" :class="`status-${day.status}`">
                  {{ day.statusText }}
                </span>
              </td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="summary-row">
              <td colspan="3"><strong>Wochensumme</strong></td>
              <td class="total-hours"><strong>{{ weekTotal }}</strong></td>
              <td></td>
            </tr>
            <tr v-if="weekData?.nonWorkingDays > 0" class="summary-row non-working-info">
              <td colspan="3" class="non-working-label">
                <strong>Arbeitsfreie Tage ({{ weekData.nonWorkingDays }}):</strong>
                <span v-for="(detail, index) in weekData.nonWorkingDetails" :key="index" class="non-working-detail">
                  {{ formatDate(detail.date) }}: {{ detail.type }} ({{ detail.hours }}h)
                  <span v-if="index < weekData.nonWorkingDetails.length - 1">, </span>
                </span>
              </td>
              <td class="non-working-total"><strong>{{ weekData.nonWorkingTotal }}</strong></td>
              <td></td>
            </tr>
            <tr class="summary-row total-all-row">
              <td colspan="3"><strong>Gesamtsumme</strong></td>
              <td class="total-all-hours"><strong>{{ weekData?.totalAll || weekTotal }}</strong></td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useAuthStore } from '../stores/authStore'
import { API_BASE_URL } from '@/config/api'

const API_URL = API_BASE_URL

const authStore = useAuthStore()

const loading = ref(true)
const weekData = ref(null)
const weekOffset = ref(0)

const weekDays = computed(() => {
  if (!weekData.value) return []
  
  return weekData.value.days.map(day => ({
    ...day,
    date: formatDate(day.date),
    name: day.name
  }))
})

const weekRange = computed(() => {
  if (!weekData.value) return ''
  
  const start = formatDate(weekData.value.weekStart)
  const end = formatDate(weekData.value.weekEnd)
  
  return `${start} - ${end}`
})

const weekTotal = computed(() => {
  return weekData.value?.weekTotal || '0:00'
})

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

const loadWeekData = async () => {
  try {
    loading.value = true
    
    const response = await fetch(`${API_URL}/week-overview?weekOffset=${weekOffset.value}`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('Fehler beim Laden der Wochenübersicht')
    }
    
    const result = await response.json()
    
    if (result.success) {
      weekData.value = result.data
    } else {
      throw new Error(result.error || 'Unbekannter Fehler')
    }
  } catch (error) {
    console.error('Fehler beim Laden der Wochenübersicht:', error)
    // Fallback zu Dummy-Daten bei Fehlern
    weekData.value = getDummyData()
  } finally {
    loading.value = false
  }
}

const previousWeek = () => {
  weekOffset.value--
  loadWeekData()
}

const nextWeek = () => {
  weekOffset.value++
  loadWeekData()
}

const getDummyData = () => {
  return {
    weekStart: '2025-01-13',
    weekEnd: '2025-01-19',
    weekOffset: weekOffset.value,
    weekTotal: '40:00',
    days: [
      {
        date: '2025-01-13',
        name: 'Montag',
        workTime: '08:00 - 16:30',
        pauses: ['12:00 - 12:30'],
        totalWorkTime: '8:30',
        pauseTimes: ['0:30'],
        netWorkTime: '8:00',
        status: 'complete',
        statusText: 'Abgeschlossen',
        isToday: false
      },
      {
        date: '2025-01-14',
        name: 'Dienstag',
        workTime: '08:15 - 17:00',
        pauses: ['12:00 - 12:30', '14:00 - 14:30'],
        totalWorkTime: '8:45',
        pauseTimes: ['0:30', '0:30'],
        netWorkTime: '7:45',
        status: 'complete',
        statusText: 'Abgeschlossen',
        isToday: false
      },
      {
        date: '2025-01-15',
        name: 'Mittwoch',
        workTime: '08:00 - 16:00',
        pauses: ['12:00 - 12:30'],
        totalWorkTime: '8:00',
        pauseTimes: ['0:30'],
        netWorkTime: '7:30',
        status: 'complete',
        statusText: 'Abgeschlossen',
        isToday: false
      },
      {
        date: '2025-01-16',
        name: 'Donnerstag',
        workTime: '08:30 - 17:30',
        pauses: ['12:00 - 12:30', '15:00 - 15:15'],
        totalWorkTime: '9:00',
        pauseTimes: ['0:30', '0:15'],
        netWorkTime: '8:15',
        status: 'complete',
        statusText: 'Abgeschlossen',
        isToday: false
      },
      {
        date: '2025-01-17',
        name: 'Freitag',
        workTime: '08:00 - 15:00',
        pauses: ['12:00 - 12:30'],
        totalWorkTime: '7:00',
        pauseTimes: ['0:30'],
        netWorkTime: '6:30',
        status: 'complete',
        statusText: 'Abgeschlossen',
        isToday: false
      },
      {
        date: '2025-01-18',
        name: 'Samstag',
        workTime: null,
        pauses: [],
        totalWorkTime: null,
        pauseTimes: [],
        netWorkTime: null,
        status: 'weekend',
        statusText: 'Wochenende',
        isToday: false
      },
      {
        date: '2025-01-19',
        name: 'Sonntag',
        workTime: null,
        pauses: [],
        totalWorkTime: null,
        pauseTimes: [],
        netWorkTime: null,
        status: 'weekend',
        statusText: 'Wochenende',
        isToday: false
      }
    ]
  }
}

const handleWorklogUpdate = () => {
  console.log('Worklog aktualisiert, lade Wochendaten neu...')
  loadWeekData()
}

onMounted(() => {
  loadWeekData()
  
  // Event-Listener für Worklog-Updates
  window.addEventListener('worklog-updated', handleWorklogUpdate)
})

onBeforeUnmount(() => {
  window.removeEventListener('worklog-updated', handleWorklogUpdate)
})
</script>

<style scoped>
.week-overview {
  padding: 1rem;
  margin: auto;
}

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

.card h2 {
  margin: 0 0 0.25rem 0;
  color: #333;
  font-size: 1.4rem;
}

.subtitle {
  color: #666;
  margin: 0 0 1rem 0;
  font-size: 0.9rem;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
  font-size: 1.1rem;
}

.week-content {
  margin-top: 1rem;
}

.week-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 6px;
}

.week-header h3 {
  margin: 0;
  color: #333;
  font-size: 1.2rem;
}

.week-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
  background: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.week-table th {
  background: #f8f9fa;
  color: #333;
  font-weight: 600;
  padding: 8px;
  text-align: left;
  border-bottom: 2px solid #e9ecef;
  font-size: 0.8rem;
}

.week-table td {
  padding: 8px;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: top;
  font-size: 0.85rem;
}

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

.current-day {
  background: #e8f5e9 !important;
}

.current-day:hover {
  background: #d4edda !important;
}

.day-name {
  font-weight: 500;
  color: #333;
  min-width: 80px;
}

.times-cell {
  min-width: 200px;
}

.work-block {
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #ddd;
}

.work-block:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.time-entry {
  margin-bottom: 4px;
  font-size: 0.9rem;
}

.pause-entry {
  color: #666;
  font-size: 0.85rem;
}

.time-fixed {
  color: #0066cc;
  cursor: help;
}

.total-cell {
  min-width: 120px;
  text-align: right;
}

.total-work-time {
  font-weight: 500;
  color: #333;
}

.total-pause-time {
  color: #666;
  font-size: 0.9rem;
}

.net-work-time {
  color: #28a745;
  font-weight: 600;
  margin-top: 4px;
  padding-top: 4px;
  border-top: 1px solid #e9ecef;
}

.total-net-work-time {
  color: #155724;
  font-weight: 700;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 2px solid #28a745;
}

.holiday-time {
  color: #6f42c1;
  font-weight: 500;
  margin-top: 4px;
  font-size: 0.9rem;
}

.vacation-time {
  color: #17a2b8;
  font-weight: 500;
  margin-top: 4px;
  font-size: 0.9rem;
}

.sick-time {
  color: #dc3545;
  font-weight: 500;
  margin-top: 4px;
  font-size: 0.9rem;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
  text-transform: uppercase;
}

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

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

.status-weekend {
  background: #e2e3e5;
  color: #6c757d;
}

.status-holiday {
  background: #e7d4f7;
  color: #5a1a8c;
}

.status-holiday-work {
  background: #fff3cd;
  color: #856404;
  border-left: 4px solid #6f42c1;
}

.status-vacation-full {
  background: #d1ecf1;
  color: #0c5460;
}

.status-vacation-half {
  background: #d1ecf1;
  color: #0c5460;
  border: 2px dashed #17a2b8;
}

.status-vacation-work {
  background: #fff3cd;
  color: #856404;
  border-left: 4px solid #17a2b8;
}

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

.summary-row {
  background: #f8f9fa;
  font-weight: 600;
}

.summary-row td {
  border-top: 2px solid #e9ecef;
  border-bottom: none;
  padding: 6px 8px;
}

.total-hours {
  font-size: 1rem;
  color: #28a745;
}

.non-working-info {
  background: #fff3cd;
  border-top: 1px solid #ffeaa7;
}

.non-working-label {
  font-size: 0.8rem;
  color: #856404;
}

.non-working-detail {
  font-weight: normal;
  font-size: 0.75rem;
}

.non-working-total {
  font-size: 0.9rem;
  color: #856404;
}

.total-all-row {
  background: #e8f5e8;
  border-top: 2px solid #28a745;
}

.total-all-hours {
  font-size: 1.1rem;
  color: #155724;
  font-weight: bold;
}

.btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  color: #333;
  cursor: pointer;
  font-size: 0.8rem;
  transition: all 0.2s;
}

.btn:hover {
  background: #f8f9fa;
  border-color: #adb5bd;
}

.btn-secondary {
  background: #6c757d;
  color: white;
  border-color: #6c757d;
}

.btn-secondary:hover {
  background: #5a6268;
  border-color: #545b62;
}
</style>