'use client'; import { useEffect, useState } from 'react'; import { crmTaskCalendarService, CrmCalendarEvent } from '@/services/api/crmTaskCalendarService'; import { systemConfigService, CrmLocation } from '@/services/api/systemConfigService'; import { Calendar as CalendarIcon, Plus, ChevronLeft, ChevronRight, Clock, Store, X, CheckCircle2, Trash2 } from 'lucide-react'; import { toast } from 'sonner'; export default function CrmCalendarPage() { const [events, setEvents] = useState([]); const [locations, setLocations] = useState([]); const [loading, setLoading] = useState(true); // Month navigation const [currentDate, setCurrentDate] = useState(new Date()); // Modal Create State 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 (

CRM Interactive Calendar Engine

Schedule customer service appointments, repair pick-ups, team meetings, and quotation follow-ups.

{/* Calendar Header Navigation */}

{monthName} {year}

{events.length} Events Scheduled
{/* Month View Grid */}
{/* Days of week header */}
SUN
MON
TUE
WED
THU
FRI
SAT
{/* Calendar Cells */}
{/* Empty cells before month start */} {Array.from({ length: firstDayOfMonth }).map((_, idx) => (
))} {/* Month Day Cells */} {daysArray.map((dayNum) => { const cellDateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(dayNum).padStart(2, '0')}`; const isToday = new Date().toDateString() === new Date(year, month, dayNum).toDateString(); const dayEvents = events.filter((e) => { if (!e.start_time) return false; const d = new Date(e.start_time); return d.getFullYear() === year && d.getMonth() === month && d.getDate() === dayNum; }); return (
{dayNum} {dayEvents.length > 0 && ( {dayEvents.length} )}
{dayEvents.map((evt) => { const locName = locations.find((l) => l.location_id === evt.location_id)?.name; return (

{evt.title}

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

); })}
); })}
{/* Modal: Schedule Event */} {isModalOpen && (

Schedule Calendar Event

setTitle(e.target.value)} placeholder="e.g. VIP Customer Quotation Consultation" className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden font-semibold" />