'use client'; import { useState } from 'react'; import { useRouter } from 'next/navigation'; import Link from 'next/link'; import api from '@/lib/api'; import { ArrowLeftIcon, PlusIcon, TrashIcon, GripVerticalIcon, CopyIcon, SparklesIcon } from '@/components/ui/Icons'; interface Step { id: string; name: string; duration_minutes?: number; position: number; } const ICONS = ['✨', '🌅', '🌙', '☀️', '💪', '🧘', '📚', '🍳', '🏃', '💼', '🎯', '⭐', '🔥', '💤', '🧠', '☕', '🍎', '💧', '🍀', '🎵', '📝', '🚴', '🏋️', '🚶', '👀', '🛡️', '😊', '😔']; const STEP_TYPES = [ { value: 'generic', label: 'Generic' }, { value: 'timer', label: 'Timer' }, { value: 'checklist', label: 'Checklist' }, { value: 'meditation', label: 'Meditation' }, { value: 'exercise', label: 'Exercise' }, ]; const DAY_OPTIONS = [ { value: 'mon', label: 'Mon' }, { value: 'tue', label: 'Tue' }, { value: 'wed', label: 'Wed' }, { value: 'thu', label: 'Thu' }, { value: 'fri', label: 'Fri' }, { value: 'sat', label: 'Sat' }, { value: 'sun', label: 'Sun' }, ]; export default function NewRoutinePage() { const router = useRouter(); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [icon, setIcon] = useState('✨'); const [steps, setSteps] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(''); const [isGenerating, setIsGenerating] = useState(false); const [aiGoal, setAiGoal] = useState(''); const [showAiInput, setShowAiInput] = useState(false); const [aiError, setAiError] = useState(''); // Schedule const [scheduleDays, setScheduleDays] = useState(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']); const [scheduleTime, setScheduleTime] = useState('08:00'); const [scheduleRemind, setScheduleRemind] = useState(true); const [scheduleFrequency, setScheduleFrequency] = useState<'weekly' | 'every_n_days'>('weekly'); const [scheduleIntervalDays, setScheduleIntervalDays] = useState(2); const [scheduleStartDate, setScheduleStartDate] = useState(() => new Date().toISOString().split('T')[0]); const toggleDay = (day: string) => { setScheduleDays(prev => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day] ); }; const handleAddStep = () => { const newStep: Step = { id: `temp-${Date.now()}`, name: '', duration_minutes: 5, position: steps.length + 1, }; setSteps([...steps, newStep]); }; const handleUpdateStep = (index: number, updates: Partial) => { const newSteps = [...steps]; newSteps[index] = { ...newSteps[index], ...updates }; setSteps(newSteps); }; const handleDeleteStep = (index: number) => { const newSteps = steps.filter((_, i) => i !== index); setSteps(newSteps.map((s, i) => ({ ...s, position: i + 1 }))); }; const handleGenerateSteps = async () => { const goal = aiGoal.trim() || name.trim(); if (!goal) { setAiError('Enter a goal or fill in the routine name first.'); return; } setIsGenerating(true); setAiError(''); try { const result = await api.ai.generateSteps(goal); const generated = result.steps.map((s, i) => ({ id: `temp-${Date.now()}-${i}`, name: s.name, duration_minutes: s.duration_minutes, position: steps.length + i + 1, })); setSteps(prev => [...prev, ...generated]); setShowAiInput(false); } catch (err) { setAiError((err as Error).message || 'Failed to generate steps. Try again.'); } finally { setIsGenerating(false); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!name.trim()) { setError('Please enter a routine name'); return; } const validSteps = steps.filter(s => s.name.trim()); if (validSteps.length === 0) { setError('Please add at least one step'); return; } setIsLoading(true); setError(''); try { const routine = await api.routines.create({ name, description, icon }); for (const step of validSteps) { await api.routines.addStep(routine.id, { name: step.name, duration_minutes: step.duration_minutes, }); } if (scheduleFrequency === 'every_n_days' || scheduleDays.length > 0) { await api.routines.setSchedule(routine.id, { days: scheduleDays, time: scheduleTime, remind: scheduleRemind, frequency: scheduleFrequency, ...(scheduleFrequency === 'every_n_days' && { interval_days: scheduleIntervalDays, start_date: scheduleStartDate, }), }); } router.push(`/dashboard/routines/${routine.id}?new=1`); } catch (err) { setError((err as Error).message || 'Failed to create routine'); } finally { setIsLoading(false); } }; return (

New Routine

Start from a template

Browse pre-made routines

Recommended
{error && (
{error}
)} {/* Basic Info */}
{ICONS.map((i) => ( ))}
setName(e.target.value)} placeholder="Morning Routine" className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500 outline-none" />
setDescription(e.target.value)} placeholder="Start your day right" className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500 outline-none" />
{/* Schedule */}

Schedule (optional)

{/* Frequency selector */}
{scheduleFrequency === 'every_n_days' ? (
setScheduleIntervalDays(Math.max(2, Number(e.target.value)))} className="w-20 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none" /> days
setScheduleStartDate(e.target.value)} className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none" />
) : ( <> {/* Quick select buttons */}
{DAY_OPTIONS.map((day) => ( ))}
)}
setScheduleTime(e.target.value)} className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-indigo-500 outline-none" />

Send reminder

Get notified when it's time

{/* Steps */}

Steps

|
{/* AI Generation Panel */} {showAiInput && (

Describe your goal and AI will suggest steps