<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { api } from '@/api'

const authStore = useAuthStore()

const currentMonth = ref(new Date())
const availability = ref<any[]>([])
const loading = ref(true)

const daysInMonth = computed(() => {
  const year = currentMonth.value.getFullYear()
  const month = currentMonth.value.getMonth()
  const days = new Date(year, month + 1, 0).getDate()
  return Array.from({ length: days }, (_, i) => {
    const date = new Date(year, month, i + 1)
    return {
      date: date.toISOString().split('T')[0],
      dayOfWeek: date.toLocaleDateString('de-DE', { weekday: 'short' }),
      day: i + 1,
      isWeekend: date.getDay() === 0 || date.getDay() === 6
    }
  })
})

const monthLabel = computed(() => {
  return currentMonth.value.toLocaleDateString('de-DE', { month: 'long', year: 'numeric' })
})

onMounted(loadAvailability)

async function loadAvailability() {
  loading.value = true
  const year = currentMonth.value.getFullYear()
  const month = currentMonth.value.getMonth()
  const from = new Date(year, month, 1).toISOString().split('T')[0]
  const to = new Date(year, month + 1, 0).toISOString().split('T')[0]
  
  try {
    const res = await api.get<{ availability: any[] }>(`/availability?from=${from}&to=${to}`)
    availability.value = res.data.availability
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

function getAvailability(date: string) {
  return availability.value.find(a => a.date === date && a.user_id === authStore.user?.id)
}

async function toggleDay(date: string) {
  const current = getAvailability(date)
  const available = !current?.available
  
  try {
    await api.post('/availability', { date, available })
    await loadAvailability()
  } catch (e) {
    alert(e instanceof Error ? e.message : 'Fehler')
  }
}

function prevMonth() {
  currentMonth.value = new Date(currentMonth.value.getFullYear(), currentMonth.value.getMonth() - 1)
  loadAvailability()
}

function nextMonth() {
  currentMonth.value = new Date(currentMonth.value.getFullYear(), currentMonth.value.getMonth() + 1)
  loadAvailability()
}
</script>

<template>
  <div class="space-y-6">
    <h1 class="text-2xl font-bold text-gray-900 dark:text-white">📅 Verfügbarkeit</h1>
    
    <div class="card">
      <div class="flex items-center justify-between mb-6">
        <button class="btn btn-secondary" @click="prevMonth">←</button>
        <h2 class="text-lg font-semibold">{{ monthLabel }}</h2>
        <button class="btn btn-secondary" @click="nextMonth">→</button>
      </div>

      <div v-if="loading" class="text-center py-8 text-gray-500">Lädt...</div>

      <div v-else class="grid grid-cols-7 gap-2">
        <div v-for="day in daysInMonth" :key="day.date" class="text-center">
          <div class="text-xs text-gray-500 mb-1">{{ day.dayOfWeek }}</div>
          <button
            :class="[
              'w-10 h-10 rounded-lg font-medium transition-colors',
              day.isWeekend ? 'bg-gray-100 dark:bg-gray-700' : '',
              getAvailability(day.date)?.available 
                ? 'bg-green-500 text-white hover:bg-green-600' 
                : 'bg-gray-200 dark:bg-gray-600 hover:bg-gray-300 dark:hover:bg-gray-500'
            ]"
            @click="toggleDay(day.date)"
          >
            {{ day.day }}
          </button>
        </div>
      </div>

      <div class="mt-6 flex items-center gap-4 text-sm">
        <div class="flex items-center gap-2">
          <span class="w-4 h-4 bg-green-500 rounded"></span>
          <span>Verfügbar</span>
        </div>
        <div class="flex items-center gap-2">
          <span class="w-4 h-4 bg-gray-200 dark:bg-gray-600 rounded"></span>
          <span>Nicht gemeldet</span>
        </div>
      </div>
    </div>
  </div>
</template>
