<script setup lang="ts">
import { ref, computed } from "vue"
import dayjs from "dayjs"

// --- Helper für Schnellauswahl ---

// Setzt ein spezifisches Quartal (Q1-Q4), optional mit Jahresangabe
const setQuarter = (quarter: number, year: number = dayjs().year()) => {
  const startMonth = (quarter - 1) * 3 // Q1=0 (Jan), Q2=3 (Apr), etc.

  // .toDate() ist wichtig für den DatePicker
  createExportData.value.start_date = dayjs().year(year).month(startMonth).startOf('month').toDate()
  createExportData.value.end_date = dayjs().year(year).month(startMonth + 2).endOf('month').toDate()
}

// Berechnet automatisch das vorherige Quartal (inkl. Jahreswechsel, falls wir in Q1 sind)
const setLastQuarter = () => {
  const currentMonth = dayjs().month() // 0 bis 11
  const currentQuarter = Math.floor(currentMonth / 3) + 1 // 1 bis 4

  if (currentQuarter === 1) {
    // Wenn wir in Q1 sind, ist das letzte Quartal Q4 des Vorjahres
    setQuarter(4, dayjs().year() - 1)
  } else {
    // Sonst einfach das vorherige Quartal im aktuellen Jahr
    setQuarter(currentQuarter - 1)
  }
}

const setMonthPreset = (type: 'current' | 'last') => {
  let date = dayjs()
  if (type === 'last') {
    date = date.subtract(1, 'month')
  }

  createExportData.value.start_date = date.startOf('month').toDate()
  createExportData.value.end_date = date.endOf('month').toDate()
}
// ---------------------------------

const exports = ref([])

// Filtert die Exporte: Nur Einträge, deren valid_until nach dem jetzigen Zeitpunkt liegt
const filteredExports = computed(() => {
  const now = dayjs()
  return exports.value.filter(row => {
    if (!row.valid_until) return true // Falls kein Ablaufdatum gesetzt ist, anzeigen
    return dayjs(row.valid_until).isAfter(now)
  })
})

const auth = useAuthStore()
const toast = useToast()
const router = useRouter()

const setupPage = async () => {
  exports.value = await useNuxtApp().$api("/api/exports",{
    method: "GET"
  })
}

setupPage()

function downloadFile(row) {
  const a = document.createElement("a")
  a.href = row.url
  a.download = row.file_path.split("/").pop()
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

const showCreateExportModal = ref(false)
const createExportData = ref({
  start_date: null,
  end_date: null,
  beraternr:null,
  mandantennr: null
})

const createExport = async () => {
  const res = await useNuxtApp().$api("/api/exports/datev",{
    method: "POST",
    body: createExportData.value
  })

  showCreateExportModal.value = false

  if(res.success) {
    toast.add({title: "Export wird erstellt. Sie erhalten eine Benachrichtigung sobald es soweit ist."})
  } else {
    toast.add({title: "Es gab einen Fehler beim erstellen", color: "error"})
  }

}
</script>

<template>
  <UDashboardNavbar
      title="Exporte"
  >
    <template #right>
      <UButton
          @click="showCreateExportModal = true"
      >+ DATEV</UButton>
      <UButton
          @click="router.push('/export/create/sepa')"
      >+ SEPA</UButton>
    </template>
  </UDashboardNavbar>

  <UTable
      :data="filteredExports"
      :columns="normalizeTableColumns([
        { key: 'created_at', label: 'Erstellt am' },
        { key: 'start_date', label: 'Start' },
        { key: 'end_date', label: 'Ende' },
        { key: 'valid_until', label: 'Gültig bis' },
        { key: 'type', label: 'Typ' },
        { key: 'download', label: 'Download' },
      ])"
  >
    <template #created_at-data="{row}">
      {{dayjs(row.created_at).format("DD.MM.YYYY HH:mm")}}
    </template>
    <template #start_date-data="{row}">
      {{dayjs(row.start_date).format("DD.MM.YYYY HH:mm")}}
    </template>
    <template #end_date-data="{row}">
      {{dayjs(row.end_date).format("DD.MM.YYYY HH:mm")}}
    </template>
    <template #valid_until-data="{row}">
      {{dayjs(row.valid_until).format("DD.MM.YYYY HH:mm")}}
    </template>
    <template #download-data="{row}">
      <UButton @click="downloadFile(row)">Download</UButton>
    </template>
  </UTable>

  <UModal v-model:open="showCreateExportModal">
    <UCard>
      <template #header>
        Export erstellen
      </template>

      <div class="mb-6 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-100 dark:border-gray-700">
        <div class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Schnellauswahl</div>

        <div class="flex flex-col gap-3">
          <div class="flex gap-2 items-center">
            <span class="text-xs text-gray-400 w-16">Monat:</span>
            <UButton size="2xs" color="white" variant="solid" @click="setMonthPreset('last')">Letzter</UButton>
            <UButton size="2xs" color="white" variant="solid" @click="setMonthPreset('current')">Aktuell</UButton>
          </div>

          <div class="flex gap-2 items-center">
            <span class="text-xs text-gray-400 w-16">Quartal:</span>

            <UButton
                size="2xs"
                color="white"
                variant="solid"
                @click="setLastQuarter()"
                class="mr-2 border-r border-gray-200 dark:border-gray-600 pr-3"
            >
              Letztes
            </UButton>

            <UButton
                v-for="q in 4"
                :key="q"
                size="2xs"
                color="white"
                variant="solid"
                @click="setQuarter(q)"
            >
              Q{{ q }}
            </UButton>
          </div>
        </div>
      </div>
      <div class="flex gap-4">
        <UFormGroup label="Start:" class="flex-1">
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton
                icon="i-heroicons-calendar-days-20-solid"
                :label="createExportData.start_date ? dayjs(createExportData.start_date).format('DD.MM.YYYY') : 'Datum auswählen'"
                variant="outline"
                class="w-full justify-start"
            />
            <template #panel="{ close }">
              <LazyDatePicker v-model="createExportData.start_date" @close="close" />
            </template>
          </UPopover>
        </UFormGroup>

        <UFormGroup label="Ende:" class="flex-1">
          <UPopover :popper="{ placement: 'bottom-start' }">
            <UButton
                icon="i-heroicons-calendar-days-20-solid"
                :label="createExportData.end_date ? dayjs(createExportData.end_date).format('DD.MM.YYYY') : 'Datum auswählen'"
                variant="outline"
                class="w-full justify-start"
            />
            <template #panel="{ close }">
              <LazyDatePicker v-model="createExportData.end_date" @close="close" />
            </template>
          </UPopover>
        </UFormGroup>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <UButton @click="createExport">
            Erstellen
          </UButton>
        </div>
      </template>

    </UCard>
  </UModal>

</template>

<style scoped>
</style>
