<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getSchemas, getTasks, toggleTask } from '../services/api'
import CategoryBadge from '../components/CategoryBadge.vue'
import Icon from '../components/Icon.vue'

const router = useRouter()
const items = ref([])
const loading = ref(true)
const mode = ref('schemas')

async function fetchData(showLoading = true) {
  if (showLoading) loading.value = true
  items.value = mode.value === 'schemas'
    ? await getSchemas()
    : await getTasks()
  loading.value = false
}

function switchMode(newMode) {
  mode.value = newMode
  fetchData()
}

function formatDate(dateStr) {
  return new Date(dateStr + 'T00:00:00').toLocaleDateString('de-DE', {
    day: '2-digit', month: '2-digit', year: 'numeric',
  })
}

function getDateKey(item) {
  if (!item.date) return null
  return item.date.split('T')[0]
}

const groupedItems = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  const noDate = items.value.filter(i => !getDateKey(i))
  const current = items.value.filter(i => {
    const d = getDateKey(i)
    return d && d >= today
  })
  const past = items.value.filter(i => {
    const d = getDateKey(i)
    return d && d < today
  })

  const monthMap = {}
  const months = []
  for (const item of past) {
    const dateKey = getDateKey(item)
    const d = new Date(dateKey + 'T00:00:00')
    const sortKey = dateKey.substring(0, 7)
    const label = d.toLocaleDateString('de-DE', { month: 'long', year: 'numeric' })
    if (!monthMap[sortKey]) {
      monthMap[sortKey] = { sortKey, label, items: [] }
      months.push(monthMap[sortKey])
    }
    monthMap[sortKey].items.push(item)
  }
  months.sort((a, b) => b.sortKey.localeCompare(a.sortKey))

  return { noDate, current, months }
})

async function handleToggle(item) {
  await toggleTask(item.id)
  await fetchData(false)
}

onMounted(fetchData)
</script>

<template>
  <div>
    <div class="header-row">
      <button @click="router.push({ name: 'categories' })">Kategorien</button>
      <div class="btn-row">
        <button class="btn-primary" @click="router.push({ name: 'schema-create' })">
          <Icon name="plus" />
        </button>
        <button @click="router.back()"><Icon name="arrowLeft" /></button>
      </div>
    </div>

    <div class="filter-row">
      <div class="toggle-group">
        <button :class="{ 'btn-primary': mode === 'schemas' }" @click="switchMode('schemas')">
          Alle Schemas
        </button>
        <button :class="{ 'btn-primary': mode === 'occurrences' }" @click="switchMode('occurrences')">
          Alle Aufgaben
        </button>
      </div>
    </div>

    <p v-if="loading" class="loading">Laden...</p>

    <ul v-else class="task-list">
      <!-- Schema-Modus: Anzeigen-Button -->
      <template v-if="mode === 'schemas'">
        <li v-for="(item, index) in items" :key="index" class="task-item">
          <div class="task-left">
            <span class="task-name">{{ item.name }}</span>
            <CategoryBadge :category="item.category" />
          </div>
          <button @click="router.push({ name: 'schema-detail', params: { id: item.id } })">
            Anzeigen
          </button>
        </li>
      </template>
      <!-- Aufgaben-Modus: gruppiert -->
      <template v-else>
        <!-- Ohne Datum -->
        <li
          v-for="(item, i) in groupedItems.noDate"
          :key="'nd-' + i"
          class="task-item task-item--clickable"
          @click="handleToggle(item)"
        >
          <div class="task-left">
            <span class="task-name" :class="{ 'task--completed': item.status === 'done' }">{{ item.name }}</span>
            <CategoryBadge :category="item.category" />
          </div>
          <div class="task-right" @click.stop>
            <button @click="router.push({ name: 'task-detail', params: { id: item.id } })">Anzeigen</button>
          </div>
        </li>

        <!-- Aktuell -->
        <li v-if="groupedItems.current.length" class="section-header"><span>Aktuell</span></li>
        <li
          v-for="(item, i) in groupedItems.current"
          :key="'cur-' + i"
          class="task-item task-item--clickable"
          @click="handleToggle(item)"
        >
          <div class="task-left">
            <span class="task-name" :class="{ 'task--completed': item.status === 'done' }">{{ item.name }}</span>
            <CategoryBadge :category="item.category" />
          </div>
          <div class="task-right" @click.stop>
            <span class="task-date">{{ formatDate(getDateKey(item)) }}</span>
            <button @click="router.push({ name: 'task-detail', params: { id: item.id } })">Anzeigen</button>
          </div>
        </li>

        <!-- Vergangene Monate -->
        <template v-for="month in groupedItems.months" :key="month.sortKey">
          <li class="section-header"><span>{{ month.label }}</span></li>
          <li
            v-for="(item, i) in month.items"
            :key="month.sortKey + '-' + i"
            class="task-item task-item--clickable task-item--past"
            @click="handleToggle(item)"
          >
            <div class="task-left">
              <span class="task-name" :class="{ 'task--completed': item.status === 'done' }">{{ item.name }}</span>
              <CategoryBadge :category="item.category" />
            </div>
            <span class="task-date">{{ formatDate(getDateKey(item)) }}</span>
          </li>
        </template>
      </template>
    </ul>

    <p v-if="!loading && items.length === 0" class="empty">Keine Einträge.</p>
  </div>
</template>

<style scoped>
.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.filter-row {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 1rem;
}

.toggle-group {
  display: flex;
}

.toggle-group button {
  border-radius: 0;
}

.toggle-group button:first-child {
  border-radius: 6px 0 0 6px;
}

.toggle-group button:last-child {
  border-radius: 0 6px 6px 0;
}

.task-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.task-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.6rem 0;
  border-bottom: 1px solid var(--border);
  gap: 0.5rem;
}

.task-item:has(+ .section-header) {
  border-bottom: none;
}

.task-left {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex: 1;
  min-width: 0;
}

.task-name {
  font-weight: 500;
  color: var(--text-h);
}

.task--completed {
  text-decoration: line-through;
  opacity: 0.5;
}

.task-item--clickable {
  cursor: pointer;
}

.task-item--clickable:hover {
  background: var(--accent-bg);
}

.task-item--past {
  opacity: 0.7;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: center;
  list-style: none;
  margin-top: 1rem;
  padding: 0;
  border-top: 1px solid var(--border);
}

.section-header span {
  margin-top: -0.7rem;
  background: var(--bg);
  padding: 0.15rem 0.75rem;
  border: 1px solid var(--border);
  border-radius: 999px;
  font-weight: 600;
  font-size: 0.8rem;
  color: var(--text-h);
}

.task-right {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.task-date {
  font-size: 0.75rem;
  color: var(--text);
}

.loading, .empty {
  text-align: center;
  color: var(--text);
  margin-top: 2rem;
}
</style>
