'use client'; import { useEffect, useState, type ReactNode } from 'react'; import { ChevronLeft, ChevronRight, Plus, RefreshCw, Trash2 } from 'lucide-react'; import { toast } from 'sonner'; import { crmTaskCalendarService, CrmCalendarEvent } from '@/services/api/crmTaskCalendarService'; import { systemConfigService, CrmLocation } from '@/services/api/systemConfigService'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { SlideOver } from '@/components/ui/SlideOver'; const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const field = 'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const primaryButton = 'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-2 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50'; const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; export default function CrmCalendarPage() { const [events, setEvents] = useState([]); const [locations, setLocations] = useState([]); const [loading, setLoading] = useState(true); const [currentDate, setCurrentDate] = useState(new Date()); const [isModalOpen, setIsModalOpen] = useState(false); const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [locationId, setLocationId] = useState(''); const [startTime, setStartTime] = useState(''); const [endTime, setEndTime] = useState(''); const [isAllDay, setIsAllDay] = useState(false); const [sourceType, setSourceType] = useState('MANUAL'); const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { loadData(); }, []); const loadData = async () => { try { setLoading(true); const [evtData, locData] = await Promise.all([ crmTaskCalendarService.getCalendarEvents(), systemConfigService.getLocations(), ]); setEvents(Array.isArray(evtData) ? evtData : []); setLocations(Array.isArray(locData) ? locData : []); } catch { toast.error('Failed to load CRM calendar events'); } finally { setLoading(false); } }; const handleCreateEvent = async (e: React.FormEvent) => { e.preventDefault(); if (!title.trim() || !startTime || !endTime) { toast.error('Title, start time, and end time are required'); return; } try { setIsSubmitting(true); await crmTaskCalendarService.createCalendarEvent({ title: title.trim(), description: description || undefined, location_id: locationId || undefined, start_time: new Date(startTime).toISOString(), end_time: new Date(endTime).toISOString(), is_all_day: isAllDay, source_type: sourceType, status: 'SCHEDULED', }); toast.success('Calendar event scheduled!'); setIsModalOpen(false); setTitle(''); setDescription(''); setLocationId(''); setStartTime(''); setEndTime(''); setIsAllDay(false); loadData(); } catch (err: any) { toast.error(err?.message || 'Failed to schedule calendar event'); } finally { setIsSubmitting(false); } }; const handleDeleteEvent = async (eventId: string) => { if (!confirm('Are you sure you want to delete this event?')) return; try { await crmTaskCalendarService.deleteCalendarEvent(eventId); toast.success('Calendar event removed'); loadData(); } catch { toast.error('Failed to delete event'); } }; const handlePrevMonth = () => { setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1)); }; const handleNextMonth = () => { setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1)); }; const year = currentDate.getFullYear(); const month = currentDate.getMonth(); const monthName = currentDate.toLocaleString('default', { month: 'long' }); const firstDayOfMonth = new Date(year, month, 1).getDay(); const daysInMonth = new Date(year, month + 1, 0).getDate(); const daysArray = Array.from({ length: daysInMonth }, (_, i) => i + 1); return (

Calendar

{events.length}

{monthName} {year}

{WEEKDAYS.map((day) => (
{day}
))}
{Array.from({ length: firstDayOfMonth }).map((_, idx) => (
))} {daysArray.map((dayNum) => { const isToday = new Date().toDateString() === new Date(year, month, dayNum).toDateString(); const dayEvents = events.filter((event) => { if (!event.start_time) return false; const date = new Date(event.start_time); return date.getFullYear() === year && date.getMonth() === month && date.getDate() === dayNum; }); return (
{dayNum} {dayEvents.length > 0 && ( {dayEvents.length} )}
{dayEvents.map((event) => { const locName = locations.find((location) => location.location_id === event.location_id)?.name; return (

{event.title}

{new Date(event.start_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} {locName ? ` ยท ${locName}` : ''}

); })}
); })}
setIsModalOpen(false)}>
setTitle(e.target.value)} className={field} />