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

const loading = ref(true)
const shifts = ref<any[]>([])
const assignments = ref<any[]>([])
const showModal = ref(false)
const currentWeek = ref(new Date())

const form = ref({
  name: '',
  start_time: '06:00',
  end_time: '14:00',
  break_minutes: 30,
  color: '#3B82F6',
  is_night_shift: false
})

onMounted(async () => {
  await loadData()
})

async function loadData() {
  loading.value = true
  try {
    const [shiftsRes, assignRes] = await Promise.all([
      api.get<any>('/shifts/definitions'),
      api.get<any>(`/shifts/assignments?start=${formatDate(getWeekStart())}&end=${formatDate(getWeekEnd())}`)
    ])
    shifts.value = shiftsRes.data.shifts || []
    assignments.value = assignRes.data.assignments || []
  } catch (e) {
    console.error(e)
  }
  loading.value = false
}

function getWeekStart(): Date {
  const d = new Date(currentWeek.value)
  d.setDate(d.getDate() - d.getDay() + 1)
  return d
}

function getWeekEnd(): Date {
  const d = new Date(getWeekStart())
  d.setDate(d.getDate() + 6)
  return d
}

function formatDate(d: Date): string {
  return d.toISOString().split('T')[0]
}

const weekDays = computed(() => {
  const days = []
  const start = getWeekStart()
  for (let i = 0; i < 7; i++) {
    const d = new Date(start)
    d.setDate(d.getDate() + i)
    days.push({ date: formatDate(d), label: d.toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit' }) })
  }
  return days
})

async function createShift() {
  try {
    await api.post('/shifts/definitions', form.value)
    showModal.value = false
    form.value = { name: '', start_time: '06:00', end_time: '14:00', break_minutes: 30, color: '#3B82F6', is_night_shift: false }
    await loadData()
  } catch (e: any) {
    alert('Fehler: ' + e.message)
  }
}

function getAssignmentsForDay(date: string) {
  return assignments.value.filter(a => a.date === date)
}
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold">📅 Schichtplanung</h1>
        <p class="text-gray-500">Dienstpläne verwalten</p>
      </div>
      <button @click="showModal = true" class="btn btn-primary">+ Schicht definieren</button>
    </div>

    <!-- Shift Definitions -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
      <h2 class="font-semibold mb-3">Schicht-Typen</h2>
      <div class="flex flex-wrap gap-2">
        <div v-for="s in shifts" :key="s.id" 
             :style="{ backgroundColor: s.color + '20', borderColor: s.color }"
             class="px-3 py-1 rounded-full border text-sm">
          {{ s.name }} ({{ s.start_time?.slice(0,5) }} - {{ s.end_time?.slice(0,5) }})
        </div>
        <div v-if="shifts.length === 0" class="text-gray-500">Keine Schichten definiert</div>
      </div>
    </div>

    <!-- Week View -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <div class="flex items-center justify-between p-4 border-b">
        <button @click="currentWeek.setDate(currentWeek.getDate() - 7); loadData()" class="text-gray-600 hover:text-gray-900">← Vorherige</button>
        <span class="font-semibold">{{ getWeekStart().toLocaleDateString('de-DE') }} - {{ getWeekEnd().toLocaleDateString('de-DE') }}</span>
        <button @click="currentWeek.setDate(currentWeek.getDate() + 7); loadData()" class="text-gray-600 hover:text-gray-900">Nächste →</button>
      </div>
      
      <div class="grid grid-cols-7 divide-x">
        <div v-for="day in weekDays" :key="day.date" class="min-h-32 p-2">
          <div class="text-xs font-semibold text-gray-500 mb-2">{{ day.label }}</div>
          <div v-for="a in getAssignmentsForDay(day.date)" :key="a.id"
               :style="{ backgroundColor: a.color + '40' }"
               class="text-xs p-1 rounded mb-1">
            {{ a.first_name }} {{ a.last_name?.charAt(0) }}.
          </div>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div v-if="showModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 class="text-xl font-bold mb-4">Neue Schicht definieren</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Name</label>
            <input v-model="form.name" class="input" placeholder="z.B. Frühschicht" />
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Beginn</label>
              <input v-model="form.start_time" type="time" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Ende</label>
              <input v-model="form.end_time" type="time" class="input" />
            </div>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">Pause (Min.)</label>
              <input v-model.number="form.break_minutes" type="number" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">Farbe</label>
              <input v-model="form.color" type="color" class="w-full h-10 rounded" />
            </div>
          </div>
        </div>
        <div class="flex justify-end space-x-2 mt-6">
          <button @click="showModal = false" class="btn">Abbrechen</button>
          <button @click="createShift" class="btn btn-primary">Erstellen</button>
        </div>
      </div>
    </div>
  </div>
</template>
