'use client'; import { useEffect, useState } from 'react'; import { useRouter, useParams } from 'next/navigation'; import api from '@/lib/api'; import { ArrowLeftIcon, PlayIcon, PlusIcon, TrashIcon, GripVerticalIcon, ClockIcon } from '@/components/ui/Icons'; import Link from 'next/link'; interface Step { id: string; name: string; instructions?: string; step_type: string; duration_minutes?: number; position: number; } interface Routine { id: string; name: string; description?: string; icon?: string; location?: string; environment_prompts?: string[]; habit_stack_after?: string; } const ICONS = ['✨', '🌅', '🌙', '☀️', '💪', '🧘', '📚', '🍳', '🏃', '💼', '🎯', '⭐', '🔥', '💤', '🧠']; export default function RoutineDetailPage() { const router = useRouter(); const params = useParams(); const routineId = params.id as string; const [routine, setRoutine] = useState(null); const [steps, setSteps] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isEditing, setIsEditing] = useState(false); const [editName, setEditName] = useState(''); const [editDescription, setEditDescription] = useState(''); const [editIcon, setEditIcon] = useState('✨'); const [editLocation, setEditLocation] = useState(''); const [editHabitStack, setEditHabitStack] = useState(''); const [editEnvPrompts, setEditEnvPrompts] = useState([]); const [newEnvPrompt, setNewEnvPrompt] = useState(''); const [newStepName, setNewStepName] = useState(''); const [newStepDuration, setNewStepDuration] = useState(5); useEffect(() => { const fetchRoutine = async () => { try { const data = await api.routines.get(routineId); setRoutine(data.routine); setSteps(data.steps); setEditName(data.routine.name); setEditDescription(data.routine.description || ''); setEditIcon(data.routine.icon || '✨'); setEditLocation((data.routine as Routine).location || ''); setEditHabitStack((data.routine as Routine).habit_stack_after || ''); setEditEnvPrompts((data.routine as Routine).environment_prompts || []); } catch (err) { console.error('Failed to fetch routine:', err); router.push('/dashboard/routines'); } finally { setIsLoading(false); } }; fetchRoutine(); }, [routineId, router]); const handleStart = () => { router.push(`/dashboard/routines/${routineId}/launch`); }; const handleSaveBasicInfo = async () => { try { await api.routines.update(routineId, { name: editName, description: editDescription, icon: editIcon, location: editLocation || null, habit_stack_after: editHabitStack || null, environment_prompts: editEnvPrompts, }); setRoutine({ ...routine!, name: editName, description: editDescription, icon: editIcon, location: editLocation || undefined, habit_stack_after: editHabitStack || undefined, environment_prompts: editEnvPrompts, }); setIsEditing(false); } catch (err) { console.error('Failed to update routine:', err); } }; const handleAddStep = async () => { if (!newStepName.trim()) return; try { const step = await api.routines.addStep(routineId, { name: newStepName, duration_minutes: newStepDuration, }); setSteps([...steps, { ...step, name: newStepName, step_type: 'generic', position: steps.length + 1 }]); setNewStepName(''); } catch (err) { console.error('Failed to add step:', err); } }; const handleDeleteStep = async (stepId: string) => { try { await api.routines.deleteStep(routineId, stepId); setSteps(steps.filter(s => s.id !== stepId).map((s, i) => ({ ...s, position: i + 1 }))); } catch (err) { console.error('Failed to delete step:', err); } }; const totalDuration = steps.reduce((acc, s) => acc + (s.duration_minutes || 0), 0); if (isLoading) { return (
); } if (!routine) return null; return (

{isEditing ? 'Edit Routine' : routine.name}

{!isEditing && ( )}
{isEditing ? (
{ICONS.map((i) => ( ))}
setEditName(e.target.value)} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none" />
setEditDescription(e.target.value)} className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none" />
setEditLocation(e.target.value)} placeholder="Where do you do this? e.g., bathroom, kitchen" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none" />
setEditHabitStack(e.target.value)} placeholder="What do you do right before? e.g., finish breakfast" className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none" />

Quick checklist shown before starting

{editEnvPrompts.map((prompt, i) => (
{prompt}
))}
setNewEnvPrompt(e.target.value)} placeholder="e.g., Water bottle nearby?" className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 outline-none" onKeyDown={(e) => { if (e.key === 'Enter' && newEnvPrompt.trim()) { setEditEnvPrompts([...editEnvPrompts, newEnvPrompt.trim()]); setNewEnvPrompt(''); } }} />
) : (
{routine.icon || '✨'}

{routine.name}

{routine.description && (

{routine.description}

)}
{totalDuration} min {steps.length} steps
)} {/* Steps */}

Steps

{steps.length >= 4 && steps.length <= 7 && ( Good length )}
{steps.length > 7 && (

Tip: Routines with 4-7 steps tend to feel more manageable. Consider combining related steps.

)}
setNewStepName(e.target.value)} placeholder="New step name" className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none" />
{steps.length === 0 ? (

No steps yet

) : (
{steps.map((step, index) => (
{index + 1}

{step.name}

{step.duration_minutes && (

{step.duration_minutes} min

)}
))}
)}
); }