'use client' import { useState, useEffect, useMemo } from 'react' import { ChevronLeft, ChevronRight, Plus, X, Clock, MapPin, Trash2, Eye, EyeOff } from 'lucide-react' interface CalendarEvent { id: string title: string start: string end: string allDay: boolean description: string | null location: string | null owner: string ownerName: string color: string } const WEEKDAYS = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'] const MONTHS = ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'] function AddEventModal({ defaultDate, onClose, onSaved }: { defaultDate: string; onClose: () => void; onSaved: (e: any) => void }) { const [title, setTitle] = useState('') const [date, setDate] = useState(defaultDate) const [startTime, setStartTime] = useState('10:00') const [endTime, setEndTime] = useState('11:00') const [allDay, setAllDay] = useState(false) const [saving, setSaving] = useState(false) const [error, setError] = useState('') const inputStyle = { padding: '12px 16px', borderRadius: 14, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)', color: 'var(--text-primary)', fontSize: 14, outline: 'none', fontFamily: 'inherit', } const save = async () => { if (!title.trim()) { setError('Введите название'); return } setSaving(true); setError('') try { const body = { title: title.trim(), date, startTime: allDay ? null : startTime, endTime: allDay ? null : endTime, allDay } const r = await fetch('/api/calendar', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) const d = await r.json() if (d.error) throw new Error(d.error) onSaved(d.event) } catch (e: any) { setError(e.message || 'Ошибка сохранения'); setSaving(false) } } return (
e.stopPropagation()}>
Новое событие
setTitle(e.target.value)} placeholder="Название события" autoFocus style={inputStyle} /> setDate(e.target.value)} style={inputStyle} /> {!allDay && (
setStartTime(e.target.value)} style={{ ...inputStyle, flex: 1 }} /> setEndTime(e.target.value)} style={{ ...inputStyle, flex: 1 }} />
)} {error &&
{error}
}
) } export default function CalendarTab() { const [year, setYear] = useState(new Date().getFullYear()) const [month, setMonth] = useState(new Date().getMonth()) const [events, setEvents] = useState([]) const [loading, setLoading] = useState(true) const [selectedEvent, setSelectedEvent] = useState(null) const [showAddModal, setShowAddModal] = useState(false) const [addDate, setAddDate] = useState('') const [deleting, setDeleting] = useState(false) const [confirmDelete, setConfirmDelete] = useState(false) const [hiddenOwners, setHiddenOwners] = useState>(new Set()) useEffect(() => { setLoading(true) fetch('/api/calendar?range=month&year=' + year + '&month=' + month) .then(r => r.json()) .then(d => { setEvents(d.events || []); setLoading(false) }) .catch(() => setLoading(false)) }, [year, month]) const deleteEvent = async (event: CalendarEvent) => { setDeleting(true) try { const r = await fetch(`/api/calendar?eventId=${event.id}`, { method: 'DELETE' }) const d = await r.json() if (d.error) throw new Error(d.error) setEvents(prev => prev.filter(e => e.id !== event.id)) setSelectedEvent(null) setConfirmDelete(false) } catch (e: any) { alert(e.message || 'Ошибка удаления') } finally { setDeleting(false) } } // Discover unique calendar owners from loaded events const calendarOwners = useMemo(() => { const map = new Map() events.forEach(e => { const existing = map.get(e.owner) if (existing) { existing.count++ } else { map.set(e.owner, { owner: e.owner, ownerName: e.ownerName, color: e.color, count: 1 }) } }) return Array.from(map.values()) }, [events]) const toggleOwner = (owner: string) => { setHiddenOwners(prev => { const next = new Set(prev) if (next.has(owner)) next.delete(owner) else next.add(owner) return next }) } const filteredEvents = useMemo(() => { if (hiddenOwners.size === 0) return events return events.filter(e => !hiddenOwners.has(e.owner)) }, [events, hiddenOwners]) const upcoming = filteredEvents .filter(e => new Date(e.start) >= new Date()) .slice(0, 6) const firstDay = new Date(year, month, 1) const lastDay = new Date(year, month + 1, 0) const startOffset = (firstDay.getDay() + 6) % 7 const totalCells = Math.ceil((startOffset + lastDay.getDate()) / 7) * 7 const cells: (number | null)[] = [] for (let i = 0; i < totalCells; i++) { const dayNum = i - startOffset + 1 cells.push(dayNum >= 1 && dayNum <= lastDay.getDate() ? dayNum : null) } const getEventsForDay = (day: number) => { return filteredEvents.filter(e => { const d = new Date(e.start) return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day }) } const prevMonth = () => { if (month === 0) { setMonth(11); setYear(y => y - 1) } else setMonth(m => m - 1) } const nextMonth = () => { if (month === 11) { setMonth(0); setYear(y => y + 1) } else setMonth(m => m + 1) } const today = new Date() return (
{/* Main calendar grid */}
{/* Header */}
{MONTHS[month]} {year}
{/* Calendar owner filters */} {calendarOwners.map(cal => { const isHidden = hiddenOwners.has(cal.owner) return ( ) })}
{/* Weekday headers */}
{WEEKDAYS.map((d, i) => (
= 5 ? 'rgba(248,113,113,0.5)' : 'var(--text-secondary)', textTransform: 'uppercase', padding: '6px 0', letterSpacing: '0.05em', }}>{d}
))}
{/* Calendar cells */}
{cells.map((day, idx) => { if (!day) return
const dayEvents = getEventsForDay(day) const isToday = today.getFullYear() === year && today.getMonth() === month && today.getDate() === day const dayOfWeek = (startOffset + day - 1) % 7 const isWeekend = dayOfWeek >= 5 return (
{ if (dayEvents.length === 1) setSelectedEvent(dayEvents[0]) else if (dayEvents.length === 0) { setAddDate(`${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`) setShowAddModal(true) } }} style={{ borderRadius: 12, padding: '5px 4px', background: isToday ? 'linear-gradient(135deg, rgba(99,102,241,0.15), rgba(139,92,246,0.08))' : 'rgba(255,255,255,0.015)', border: isToday ? '1px solid rgba(129,140,248,0.3)' : '1px solid transparent', cursor: 'pointer', minHeight: 56, display: 'flex', flexDirection: 'column', gap: 2, transition: 'all 0.2s ease', }} > {day} {dayEvents.slice(0, 2).map(e => (
{ ev.stopPropagation(); setSelectedEvent(e) }} style={{ fontSize: 10, fontWeight: 600, background: e.color + '1a', border: `1px solid ${e.color}30`, color: e.color, borderRadius: 6, padding: '2px 5px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: 'pointer', }}> {e.title}
))} {dayEvents.length > 2 && (
+{dayEvents.length - 2}
)}
) })}
{/* Right panel */}
Ближайшие
{upcoming.length === 0 && !loading && (
Нет событий
)} {upcoming.map(e => { const d = new Date(e.start) return (
setSelectedEvent(e)} style={{ borderRadius: 16, padding: '14px', background: `${e.color}0c`, border: `1px solid ${e.color}1a`, cursor: 'pointer', transition: 'all 0.25s ease', }}>
{d.getDate()}
{MONTHS[d.getMonth()].slice(0, 3)}
{e.title}
{e.allDay ? 'Весь день' : d.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}
{e.ownerName}
) })}
{/* Event detail modal */} {selectedEvent && (
{ setSelectedEvent(null); setConfirmDelete(false) }}>
e.stopPropagation()}>
{selectedEvent.title}
{selectedEvent.ownerName}
{selectedEvent.allDay ? 'Весь день' : `${new Date(selectedEvent.start).toLocaleString('ru-RU', { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' })} — ${new Date(selectedEvent.end).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}`}
{selectedEvent.location && (
{selectedEvent.location}
)} {selectedEvent.description && (
{selectedEvent.description}
)}
{!confirmDelete ? ( ) : (
)}
)} {showAddModal && ( setShowAddModal(false)} onSaved={(newEvent) => { setEvents(prev => [...prev, newEvent]); setShowAddModal(false) }} /> )}
) }