'use client'; import { useEffect, useState, type ReactNode } from 'react'; import { format } from 'date-fns'; import { CheckCircle2, Circle, Plus, RefreshCw, Trash2 } from 'lucide-react'; import { toast } from 'sonner'; import { crmTaskCalendarService, CrmTask } 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 PRIORITY_META: Record = { HIGH: { label: 'High', className: 'bg-destructive/10 text-destructive' }, MEDIUM: { label: 'Medium', className: 'bg-warning/15 text-warning' }, LOW: { label: 'Low', className: 'bg-muted text-foreground' }, }; function priorityMeta(priority?: string) { return PRIORITY_META[priority || ''] || { label: priority || '—', className: 'bg-muted text-foreground' }; } function formatDue(iso?: string) { if (!iso) return '—'; const date = new Date(iso); if (Number.isNaN(date.getTime())) return '—'; return format(date, 'dd MMM yyyy, hh:mm a'); } export default function CrmTodosPage() { const [tasks, setTasks] = useState([]); const [locations, setLocations] = useState([]); const [loading, setLoading] = useState(true); const [filterStatus, setFilterStatus] = useState('ALL'); const [filterPriority, setFilterPriority] = useState('ALL'); const [filterLocationId, setFilterLocationId] = useState('ALL'); const [isModalOpen, setIsModalOpen] = useState(false); const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [locationId, setLocationId] = useState(''); const [priority, setPriority] = useState('MEDIUM'); const [entityType, setEntityType] = useState(''); const [entityId, setEntityId] = useState(''); const [dueAt, setDueAt] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { loadData(); }, []); const loadData = async () => { try { setLoading(true); const [taskData, locData] = await Promise.all([ crmTaskCalendarService.getTasks(), systemConfigService.getLocations(), ]); setTasks(Array.isArray(taskData) ? taskData : []); setLocations(Array.isArray(locData) ? locData : []); } catch { toast.error('Failed to load CRM tasks'); } finally { setLoading(false); } }; const handleCreateTask = async (e: React.FormEvent) => { e.preventDefault(); if (!title.trim()) { toast.error('Task title is required'); return; } try { setIsSubmitting(true); await crmTaskCalendarService.createTask({ title: title.trim(), description: description || undefined, location_id: locationId || undefined, priority: priority, status: 'PENDING', entity_type: entityType || undefined, entity_id: entityId || undefined, due_at: dueAt ? new Date(dueAt).toISOString() : undefined, }); toast.success('CRM Task created successfully!'); setIsModalOpen(false); setTitle(''); setDescription(''); setLocationId(''); setPriority('MEDIUM'); setEntityType(''); setEntityId(''); setDueAt(''); loadData(); } catch (err: any) { toast.error(err?.message || 'Failed to create task'); } finally { setIsSubmitting(false); } }; const handleToggleStatus = async (task: CrmTask) => { const newStatus = task.status === 'COMPLETED' ? 'PENDING' : 'COMPLETED'; try { await crmTaskCalendarService.updateTask(task.task_id, { status: newStatus }); toast.success(`Task marked as ${newStatus}`); loadData(); } catch { toast.error('Failed to update task status'); } }; const handleDeleteTask = async (taskId: string) => { if (!confirm('Are you sure you want to delete this task?')) return; try { await crmTaskCalendarService.deleteTask(taskId); toast.success('Task deleted'); loadData(); } catch { toast.error('Failed to delete task'); } }; const filteredTasks = tasks.filter((t) => { if (filterStatus !== 'ALL' && t.status !== filterStatus) return false; if (filterPriority !== 'ALL' && t.priority !== filterPriority) return false; if (filterLocationId !== 'ALL' && t.location_id !== filterLocationId) return false; return true; }); return (

Tasks

{filteredTasks.length}
({ value: loc.location_id, label: loc.name })), ]} />
{loading ? (

Loading tasks

) : (
{filteredTasks.length === 0 ? ( ) : filteredTasks.map((task) => { const locName = locations.find((l) => l.location_id === task.location_id)?.name; const isDone = task.status === 'COMPLETED'; const priority = priorityMeta(task.priority); return ( ); })}
Task Priority Location Linked Due Action
No tasks match this view.

{task.title}

{task.description &&

{task.description}

}
{priority.label} {locName || '—'} {task.entity_type ? `${task.entity_type.replaceAll('_', ' ').toLowerCase()}${task.entity_id ? ` · ${task.entity_id}` : ''}` : '—'} {formatDue(task.due_at)}
)}
setIsModalOpen(false)}>
setTitle(e.target.value)} className={field} />