'use client' import { useState, useEffect } from 'react' import { useRouter } from 'next/navigation' import { Clock, Calendar, Repeat, Pill, Package, ChevronDown, Plus, X } from 'lucide-react' import { Button, Input, Textarea, Select, showToast } from '@/components/ui' import { useApp } from '@/app/(app)/provider' type ScheduleType = 'FIXED_TIMES' | 'INTERVAL' | 'WEEKDAYS' | 'PRN' const scheduleTypeOptions = [ { value: 'FIXED_TIMES', label: 'Fixed times daily', icon: Clock, desc: 'Same times every day' }, { value: 'INTERVAL', label: 'Every X hours', icon: Repeat, desc: 'Regular intervals' }, { value: 'WEEKDAYS', label: 'Specific days', icon: Calendar, desc: 'Certain days of the week' }, { value: 'PRN', label: 'As needed (PRN)', icon: Pill, desc: 'When you need it' }, ] const weekdays = [ { value: 0, label: 'Sun', full: 'Sunday' }, { value: 1, label: 'Mon', full: 'Monday' }, { value: 2, label: 'Tue', full: 'Tuesday' }, { value: 3, label: 'Wed', full: 'Wednesday' }, { value: 4, label: 'Thu', full: 'Thursday' }, { value: 5, label: 'Fri', full: 'Friday' }, { value: 6, label: 'Sat', full: 'Saturday' }, ] interface MedicationFormProps { initialData?: { id?: string name: string instructions?: string | null scheduleType: string scheduleData: any active?: boolean pillCount?: number | null pillsPerDose?: number | null refillThreshold?: number | null } isEditing?: boolean } export function MedicationForm({ initialData, isEditing = false }: MedicationFormProps) { const router = useRouter() const { currentWorkspace, refreshData } = useApp() const [mounted, setMounted] = useState(false) const [name, setName] = useState(initialData?.name || '') const [instructions, setInstructions] = useState(initialData?.instructions || '') const [scheduleType, setScheduleType] = useState((initialData?.scheduleType as ScheduleType) || 'FIXED_TIMES') // Fixed times const [times, setTimes] = useState(initialData?.scheduleData?.times || ['08:00']) // Interval const [intervalHours, setIntervalHours] = useState(initialData?.scheduleData?.hours || 8) const [startTime, setStartTime] = useState(initialData?.scheduleData?.startTime || '08:00') // Weekdays const [selectedDays, setSelectedDays] = useState(initialData?.scheduleData?.days || [1, 3, 5]) const [weekdayTime, setWeekdayTime] = useState(initialData?.scheduleData?.time || '09:00') // PRN const [minHoursBetween, setMinHoursBetween] = useState(initialData?.scheduleData?.minHoursBetween || 4) // Refill tracking (optional) const hasRefillInfo = initialData?.pillCount !== null && initialData?.pillCount !== undefined const [trackRefills, setTrackRefills] = useState(hasRefillInfo) const [pillCount, setPillCount] = useState(initialData?.pillCount ?? '') const [pillsPerDose, setPillsPerDose] = useState(initialData?.pillsPerDose || 1) const [refillThreshold, setRefillThreshold] = useState(initialData?.refillThreshold || 7) const [loading, setLoading] = useState(false) const [error, setError] = useState('') useEffect(() => { setMounted(true) }, []) useEffect(() => { if (initialData?.scheduleType !== scheduleType) { // Keep current state if user is just switching around in new mode } }, [scheduleType, initialData]) const addTime = () => { setTimes([...times, '12:00']) } const removeTime = (index: number) => { setTimes(times.filter((_, i) => i !== index)) } const updateTime = (index: number, value: string) => { const newTimes = [...times] newTimes[index] = value setTimes(newTimes) } const toggleDay = (day: number) => { if (selectedDays.includes(day)) { setSelectedDays(selectedDays.filter((d) => d !== day)) } else { setSelectedDays([...selectedDays, day].sort()) } } const buildScheduleData = () => { switch (scheduleType) { case 'FIXED_TIMES': return { type: 'FIXED_TIMES', times } case 'INTERVAL': return { type: 'INTERVAL', hours: intervalHours, startTime } case 'WEEKDAYS': return { type: 'WEEKDAYS', days: selectedDays, time: weekdayTime } case 'PRN': return { type: 'PRN', minHoursBetween } } } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setError('') setLoading(true) try { const url = isEditing && initialData?.id ? `/api/workspaces/${currentWorkspace.id}/medications/${initialData.id}` : `/api/workspaces/${currentWorkspace.id}/medications` const method = isEditing ? 'PATCH' : 'POST' const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, instructions: instructions || null, scheduleType, scheduleData: buildScheduleData(), active: true, ...(trackRefills && pillCount !== '' && { pillCount: Number(pillCount), pillsPerDose, refillThreshold, }), ...(isEditing && !trackRefills && { pillCount: null, pillsPerDose: null, refillThreshold: null, }) }), }) if (!response.ok) { const data = await response.json() throw new Error(data.error || 'Failed to save medication') } await refreshData() showToast(isEditing ? 'Medication updated' : 'Medication added', 'success') router.push('/meds') } catch (err) { setError(err instanceof Error ? err.message : 'Something went wrong') } finally { setLoading(false) } } const currentScheduleOption = scheduleTypeOptions.find(opt => opt.value === scheduleType) const ScheduleIcon = currentScheduleOption?.icon || Clock return (
{/* Form Header */}

{isEditing ? 'Edit Medication' : 'Add Medication'}

{isEditing ? 'Update your medication details' : 'Keep track of your medications'}

{/* Basic Info Section */}

1 Basic Information

setName(e.target.value)} placeholder="e.g., Paracetamol 500mg" className="input-sanctuary w-full" required />