'use client'

import { useState, useEffect, useCallback } from 'react'
import { useTheme } from '@/lib/ThemeContext'
import { Sidebar } from '@/components/Sidebar'
import { ThemeToggle } from '@/components/ThemeToggle'
import { LanguageDropdown } from '@/components/LanguageDropdown'
import { calendarApi } from '@/lib/schulkalender/api'
import type { PublicEvent, SchoolCalendarConfig } from './types'
import { BUNDESLAENDER } from './types'
import { MonthView } from './_components/MonthView'
import { BundeslandWizard } from './_components/BundeslandWizard'

function monthRange(year: number, month: number): { from: string; to: string } {
  // Render the visible 6-week grid worth of holidays (covers prev/next month edges).
  const from = new Date(Date.UTC(year, month - 1, 1))
  from.setUTCDate(from.getUTCDate() - 7)
  const to = new Date(Date.UTC(year, month, 0))
  to.setUTCDate(to.getUTCDate() + 14)
  return { from: from.toISOString().slice(0, 10), to: to.toISOString().slice(0, 10) }
}

export default function SchulkalenderPage() {
  const { isDark } = useTheme()
  const today = new Date()
  const [year, setYear] = useState(today.getFullYear())
  const [month, setMonth] = useState(today.getMonth() + 1)
  const [config, setConfig] = useState<SchoolCalendarConfig | null>(null)
  const [holidays, setHolidays] = useState<PublicEvent[]>([])
  const [configLoading, setConfigLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const loadConfig = useCallback(async () => {
    setConfigLoading(true)
    try {
      const cfg = await calendarApi.getConfig()
      setConfig(cfg)
      setError(null)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Config laden fehlgeschlagen')
    } finally {
      setConfigLoading(false)
    }
  }, [])

  useEffect(() => { loadConfig() }, [loadConfig])

  const loadHolidays = useCallback(async () => {
    if (!config?.bundesland) return
    const { from, to } = monthRange(year, month)
    try {
      const data = await calendarApi.listHolidays(config.bundesland, from, to)
      setHolidays(data || [])
      setError(null)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Ferien laden fehlgeschlagen')
    }
  }, [config, year, month])

  useEffect(() => { loadHolidays() }, [loadHolidays])

  const handleSaveBundesland = async (bundesland: string) => {
    const cfg = await calendarApi.upsertConfig({ bundesland })
    setConfig(cfg)
  }

  const goPrev = () => {
    if (month === 1) { setYear(y => y - 1); setMonth(12) }
    else setMonth(m => m - 1)
  }
  const goNext = () => {
    if (month === 12) { setYear(y => y + 1); setMonth(1) }
    else setMonth(m => m + 1)
  }
  const goToday = () => {
    const t = new Date()
    setYear(t.getFullYear())
    setMonth(t.getMonth() + 1)
  }

  const bundeslandName = config
    ? BUNDESLAENDER.find(b => b.code === config.bundesland)?.name || config.bundesland
    : ''

  return (
    <div className={`min-h-screen flex relative overflow-hidden ${
      isDark ? 'bg-gradient-to-br from-indigo-900 via-purple-900 to-pink-800'
        : 'bg-gradient-to-br from-slate-100 via-blue-50 to-indigo-100'
    }`}>
      <div className={`absolute -top-40 -right-40 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob ${isDark ? 'bg-purple-500 opacity-30' : 'bg-purple-300 opacity-40'}`} />
      <div className={`absolute top-1/2 -left-40 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob animation-delay-2000 ${isDark ? 'bg-pink-500 opacity-30' : 'bg-pink-300 opacity-40'}`} />
      <div className={`absolute -bottom-40 right-1/3 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob animation-delay-4000 ${isDark ? 'bg-blue-500 opacity-30' : 'bg-blue-300 opacity-40'}`} />

      <div className="relative z-10 p-4"><Sidebar selectedTab="schulkalender" /></div>

      <main className="flex-1 relative z-10 p-6 overflow-y-auto">
        <div className="max-w-6xl mx-auto">
          <header className="flex items-center justify-between mb-6">
            <div>
              <h1 className={`text-3xl font-bold ${isDark ? 'text-white' : 'text-slate-900'}`}>
                Schulkalender
              </h1>
              <p className={`text-sm mt-1 ${isDark ? 'text-white/60' : 'text-slate-500'}`}>
                {config ? `Ferien und Feiertage fuer ${bundeslandName}` : 'Ferien, Feiertage und Schultermine'}
              </p>
            </div>
            <div className="flex items-center gap-3">
              <ThemeToggle />
              <LanguageDropdown />
            </div>
          </header>

          {error && (
            <div className="mb-4 p-3 rounded-xl bg-red-500/20 border border-red-500/40 text-red-300">{error}</div>
          )}

          {configLoading ? (
            <div className={`text-center py-12 opacity-60 ${isDark ? 'text-white' : 'text-slate-700'}`}>Laedt…</div>
          ) : !config ? (
            <BundeslandWizard onSave={handleSaveBundesland} />
          ) : (
            <MonthView
              year={year}
              month={month}
              holidays={holidays}
              onPrev={goPrev}
              onNext={goNext}
              onToday={goToday}
            />
          )}
        </div>
      </main>
    </div>
  )
}
