<template>
  <div class="export-page">
    <div class="card">
      <h3>Zeiterfassung exportieren</h3>
      
      <form @submit.prevent="exportData" class="export-form">
        <div class="form-row">
          <div class="form-group">
            <label for="startDate">Von</label>
            <input 
              type="date" 
              id="startDate" 
              v-model="form.startDate" 
              required
            >
          </div>
          
          <div class="form-group">
            <label for="endDate">Bis</label>
            <input 
              type="date" 
              id="endDate" 
              v-model="form.endDate" 
              required
            >
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="format">Format</label>
            <select 
              id="format" 
              v-model="form.format" 
              required
            >
              <option value="pdf">PDF (Wochen-Übersicht)</option>
              <option value="excel">Excel (Detailliert)</option>
              <option value="csv">CSV (Detailliert)</option>
            </select>
          </div>
        </div>

        <div class="format-description">
          <div v-if="form.format === 'pdf'">
            <strong>PDF-Format:</strong> Zeigt die Daten wie in der Wochenübersicht mit allen Details (Arbeitszeiten, Pausen, Urlaub, etc.)
          </div>
          <div v-else>
            <strong>{{ form.format === 'excel' ? 'Excel' : 'CSV' }}-Format:</strong> 
            Detaillierte Liste mit Spalten: Datum, Uhrzeit, Aktivität, Gesamt-Netto-Arbeitszeit
          </div>
        </div>

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

      <div class="info-box">
        <h4>Hinweise:</h4>
        <ul>
          <li>Es werden nur die <strong>korrigierten Zeiten</strong> exportiert (inkl. Zeitkorrekturen)</li>
          <li><strong>PDF</strong>: Übersichtliche Darstellung nach Wochen, ideal für Ausdrucke</li>
          <li><strong>Excel/CSV</strong>: Detaillierte Rohdaten, ideal für weitere Analysen</li>
          <li>Die Netto-Arbeitszeit ist bereits um Pausen bereinigt</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 } 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 loading = ref(false)

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

// Default: Aktuelles Jahr bis heute
const now = new Date()
const yearStart = new Date(now.getFullYear(), 0, 1)

const form = ref({
  startDate: yearStart.toISOString().split('T')[0],
  endDate: now.toISOString().split('T')[0],
  format: 'pdf'
})

// Exportiere Daten
async function exportData() {
  if (!form.value.startDate || !form.value.endDate) {
    await alert('Bitte geben Sie Start- und Enddatum an', 'Fehlende Angaben')
    return
  }
  
  if (new Date(form.value.startDate) > new Date(form.value.endDate)) {
    await alert('Das Startdatum muss vor dem Enddatum liegen', 'Ungültige Eingabe')
    return
  }
  
  try {
    loading.value = true
    
    if (form.value.format === 'pdf') {
      await exportPDF()
    } else if (form.value.format === 'excel') {
      await downloadFile('excel')
    } else if (form.value.format === 'csv') {
      await downloadFile('csv')
    }
  } catch (error) {
    console.error('Fehler beim Export:', error)
    await alert(`Fehler: ${error.message}`, 'Fehler')
  } finally {
    loading.value = false
  }
}

// Download CSV/Excel-Datei
async function downloadFile(format) {
  const url = `${API_URL}/export/${format}?startDate=${form.value.startDate}&endDate=${form.value.endDate}`
  
  const response = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${authStore.token}`
    }
  })
  
  if (!response.ok) {
    throw new Error('Fehler beim Export')
  }
  
  const blob = await response.blob()
  const downloadUrl = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = downloadUrl
  
  // Richtiger Dateiname je nach Format
  const extension = format === 'excel' ? 'xlsx' : 'csv'
  a.download = `zeiterfassung_${form.value.startDate}_${form.value.endDate}.${extension}`
  
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  window.URL.revokeObjectURL(downloadUrl)
}

// PDF-Export (Browser-Print)
async function exportPDF() {
  const url = `${API_URL}/export/pdf?startDate=${form.value.startDate}&endDate=${form.value.endDate}`
  
  const response = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${authStore.token}`
    }
  })
  
  if (!response.ok) {
    throw new Error('Fehler beim PDF-Export')
  }
  
  const data = await response.json()
  
  // Öffne neues Fenster für PDF-Druck
  const printWindow = window.open('', '_blank')
  printWindow.document.write(generatePDFHTML(data))
  printWindow.document.close()
  
  // Warte kurz, dann öffne Druckdialog
  setTimeout(() => {
    printWindow.print()
  }, 500)
}

// Generiere HTML für PDF-Druck
function generatePDFHTML(data) {
  const dayNames = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag']
  
  let html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Zeiterfassung ${data.startDate} - ${data.endDate}</title>
      <style>
        body {
          font-family: Arial, sans-serif;
          padding: 20px;
          font-size: 11pt;
        }
        h1 {
          font-size: 18pt;
          margin-bottom: 10px;
        }
        .week {
          page-break-inside: avoid;
          margin-bottom: 30px;
        }
        .week-header {
          background: #f0f0f0;
          padding: 8px;
          font-weight: bold;
          margin-bottom: 10px;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 10px;
        }
        th {
          background: #e0e0e0;
          padding: 6px;
          text-align: left;
          border: 1px solid #ccc;
          font-size: 10pt;
        }
        td {
          padding: 6px;
          border: 1px solid #ccc;
          font-size: 10pt;
        }
        .summary-row {
          background: #f9f9f9;
          font-weight: bold;
        }
        @media print {
          body { padding: 0; }
          .week { page-break-inside: avoid; }
        }
      </style>
    </head>
    <body>
      <h1>Zeiterfassung</h1>
      <p>Zeitraum: ${formatDate(data.startDate)} - ${formatDate(data.endDate)}</p>
  `
  
  data.weeks.forEach(week => {
    html += `
      <div class="week">
        <div class="week-header">
          Woche: ${formatDate(week.weekStart)} - ${formatDate(week.weekEnd)}
        </div>
        <table>
          <thead>
            <tr>
              <th>Tag</th>
              <th>Datum</th>
              <th>Arbeitszeit</th>
              <th>Pausen</th>
              <th>Gesamt</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
    `
    
    week.days.forEach(day => {
      const date = new Date(day.date)
      const dayName = dayNames[date.getDay()]
      
      html += `
        <tr>
          <td>${dayName}</td>
          <td>${formatDate(day.date)}</td>
          <td>${day.totalWorkTime || '—'}</td>
          <td>${day.pauseTimes?.map(p => p.time).join(', ') || '—'}</td>
          <td>${day.netWorkTime || '—'}</td>
          <td>${day.statusText || '—'}</td>
        </tr>
      `
    })
    
    html += `
            <tr class="summary-row">
              <td colspan="4">Wochensumme</td>
              <td>${week.weekTotal}</td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
    `
  })
  
  html += `
    </body>
    </html>
  `
  
  return html
}

// Formatiere Datum
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'
  })
}
</script>

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

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

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

.export-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

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

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

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

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

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

.format-description {
  background: #f0f8ff;
  border: 1px solid #d0e8ff;
  border-radius: 4px;
  padding: 12px;
  font-size: 13px;
  color: #1565c0;
}

.format-description strong {
  color: #0d47a1;
}

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

.info-box {
  background: #f9f9f9;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 16px;
  margin-top: 24px;
}

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

.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: 12px 24px;
  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>

