'use client'

import { useState, useMemo } from'react'
import { Plus, Trash2, RotateCcw, Save, X } from'lucide-react'
import { DEFAULT_CALENDAR_COLORS } from'@/lib/planning-settings'
import { getBavarianHolidayMap } from'@/lib/calendar/bavarian-holidays'
import type { CalendarColors, CustomHoliday } from'@/lib/planning-settings'

interface Props {
 initialColors: CalendarColors
 initialCustomHolidays: CustomHoliday[]
}

// ── Color Preview ─────────────────────────────────────────────────────────────

function ColorPreview({ colors }: { colors: CalendarColors }) {
 const today = new Date()
 // Build a 7-day preview starting from the nearest Monday
 const startOffset = today.getDay() === 0 ? -6 : 1 - today.getDay()
 const days = Array.from({ length: 7 }, (_, i) => {
 const d = new Date(today)
 d.setDate(today.getDate() + startOffset + i)
 return d
 })
 const DAY_ABBREV = ['So','Mo','Di','Mi','Do','Fr','Sa']
 const todayStr = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,'0')}-${String(today.getDate()).padStart(2,'0')}`

 return (
 <div className="flex rounded-lg overflow-hidden border border-muted w-fit">
 {days.map((d) => {
 const isToday_ = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}` === todayStr
 const dow = d.getDay()
 const isWeekend = dow === 0 || dow === 6
 const bg = isToday_ ? colors.today : isWeekend ? colors.weekend : colors.weekday
 return (
 <div
 key={d.toISOString()}
 className="flex flex-col items-center px-3 py-2 border-r border-muted last:border-r-0 min-w-[40px]"
 style={{ backgroundColor: bg }}
 >
 <span className={`text-[10px] font-medium ${isToday_ ?'text-[#1D4ED8]': isWeekend ?'text-[#888888]':'text-muted-foreground'}`}>
 {DAY_ABBREV[dow]}
 </span>
 <span className={`text-[13px] font-bold leading-tight ${isToday_ ?'text-[#1D4ED8]':'text-foreground'}`}>
 {d.getDate()}
 </span>
 {isToday_ && <span className="w-1 h-1 rounded-full bg-[#3B82F6] mt-0.5"/>}
 </div>
 )
 })}
 </div>
 )
}

// ── Component ─────────────────────────────────────────────────────────────────

const inputCls ='w-full h-8 rounded border border-muted text-[13px] text-foreground px-2 bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary'
const labelCls ='block text-[12px] font-medium text-foreground mb-1'

export default function CalendarSettingsSection({ initialColors, initialCustomHolidays }: Props) {
 const [colors, setColors] = useState<CalendarColors>(initialColors)
 const [customHolidays, setCustomHolidays] = useState<CustomHoliday[]>(initialCustomHolidays)
 const [colorSaving, setColorSaving] = useState(false)
 const [colorMsg, setColorMsg] = useState<string | null>(null)
 const [holidaySaving, setHolidaySaving] = useState(false)
 const [holidayMsg, setHolidayMsg] = useState<string | null>(null)
 const [newHoliday, setNewHoliday] = useState<Partial<CustomHoliday>>({ region:'Bayern'})
 const [confirmDel, setConfirmDel] = useState<string | null>(null)
 const [showForm, setShowForm] = useState(false)

 const currentYear = new Date().getFullYear()
 const bavarianMap = useMemo(() => getBavarianHolidayMap(currentYear), [currentYear])

 // Merge bavarian + custom for display table
 const allHolidays = useMemo(() => {
 const list: { date: string; name: string; region: string; isCustom: boolean; id?: string }[] = []
 for (const [date, name] of bavarianMap.entries()) {
 list.push({ date, name, region:'Bayern (gesetzlich)', isCustom: false })
 }
 for (const h of customHolidays) {
 list.push({ date: h.date, name: h.name, region: h.region, isCustom: true, id: h.id })
 }
 return list.sort((a, b) => a.date.localeCompare(b.date))
 }, [bavarianMap, customHolidays])

 async function saveColors() {
 setColorSaving(true)
 setColorMsg(null)
 const res = await fetch('/api/planning/settings', {
 method:'PATCH',
 headers: {'Content-Type':'application/json'},
 body: JSON.stringify({ key:'calendar_colors', value: colors }),
 })
 setColorMsg(res.ok ?'Farben gespeichert. Gilt beim nächsten Laden.':'Fehler beim Speichern.')
 setColorSaving(false)
 }

 async function saveHolidays(updated: CustomHoliday[]) {
 setHolidaySaving(true)
 const res = await fetch('/api/planning/settings', {
 method:'PATCH',
 headers: {'Content-Type':'application/json'},
 body: JSON.stringify({ key:'custom_holidays', value: updated }),
 })
 if (res.ok) setCustomHolidays(updated)
 else setHolidayMsg('Fehler beim Speichern.')
 setHolidaySaving(false)
 }

 function addHoliday() {
 if (!newHoliday.date || !newHoliday.name) return
 const h: CustomHoliday = {
 id: crypto.randomUUID(),
 date: newHoliday.date,
 name: newHoliday.name,
 region: newHoliday.region ??'Bayern',
 }
 const updated = [...customHolidays, h]
 void saveHolidays(updated)
 setNewHoliday({ region:'Bayern'})
 setShowForm(false)
 }

 function deleteHoliday(id: string) {
 const updated = customHolidays.filter((h) => h.id !== id)
 void saveHolidays(updated)
 setConfirmDel(null)
 }

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

 return (
 <div className="space-y-6">

 {/* Section A — Calendar Colors */}
 <div className="bg-card rounded-xl border border-muted overflow-hidden">
 <div className="px-5 py-3 border-b border-border">
 <h2 className="font-semibold text-[14px] text-foreground">Kalenderfarben</h2>
 <p className="text-[11px] text-muted-foreground mt-0.5">Zellhintergrundfarben für den Kalender anpassen</p>
 </div>

 <div className="px-5 py-4 space-y-4">
 <div className="grid grid-cols-2 gap-4">
 {(['weekday','weekend','holiday','today'] as const).map((key) => {
 const LABELS: Record<typeof key, string> = {
 weekday:'Arbeitstage',
 weekend:'Wochenende (Sa/So)',
 holiday:'Feiertage',
 today:'Heute',
 }
 return (
 <div key={key}>
 <label className={labelCls}>{LABELS[key]}</label>
 <div className="flex items-center gap-2">
 <input
 type="color"
 value={colors[key]}
 onChange={(e) => setColors((prev) => ({ ...prev, [key]: e.target.value }))}
 className="h-8 w-10 rounded border border-muted cursor-pointer p-0.5 bg-card shrink-0"
 />
 <input
 value={colors[key]}
 onChange={(e) => setColors((prev) => ({ ...prev, [key]: e.target.value }))}
 className={`${inputCls} font-mono`}
 maxLength={7}
 placeholder="#FAFAFA"
 />
 </div>
 </div>
 )
 })}
 </div>

 {/* KW-Hervorhebung */}
 <div className="border-t border-muted pt-4">
 <p className={labelCls}>Auswahl-Hervorhebung (Zeilen & KW)</p>
 <p className="text-[11px] text-muted-foreground mb-2">Gilt für Berater-Zeilen (klicken) und KW-Spalten (Mo–Fr) gleichermaßen</p>
 <div className="flex flex-wrap items-end gap-4">
 <div>
 <label className="block text-[11px] text-muted-foreground mb-1">Farbe</label>
 <div className="flex items-center gap-2">
 <input
 type="color"
 value={colors.selectionHighlightColor}
 onChange={(e) => setColors((prev) => ({ ...prev, selectionHighlightColor: e.target.value }))}
 className="h-8 w-10 rounded border border-muted cursor-pointer p-0.5 bg-card shrink-0"
 />
 <input
 value={colors.selectionHighlightColor}
 onChange={(e) => setColors((prev) => ({ ...prev, selectionHighlightColor: e.target.value }))}
 className="w-24 h-8 rounded border border-muted text-[13px] px-2 bg-card font-mono focus:outline-none focus:border-primary"
 maxLength={7}
 />
 </div>
 </div>
 <div className="flex-1 min-w-[140px]">
 <label className="block text-[11px] text-muted-foreground mb-1">
 Deckkraft: <span className="font-medium text-foreground">{colors.selectionHighlightOpacity}%</span>
 </label>
 <input
 type="range"
 min={5} max={25} step={1}
 value={colors.selectionHighlightOpacity}
 onChange={(e) => setColors((prev) => ({ ...prev, selectionHighlightOpacity: Number(e.target.value) }))}
 className="w-full h-2 accent-primary"
 />
 </div>
 <div>
 <label className="block text-[11px] text-muted-foreground mb-1">Vorschau</label>
 <div className="flex rounded border border-muted overflow-hidden">
 <div className="w-12 h-8 flex items-center justify-center text-[10px] text-muted-foreground"
 style={{ backgroundColor: colors.weekday }}>
 Mo
 </div>
 <div className="w-12 h-8 flex items-center justify-center text-[10px] font-medium text-[#1D4ED8] border-l border-muted"
 style={{ backgroundColor: (() => {
 try {
 const r = parseInt(colors.selectionHighlightColor.slice(1, 3), 16)
 const g = parseInt(colors.selectionHighlightColor.slice(3, 5), 16)
 const b = parseInt(colors.selectionHighlightColor.slice(5, 7), 16)
 return `rgba(${r},${g},${b},${colors.selectionHighlightOpacity / 100})`
 } catch { return colors.selectionHighlightColor }
 })() }}>
 Mo
 </div>
 </div>
 </div>
 </div>
 </div>

 {/* Day color preview */}
 <div>
 <p className={labelCls}>Kalender-Vorschau</p>
 <ColorPreview colors={colors} />
 </div>

 {colorMsg && (
 <p className={`text-[12px] ${colorMsg.startsWith('Fehler') ?'text-destructive':'text-status-green'}`}>
 {colorMsg}
 </p>
 )}

 <div className="flex items-center gap-2">
 <button
 onClick={() => { setColors(DEFAULT_CALENDAR_COLORS); setColorMsg(null) }}
 className="h-8 px-3 flex items-center gap-1.5 text-[12px] rounded border border-muted text-muted-foreground hover:bg-muted transition-colors"
 >
 <RotateCcw size={12} />
 Standard
 </button>
 <button
 onClick={() => void saveColors()}
 disabled={colorSaving}
 className="h-8 px-3 flex items-center gap-1.5 text-[12px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50 transition-colors"
 >
 <Save size={12} />
 {colorSaving ?'Speichern…':'Speichern'}
 </button>
 </div>
 </div>
 </div>

 {/* Section B — Holiday management */}
 <div className="bg-card rounded-xl border border-muted overflow-hidden">
 <div className="flex items-center justify-between px-5 py-3 border-b border-border">
 <div>
 <h2 className="font-semibold text-[14px] text-foreground">Feiertage verwalten</h2>
 <p className="text-[11px] text-muted-foreground mt-0.5">Bayerische Feiertage werden automatisch berechnet. Hier können zusätzliche Feiertage hinzugefügt werden.</p>
 </div>
 <button
 onClick={() => setShowForm(true)}
 className="h-8 px-3 flex items-center gap-1.5 text-[12px] font-medium rounded bg-primary text-white hover:bg-primary-dark transition-colors shrink-0"
 >
 <Plus size={12} />
 Neuer Feiertag
 </button>
 </div>

 {/* Add form */}
 {showForm && (
 <div className="px-5 py-3 bg-background border-b border-border">
 <p className={labelCls}>Neuer benutzerdefinierter Feiertag</p>
 <div className="flex flex-wrap items-end gap-2 mt-1">
 <div>
 <label className="block text-[11px] text-muted-foreground mb-1">Datum *</label>
 <input
 type="date"
 value={newHoliday.date ??''}
 onChange={(e) => setNewHoliday((p) => ({ ...p, date: e.target.value }))}
 className="h-8 rounded border border-muted text-[13px] px-2 bg-card focus:outline-none focus:border-primary"
 />
 </div>
 <div className="flex-1 min-w-[160px]">
 <label className="block text-[11px] text-muted-foreground mb-1">Name *</label>
 <input
 value={newHoliday.name ??''}
 onChange={(e) => setNewHoliday((p) => ({ ...p, name: e.target.value }))}
 placeholder="z.B. Betriebsferien"
 className={inputCls}
 />
 </div>
 <div>
 <label className="block text-[11px] text-muted-foreground mb-1">Region</label>
 <input
 value={newHoliday.region ??'Bayern'}
 onChange={(e) => setNewHoliday((p) => ({ ...p, region: e.target.value }))}
 className="h-8 w-28 rounded border border-muted text-[13px] px-2 bg-card focus:outline-none focus:border-primary"
 />
 </div>
 <div className="flex gap-1">
 <button
 onClick={addHoliday}
 disabled={!newHoliday.date || !newHoliday.name || holidaySaving}
 className="h-8 px-3 text-[12px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50"
 >
 Hinzufügen
 </button>
 <button
 onClick={() => { setShowForm(false); setNewHoliday({ region:'Bayern'}) }}
 className="h-8 w-8 flex items-center justify-center rounded border border-muted text-muted-foreground hover:bg-muted"
 >
 <X size={13} />
 </button>
 </div>
 </div>
 </div>
 )}

 {/* Holidays table */}
 <div className="divide-y divide-muted max-h-72 overflow-y-auto">
 {allHolidays.length === 0 && (
 <p className="px-5 py-4 text-[12px] text-muted-foreground italic">Keine Feiertage für {currentYear} definiert.</p>
 )}
 {allHolidays.map((h, i) => (
 <div key={`${h.date}-${i}`} className="flex items-center gap-3 px-5 py-2">
 <span className="text-[12px] font-mono text-muted-foreground w-20 shrink-0">{fmtDate(h.date)}</span>
 <span className="flex-1 text-[12px] text-foreground">{h.name}</span>
 <span className="text-[11px] text-muted-foreground shrink-0">{h.region}</span>
 {h.isCustom ? (
 confirmDel === h.id ? (
 <div className="flex items-center gap-1 shrink-0">
 <button
 onClick={() => h.id && deleteHoliday(h.id)}
 className="h-6 px-2 text-[11px] rounded bg-destructive text-white hover:bg-destructive"
 >
 Löschen
 </button>
 <button
 onClick={() => setConfirmDel(null)}
 className="h-6 px-2 text-[11px] rounded border border-muted text-foreground"
 >
 Nein
 </button>
 </div>
 ) : (
 <button
 onClick={() => setConfirmDel(h.id ?? null)}
 className="w-6 h-6 flex items-center justify-center rounded hover:bg-status-red-soft text-destructive shrink-0"
 >
 <Trash2 size={11} />
 </button>
 )
 ) : (
 <div className="w-6 h-6 shrink-0"/>
 )}
 </div>
 ))}
 </div>

 {holidayMsg && (
 <p className="px-5 py-2 text-[12px] text-destructive">{holidayMsg}</p>
 )}
 </div>
 </div>
 )
}
