<template>
  <UDashboardNavbar title="Serienrechnungen" :badge="filteredRows.length">
    <template #right>
      <UInput
          id="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block"
          @keydown.esc="$event.target.blur()"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>

      <UButton
          icon="i-heroicons-queue-list"
          color="gray"
          variant="ghost"
          label="Ausführungen"
          @click="openExecutionsSlideover"
      />

      <UButton
          icon="i-heroicons-play"
          color="white"
          variant="solid"
          label="Ausführen"
          @click="openExecutionModal"
      />

      <UButton
          @click="router.push(`/createDocument/edit?type=serialInvoices`)"
      >
        + Serienrechnung
      </UButton>
    </template>
  </UDashboardNavbar>

  <UDashboardToolbar>
    <template #right>
      <USelectMenu
          v-model="selectedFilters"
          icon="i-heroicons-adjustments-horizontal-solid"
          :items="filterOptions"
          label-key="name"
          value-key="name"
          multiple
          class="hidden lg:block"
          :color="selectedFilters.length > 0 ? 'primary' : 'white'"
          :content="{ width: 'min-w-max' }"
      >
        <template #default>
          Filter
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>

  <div v-if="runningExecutions.length > 0" class="p-4 space-y-4 bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
    <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-200 flex items-center gap-2">
      <UIcon name="i-heroicons-arrow-path" class="animate-spin text-primary" />
      Laufende Ausführungen
    </h3>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      <UCard v-for="exec in runningExecutions" :key="exec.id" :ui="{ body: { padding: 'p-4' } }">
        <div class="flex justify-between items-start mb-2">
          <div>
            <p class="text-sm font-medium">Start: {{ dayjs(exec.createdAt).format('DD.MM.YYYY HH:mm') }}</p>
          </div>
          <UBadge color="primary" variant="subtle">Läuft</UBadge>
        </div>

        <div class="text-xs text-gray-500 flex justify-between mb-3">
          <span>{{exec.summary}}</span>
        </div>

        <div class="flex justify-end pt-2 border-t border-gray-100 dark:border-gray-800">
          <UButton
              size="xs"
              color="white"
              variant="solid"
              icon="i-heroicons-check"
              label="Fertigstellen"
              :loading="finishingId === exec.id"
              @click="finishExecution(exec.id)"
          />
        </div>
      </UCard>
    </div>
  </div>

  <UTable
      :data="filteredRows"
      :columns="normalizeTableColumns(columns)"
      class="w-full"
      :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
      :on-select="(row) => router.push(`/createDocument/edit/${row.original?.id || row.id}`)"
  >
    <template #actions-cell="{ row }">
      <div @click.stop>
        <UDropdownMenu :items="getActionItems(row.original)" :content="{ align: 'end' }">
          <UButton
              color="neutral"
              variant="ghost"
              icon="i-heroicons-ellipsis-horizontal-20-solid"
          />
        </UDropdownMenu>
      </div>
    </template>

    <template #type-cell="{row}">
      {{dataStore.documentTypesForCreation[row.original.type].labelSingle}}
    </template>
    <template #partner-cell="{row}">
      <span v-if="row.original.customer">{{row.original.customer ? row.original.customer.name : ""}}</span>

    </template>
    <template #amount-cell="{row}">
      {{displayCurrency(calculateDocSum(row.original))}}
    </template>
    <template #serialConfig.active-cell="{row}">
      <span v-if="row.original.serialConfig.active" class="text-primary">Ja</span>
      <span v-else class="text-rose-600">Nein</span>
    </template>
    <template #contract-cell="{row}">
      <span v-if="row.original.contract">{{row.original.contract.contractNumber}} - {{row.original.contract.name}}</span>
    </template>
    <template #serialConfig.intervall-cell="{row}">
      <span v-if="row.original.serialConfig?.intervall === 'monatlich'">Monatlich</span>
      <span v-if="row.original.serialConfig?.intervall === 'vierteljährlich'">Quartalsweise</span>
    </template>
    <template #payment_type-cell="{row}">
      <span v-if="row.original.payment_type === 'transfer'">Überweisung</span>
      <span v-else-if="row.original.payment_type === 'direct-debit'">SEPA - Einzug</span>
    </template>
    <template #empty>
      <TableEmptyState label="Keine Belege anzuzeigen" />
    </template>
  </UTable>

  <UModal v-model:open="showExecutionModal" :ui="{ width: 'sm:max-w-4xl' }">
    <template #content>
      <UCard>
        <template #header>
          <div class="flex items-center justify-between">
            <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
              Serienrechnungen manuell ausführen
            </h3>
            <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="showExecutionModal = false" />
          </div>
        </template>

      <div class="max-h-[70vh] space-y-4 overflow-y-auto pr-1">
        <UFormField label="Ausführungsdatum (Belegdatum)" help="Dieses Datum steuert auch den Leistungszeitraum (z.B. Vormonat bei 'Rückwirkend').">
          <div class="flex items-center gap-2">
            <UInput type="date" v-model="executionDate" class="flex-1" />
            <UButton color="gray" variant="soft" label="Heute" @click="setExecutionDateToToday" />
          </div>
        </UFormField>

        <USeparator label="Vorlagen auswählen" />

        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div class="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
            <UInput
                v-model="modalSearch"
                icon="i-heroicons-magnifying-glass"
                placeholder="Kunde oder Vertrag suchen..."
                class="w-full sm:w-64"
                size="sm"
            />

            <USelectMenu
                v-model="selectedExecutionIntervall"
                :items="executionIntervallOptions"
                label-key="label"
                value-key="value"
                size="sm"
                class="w-full sm:w-52"
            />
          </div>

          <div class="flex items-center gap-2">
                <span class="text-xs text-gray-500 hidden sm:inline">
                   {{ filteredExecutionList.length }} sichtbar
                </span>
            <UButton
                size="2xs"
                color="gray"
                variant="soft"
                label="Alle auswählen"
                @click="selectAllTemplates"
            />
            <UButton
                size="2xs"
                color="gray"
                variant="ghost"
                label="Keine"
                @click="clearSelectedTemplates"
            />
          </div>
        </div>

        <div class="max-h-96 overflow-y-auto border border-gray-200 dark:border-gray-800 rounded-md">
          <UTable
              v-model:row-selection="executionRowSelection"
              :data="filteredExecutionList"
              :columns="normalizeTableColumns(executionColumns)"
              :row-selection-options="{ enableMultiRowSelection: true }"
              :get-row-id="(row) => row.id"
              :ui="{ th: { base: 'whitespace-nowrap' } }"
              :on-select="toggleExecutionRow"
          >
            <template #select-header="{ table }">
              <div class="flex justify-center" @click.stop>
                <UCheckbox
                    :model-value="table.getIsAllPageRowsSelected() ? true : (table.getIsSomePageRowsSelected() ? 'indeterminate' : false)"
                    @update:model-value="table.toggleAllPageRowsSelected(!!$event)"
                />
              </div>
            </template>
            <template #select-cell="{ row }">
              <div class="flex justify-center" @click.stop>
                <UCheckbox
                    :model-value="row.getIsSelected()"
                    @update:model-value="row.toggleSelected(!!$event)"
                />
              </div>
            </template>
            <template #partner-cell="{row}">
              {{row.original.customer ? row.original.customer.name : "-"}}
            </template>
            <template #amount-cell="{row}">
              {{displayCurrency(calculateDocSum(row.original))}}
            </template>
            <template #serialConfig.intervall-cell="{row}">
              {{ getIntervallLabel(row.original.serialConfig?.intervall) }}
            </template>
            <template #contract-cell="{row}">
              {{row.original.contract?.contractNumber}} - {{row.original.contract?.name}}
            </template>
            <template #plant-cell="{row}">
              {{ row.original.plant?.name || "-" }}
            </template>
            <template #empty>
              <TableEmptyState label="Keine Belege anzuzeigen" />
            </template>
          </UTable>
        </div>

        <div class="text-sm text-gray-500">
          {{ selectedExecutionRows.length }} Vorlage(n) ausgewählt.
        </div>
      </div>

        <template #footer>
          <div class="flex justify-end gap-2">
            <UButton color="white" @click="showExecutionModal = false">Abbrechen</UButton>
            <UButton
                color="primary"
                :loading="isExecuting"
                :disabled="selectedExecutionRows.length === 0"
                @click="executeSerialInvoices"
            >
              Jetzt ausführen
            </UButton>
          </div>
        </template>
      </UCard>
    </template>
  </UModal>

  <USlideover v-model:open="showExecutionsSlideover" :ui="{ width: 'w-screen max-w-md' }">
    <template #body>
      <UCard class="flex flex-col flex-1" :ui="{ body: { base: 'flex-1' }, ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
        <template #header>
          <div class="flex items-center justify-between">
            <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
              Alle Ausführungen
            </h3>
            <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="showExecutionsSlideover = false" />
          </div>
        </template>

        <div class="space-y-4 overflow-y-auto h-full p-1">
          <div v-if="executionsLoading" class="flex justify-center py-4">
            <UIcon name="i-heroicons-arrow-path" class="animate-spin text-gray-400 w-6 h-6" />
          </div>

          <div v-else-if="completedExecutions.length === 0" class="text-center text-gray-500 py-8">
            Keine abgeschlossenen Ausführungen gefunden.
          </div>

          <div v-for="exec in completedExecutions" :key="exec.id" class="border border-gray-200 dark:border-gray-700 rounded-lg p-3">
            <div class="flex justify-between items-start mb-2">
              <span class="text-sm font-semibold">{{ dayjs(exec.createdAt).format('DD.MM.YYYY HH:mm') }}</span>
              <UBadge :color="getStatusColor(exec.status)" variant="subtle" size="xs">
                {{ getStatusLabel(exec.status) }}
              </UBadge>
            </div>
            <div class="text-xs text-gray-500 grid grid-cols-2 gap-2 mt-2">
              <div>
                <UIcon name="i-heroicons-check-circle" class="text-green-500 w-3 h-3 align-text-bottom" />
                {{exec.summary}}
              </div>
            </div>
          </div>
        </div>
      </UCard>
    </template>
  </USlideover>

</template>

<script setup>
import dayjs from "dayjs";

const router = useRouter()
const { $api } = useNuxtApp()
const toast = useToast()
const dataStore = useDataStore()

const items = ref([])
const selectedItem = ref(0)

// --- Execution State ---
const showExecutionModal = ref(false)
const executionDate = ref(dayjs().format('YYYY-MM-DD'))
const executionRowSelection = ref({})
const isExecuting = ref(false)
const modalSearch = ref("") // NEU: Suchstring für das Modal
const selectedExecutionIntervall = ref("all")

const setExecutionDateToToday = () => {
  executionDate.value = dayjs().format('YYYY-MM-DD')
}

// --- SerialExecutions State ---
const showExecutionsSlideover = ref(false)
const executionItems = ref([])
const executionsLoading = ref(false)
const finishingId = ref(null)

const setupPage = async () => {
  items.value = await useEntities("createddocuments").select("*, customer(id,name), contract(id,name, contractNumber), plant(id,name)","documentDate",undefined,true)
  await fetchExecutions()
}

// --- Logic für Ausführungen ---

const fetchExecutions = async () => {
  executionsLoading.value = true
  try {
    const res = await useEntities("serialexecutions").select("*", "createdAt", true)
    executionItems.value = res || []
  } catch (e) {
    console.error("Fehler beim Laden der serialexecutions", e)
  } finally {
    executionsLoading.value = false
  }
}

const runningExecutions = computed(() => {
  return executionItems.value.filter(i => i.status === 'draft')
})

const completedExecutions = computed(() => {
  return executionItems.value.filter(i => i.status !== 'running' && i.status !== 'pending' && i.status !== 'draft')
})

const openExecutionsSlideover = () => {
  showExecutionsSlideover.value = true
  fetchExecutions()
}

const finishExecution = async (executionId) => {
  if (!executionId) return
  finishingId.value = executionId
  try {
    await $api(`/api/functions/serial/finish/${executionId}`, { method: 'POST' })
    toast.add({
      title: 'Ausführung beendet',
      description: 'Der Prozess wurde erfolgreich als fertig markiert.',
      icon: 'i-heroicons-check-circle',
      color: 'green'
    })
    await fetchExecutions()
  } catch (error) {
    console.error(error)
    toast.add({
      title: 'Fehler',
      description: 'Die Ausführung konnte nicht beendet werden.',
      icon: 'i-heroicons-exclamation-triangle',
      color: 'red'
    })
  } finally {
    finishingId.value = null
  }
}

const getStatusColor = (status) => {
  switch (status) {
    case 'completed': return 'green'
    case 'error': return 'red'
    case 'running':
    case 'draft': return 'primary'
    default: return 'gray'
  }
}

const getStatusLabel = (status) => {
  switch (status) {
    case 'completed': return 'Abgeschlossen'
    case 'error': return 'Fehlerhaft'
    case 'draft': return 'Gestartet'
    default: return status
  }
}

// --- Bestehende Logik ---

const searchString = ref("")

const filteredRows = computed(() => {
  let temp = items.value.filter(i => i.type === "serialInvoices").map(i => {
    return {
      ...i,
      class: i.archived ? 'bg-red-500/50 dark:bg-red-400/50' : null
    }
  })

  selectedFilters.value.forEach(filterName => {
    let filter = filterOptions.value.find(i => i.name === filterName)
    temp = temp.filter(filter.filterFunction)
  })

  return useSearch(searchString.value, temp.slice().reverse())
})

// Basis Liste für das Modal (nur aktive und nicht archivierte Vorlagen)
const activeTemplates = computed(() => {
  return items.value
      .filter(i => i.type === "serialInvoices" && !!i.serialConfig?.active && !i.archived)
      .map(i => ({...i}))
})

const intervallLabelMap = {
  "wöchentlich": "Wöchentlich",
  "2 - wöchentlich": "Alle 2 Wochen",
  "monatlich": "Monatlich",
  "vierteljährlich": "Quartalsweise",
  "halbjährlich": "Halbjährlich",
  "jährlich": "Jährlich"
}

const getIntervallLabel = (intervall) => {
  if (!intervall) return "-"
  return intervallLabelMap[intervall] || intervall
}

const executionIntervallOptions = computed(() => {
  const availableIntervals = [...new Set(
      activeTemplates.value
          .map(row => row.serialConfig?.intervall)
          .filter(Boolean)
  )]

  const sorted = availableIntervals.sort((a, b) =>
      getIntervallLabel(a).localeCompare(getIntervallLabel(b), 'de')
  )

  return [
    {label: 'Alle Intervalle', value: 'all'},
    ...sorted.map(intervall => ({
      label: getIntervallLabel(intervall),
      value: intervall
    }))
  ]
})

// NEU: Gefilterte Liste für das Modal basierend auf der Suche
const filteredExecutionList = computed(() => {
  let filtered = [...activeTemplates.value]

  if (selectedExecutionIntervall.value !== 'all') {
    filtered = filtered.filter(
        row => row.serialConfig?.intervall === selectedExecutionIntervall.value
    )
  }

  if (!modalSearch.value) return filtered

  const term = modalSearch.value.toLowerCase()

  return filtered.filter(row => {
    const customerName = row.customer?.name?.toLowerCase() || ""
    const contractNum = row.contract?.contractNumber?.toLowerCase() || ""
    const contractName = row.contract?.name?.toLowerCase() || ""
    const plantName = row.plant?.name?.toLowerCase() || ""

    return customerName.includes(term) ||
        contractNum.includes(term) ||
        contractName.includes(term) ||
        plantName.includes(term)
  })
})

const selectedExecutionRows = computed(() => {
  return activeTemplates.value.filter(row => !!executionRowSelection.value[row.id])
})

watch(selectedExecutionIntervall, () => {
  executionRowSelection.value = filteredExecutionList.value.reduce((acc, row) => {
    acc[row.id] = true
    return acc
  }, {})
})

// NEU: Alle auswählen (nur die aktuell sichtbaren/gefilterten)
const selectAllTemplates = () => {
  // WICHTIG: Überschreibt nicht bestehende Auswahl, sondern fügt hinzu oder ersetzt.
  // Hier ersetzen wir die Auswahl komplett mit dem aktuellen Filterergebnis
  executionRowSelection.value = filteredExecutionList.value.reduce((acc, row) => {
    acc[row.id] = true
    return acc
  }, {})
}

const clearSelectedTemplates = () => {
  executionRowSelection.value = {}
}

const toggleExecutionRow = (row) => {
  row.toggleSelected(!row.getIsSelected())
}

const getActionItems = (row) => {
  const isActive = row.serialConfig && row.serialConfig.active
  return [
    [{
      label: isActive ? 'Deaktivieren' : 'Aktivieren',
      icon: isActive ? 'i-heroicons-pause' : 'i-heroicons-play',
      class: isActive ? 'text-red-500' : 'text-primary',
      onSelect: () => toggleActiveState(row)
    }]
  ]
}

const toggleActiveState = async (row) => {
  const newState = !row.serialConfig.active
  row.serialConfig.active = newState
  try {
    await useEntities('createddocuments').update(row.id, {
      serialConfig: { ...row.serialConfig, active: newState }
    })
    toast.add({
      title: newState ? 'Aktiviert' : 'Deaktiviert',
      description: `Die Vorlage wurde ${newState ? 'aktiviert' : 'deaktiviert'}.`,
      icon: 'i-heroicons-check',
      color: 'green'
    })
  } catch (e) {
    console.error(e)
    row.serialConfig.active = !newState
    toast.add({
      title: 'Fehler',
      description: 'Status konnte nicht gespeichert werden.',
      color: 'red'
    })
  }
}

const templateColumns = [
  { key: 'actions', label: '' },
  { key: 'serialConfig.active', label: "Aktiv" },
  { key: "amount", label: "Betrag" },
  { key: 'partner', label: "Kunde" },
  { key: 'contract', label: "Vertrag" },
  { key: 'serialConfig.intervall', label: "Rhythmus" },
  { key: 'payment_type', label: "Zahlart" }
]

const executionColumns = [
  {key: 'select', label: ""},
  {key: 'partner', label: "Kunde"},
  {key: 'plant', label: "Objekt"},
  {key: 'contract', label: "Vertrag"},
  {key: 'serialConfig.intervall', label: "Intervall"},
  {key: "amount", label: "Betrag"},
]

const selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))

const filterOptions = ref([
  {
    name: "Archivierte ausblenden",
    default: true,
    "filterFunction": function (row) {
      return !row.archived;
    }
  }, {
    name: "Inaktive ausblenden",
    "filterFunction": function (row) {
      return !!row.serialConfig.active;
    }
  }
])
const selectedFilters = ref(filterOptions.value.filter(i => i.default).map(i => i.name) || [])

const displayCurrency = (value, currency = "€") => {
  return `${Number(value).toFixed(2).replace(".", ",")} ${currency}`
}

const calculateDocSum = (row) => {
  let sum = 0
  row.rows.forEach(row => {
    if (row.mode === "normal" || row.mode === "service" || row.mode === "free") {
      sum += row.quantity * row.price * (1 - row.discountPercent / 100) * (1 + row.taxPercent / 100)
    }
  })
  return sum.toFixed(2)
}

const openExecutionModal = () => {
  executionDate.value = dayjs().format('YYYY-MM-DD')
  modalSearch.value = "" // Reset Search
  selectedExecutionIntervall.value = "all"
  executionRowSelection.value = {}
  showExecutionModal.value = true
}

const executeSerialInvoices = async () => {
  if (selectedExecutionRows.value.length === 0) return;

  isExecuting.value = true

  try {
    const payload = {
      tenantId: dataStore.currentTenantId || items.value[0]?.tenant,
      executionDate: executionDate.value,
      templateIds: selectedExecutionRows.value.map(row => row.id)
    }

    const res = await $api('/api/functions/serial/start', {
      method: 'POST',
      body: payload
    })

    toast.add({
      title: 'Ausführung gestartet',
      description: `${res.length} Rechnungen werden im Hintergrund generiert.`,
      icon: 'i-heroicons-check-circle',
      color: 'green'
    })

    showExecutionModal.value = false
    executionRowSelection.value = {}

    await fetchExecutions()

  } catch (error) {
    console.error(error)
    toast.add({
      title: 'Fehler',
      description: 'Die Ausführung konnte nicht gestartet werden.',
      icon: 'i-heroicons-exclamation-triangle',
      color: 'red'
    })
  } finally {
    isExecuting.value = false
  }
}

setupPage()
</script>
