'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams, useSearchParams } 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;
}

interface Schedule {
  days: string[];
  time: string;
  remind: boolean;
}

const ICONS = ['✨', '🌅', '🌙', '☀️', '💪', '🧘', '📚', '🍳', '🏃', '💼', '🎯', '⭐', '🔥', '💤', '🧠', '☕', '🍎', '💧', '🍀', '🎵', '📝', '🚴', '🏋️', '🚶', '👀', '🛡️', '😊', '😔'];

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' },
];

function formatDays(days: string[]): string {
  if (days.length === 7) return 'Every day';
  if (days.length === 5 && ['mon', 'tue', 'wed', 'thu', 'fri'].every(d => days.includes(d))) return 'Weekdays';
  if (days.length === 2 && ['sat', 'sun'].every(d => days.includes(d))) return 'Weekends';
  return days.map(d => DAY_OPTIONS.find(o => o.value === d)?.label || d).join(', ');
}

export default function RoutineDetailPage() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const routineId = params.id as string;
  const isNewRoutine = searchParams.get('new') === '1';

  const [routine, setRoutine] = useState<Routine | null>(null);
  const [steps, setSteps] = useState<Step[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [isDeleting, setIsDeleting] = 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<string[]>([]);
  const [newEnvPrompt, setNewEnvPrompt] = useState('');
  const [newStepName, setNewStepName] = useState('');
  const [newStepDuration, setNewStepDuration] = useState(5);

  // Schedule state
  const [schedule, setSchedule] = useState<Schedule | null>(null);
  const [editDays, setEditDays] = useState<string[]>(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']);
  const [editTime, setEditTime] = useState('08:00');
  const [editRemind, setEditRemind] = useState(true);
  const [showScheduleEditor, setShowScheduleEditor] = useState(false);

  useEffect(() => {
    const fetchRoutine = async () => {
      try {
        const [data, scheduleData] = await Promise.all([
          api.routines.get(routineId),
          api.routines.getSchedule(routineId).catch(() => null),
        ]);
        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 || []);
        if (scheduleData) {
          setSchedule(scheduleData);
          setEditDays(scheduleData.days || []);
          setEditTime(scheduleData.time || '08:00');
          setEditRemind(scheduleData.remind ?? true);
        } else {
          setEditDays(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']);
          if (isNewRoutine) {
            setShowScheduleEditor(true);
          }
        }
      } catch (err) {
        console.error('Failed to fetch routine:', err);
        router.push('/dashboard/routines');
      } finally {
        setIsLoading(false);
      }
    };
    fetchRoutine();
  }, [routineId, router, isNewRoutine]);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (showScheduleEditor) {
          setShowScheduleEditor(false);
        } else if (isEditing) {
          setIsEditing(false);
        }
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isEditing, showScheduleEditor]);

  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 handleSaveSchedule = async () => {
    try {
      if (editDays.length > 0) {
        await api.routines.setSchedule(routineId, {
          days: editDays,
          time: editTime || '08:00',
          remind: editRemind,
        });
        setSchedule({ days: editDays, time: editTime || '08:00', remind: editRemind });
      } else if (schedule) {
        await api.routines.deleteSchedule(routineId);
        setSchedule(null);
      }
      setShowScheduleEditor(false);
    } catch (err) {
      console.error('Failed to save schedule:', err);
      alert('Failed to save schedule. Please try again.');
    }
  };

  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 handleMoveStep = async (stepId: string, direction: 'up' | 'down') => {
    const currentIndex = steps.findIndex(s => s.id === stepId);
    if (direction === 'up' && currentIndex === 0) return;
    if (direction === 'down' && currentIndex === steps.length - 1) return;
    
    const newSteps = [...steps];
    const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
    [newSteps[currentIndex], newSteps[targetIndex]] = [newSteps[targetIndex], newSteps[currentIndex]];
    newSteps.forEach((s, i) => s.position = i + 1);
    setSteps(newSteps);
    
    try {
      const stepIds = newSteps.map(s => s.id);
      await api.routines.reorderSteps(routineId, stepIds);
    } catch (err) {
      console.error('Failed to reorder steps:', err);
    }
  };

  const toggleDay = (day: string) => {
    setEditDays(prev =>
      prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day]
    );
  };

  const totalDuration = steps.reduce((acc, s) => acc + (s.duration_minutes || 0), 0);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  if (!routine) return null;

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-950">
      <header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-10">
        <div className="flex items-center justify-between px-4 py-3">
          <div className="flex items-center gap-3">
            <button onClick={() => router.back()} className="p-1 text-gray-600 dark:text-gray-400">
              <ArrowLeftIcon size={24} />
            </button>
            <h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">
              {isEditing ? 'Edit Routine' : routine.name}
            </h1>
          </div>
          {!isEditing && (
            <div className="flex items-center gap-2">
              <button
                onClick={() => {
                  if (confirm('Are you sure you want to delete this routine?')) {
                    setIsDeleting(true);
                    api.routines.delete(routineId).then(() => {
                      router.push('/dashboard/routines');
                    }).catch(err => {
                      console.error('Failed to delete routine:', err);
                      alert('Failed to delete routine');
                      setIsDeleting(false);
                    });
                  }
                }}
                disabled={isDeleting}
                className="text-red-500 dark:text-red-400 font-medium disabled:opacity-50"
              >
                {isDeleting ? 'Deleting...' : 'Delete'}
              </button>
              <button
                onClick={() => setIsEditing(true)}
                className="text-indigo-600 dark:text-indigo-400 font-medium"
              >
                Edit
              </button>
            </div>
          )}
        </div>
      </header>

      <div className="p-4 space-y-6">
        {isEditing ? (
          <>
            <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Icon</label>
                <div className="flex flex-wrap gap-2">
                  {ICONS.map((i) => (
                    <button
                      key={i}
                      type="button"
                      onClick={() => setEditIcon(i)}
                      className={`w-10 h-10 rounded-lg text-xl flex items-center justify-center transition ${
                        editIcon === i
                          ? 'bg-indigo-100 dark:bg-indigo-900/50 ring-2 ring-indigo-600'
                          : 'bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600'
                      }`}
                    >
                      {i}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Name</label>
                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(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 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500 outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Description</label>
                <input
                  type="text"
                  value={editDescription}
                  onChange={(e) => setEditDescription(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 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500 outline-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Location</label>
                <input
                  type="text"
                  value={editLocation}
                  onChange={(e) => 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 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"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Anchor habit</label>
                <input
                  type="text"
                  value={editHabitStack}
                  onChange={(e) => 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 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"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Environment prompts</label>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-2">Quick checklist shown before starting</p>
                <div className="space-y-2 mb-2">
                  {editEnvPrompts.map((prompt, i) => (
                    <div key={i} className="flex items-center gap-2">
                      <span className="flex-1 text-sm text-gray-700 dark:text-gray-300 bg-gray-50 dark:bg-gray-700 px-3 py-2 rounded-lg">{prompt}</span>
                      <button
                        onClick={() => setEditEnvPrompts(editEnvPrompts.filter((_, j) => j !== i))}
                        className="text-red-500 dark:text-red-400 text-sm px-2"
                      >
                        Remove
                      </button>
                    </div>
                  ))}
                </div>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={newEnvPrompt}
                    onChange={(e) => setNewEnvPrompt(e.target.value)}
                    placeholder="e.g., Water bottle nearby?"
                    className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm 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"
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && newEnvPrompt.trim()) {
                        setEditEnvPrompts([...editEnvPrompts, newEnvPrompt.trim()]);
                        setNewEnvPrompt('');
                      }
                    }}
                  />
                  <button
                    onClick={() => {
                      if (newEnvPrompt.trim()) {
                        setEditEnvPrompts([...editEnvPrompts, newEnvPrompt.trim()]);
                        setNewEnvPrompt('');
                      }
                    }}
                    className="px-3 py-2 bg-gray-200 dark:bg-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300"
                  >
                    Add
                  </button>
                </div>
              </div>
            </div>

            {/* Save/Cancel */}
            <div className="flex gap-3">
              <button
                onClick={() => {
                  setIsEditing(false);
                  setEditName(routine.name);
                  setEditDescription(routine.description || '');
                  setEditIcon(routine.icon || '✨');
                  setEditLocation(routine.location || '');
                  setEditHabitStack(routine.habit_stack_after || '');
                  setEditEnvPrompts(routine.environment_prompts || []);
                }}
                className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg font-medium text-gray-700 dark:text-gray-300"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveBasicInfo}
                className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg font-medium"
              >
                Save
              </button>
            </div>
          </>
        ) : (
          <>
            <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 bg-gradient-to-br from-indigo-100 to-pink-100 dark:from-indigo-900/50 dark:to-pink-900/50 rounded-2xl flex items-center justify-center">
                  <span className="text-4xl">{routine.icon || '✨'}</span>
                </div>
                <div className="flex-1">
                  <h2 className="text-xl font-bold text-gray-900 dark:text-gray-100">{routine.name}</h2>
                  {routine.description && (
                    <p className="text-gray-500 dark:text-gray-400">{routine.description}</p>
                  )}
                  <div className="flex items-center gap-4 mt-2 text-sm text-gray-500 dark:text-gray-400">
                    <span className="flex items-center gap-1">
                      <ClockIcon size={14} />
                      {totalDuration} min
                    </span>
                    <span>{steps.length} steps</span>
                  </div>
                </div>
              </div>
              <button
                onClick={handleStart}
                className="w-full mt-4 bg-gradient-to-r from-indigo-600 to-purple-600 text-white font-bold py-4 rounded-2xl flex items-center justify-center gap-2 text-lg shadow-lg shadow-indigo-500/25 active:scale-[0.98] transition-transform"
              >
                <PlayIcon size={24} />
                Start Routine
              </button>
            </div>

            {/* Schedule display (view mode) */}
            <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <ClockIcon size={16} className="text-indigo-500" />
                  <h3 className="font-semibold text-gray-900 dark:text-gray-100">Schedule</h3>
                </div>
                {!showScheduleEditor && (
                  <button
                    onClick={() => setShowScheduleEditor(true)}
                    className="text-indigo-600 dark:text-indigo-400 text-sm font-medium"
                  >
                    {schedule ? 'Edit' : 'Add schedule'}
                  </button>
                )}
              </div>
              
              {showScheduleEditor ? (
                <>
                  {/* Quick select */}
                  <div className="flex gap-2 mb-3">
                    <button
                      type="button"
                      onClick={() => setEditDays(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])}
                      className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
                        editDays.length === 7 ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600'
                      }`}
                    >
                      Every day
                    </button>
                    <button
                      type="button"
                      onClick={() => setEditDays(['mon', 'tue', 'wed', 'thu', 'fri'])}
                      className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
                        editDays.length === 5 && !editDays.includes('sat') && !editDays.includes('sun') ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600'
                      }`}
                    >
                      Weekdays
                    </button>
                    <button
                      type="button"
                      onClick={() => setEditDays(['sat', 'sun'])}
                      className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
                        editDays.length === 2 && editDays.includes('sat') && editDays.includes('sun') ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600'
                      }`}
                    >
                      Weekends
                    </button>
                  </div>
                  
                  <div className="mb-3">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Days</label>
                    <div className="flex gap-2 flex-wrap">
                      {DAY_OPTIONS.map((day) => (
                        <button
                          key={day.value}
                          type="button"
                          onClick={() => toggleDay(day.value)}
                          className={`px-3 py-2 rounded-lg text-sm font-medium border transition-colors ${
                              editDays.includes(day.value)
                                ? 'bg-indigo-600 text-white border-indigo-600'
                                : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600'
                          }`}
                        >
                          {day.label}
                        </button>
                      ))}
                    </div>
                  </div>
                  <div className="mb-3">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Time</label>
                    <input
                      type="time"
                      value={editTime}
                      onChange={(e) => setEditTime(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"
                    />
                  </div>
                  <div className="flex items-center justify-between mb-3">
                    <div>
                      <p className="font-medium text-gray-900 dark:text-gray-100">Send reminder</p>
                      <p className="text-sm text-gray-500 dark:text-gray-400">Get notified when it's time</p>
                    </div>
                    <button
                      onClick={() => setEditRemind(!editRemind)}
                      className={`w-12 h-7 rounded-full transition-colors ${
                        editRemind ? 'bg-indigo-500' : 'bg-gray-300 dark:bg-gray-600'
                      }`}
                    >
                      <div className={`w-5 h-5 bg-white rounded-full shadow transition-transform ml-1 ${
                        editRemind ? 'translate-x-5' : ''
                      }`} />
                    </button>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => {
                        setShowScheduleEditor(false);
                        if (schedule) {
                          setEditDays(schedule.days);
                          setEditTime(schedule.time);
                          setEditRemind(schedule.remind);
                        } else {
                          setEditDays(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']);
                          setEditTime('08:00');
                          setEditRemind(true);
                        }
                      }}
                      className="flex-1 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleSaveSchedule}
                      className="flex-1 px-3 py-2 bg-indigo-600 text-white rounded-lg text-sm font-medium"
                    >
                      Save Schedule
                    </button>
                  </div>
                </>
              ) : schedule && schedule.days.length > 0 ? (
                <>
                  <p className="text-gray-700 dark:text-gray-300">
                    {formatDays(schedule.days)} at {schedule.time}
                  </p>
                  {schedule.remind && (
                    <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Reminders on</p>
                  )}
                </>
              ) : (
                <p className="text-gray-500 dark:text-gray-400 text-sm">Not scheduled. Click "Add schedule" to set a time.</p>
              )}
            </div>
          </>
        )}

        {/* Steps */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Steps</h2>
            {steps.length >= 4 && steps.length <= 7 && (
              <span className="text-xs text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/30 px-2 py-1 rounded-full">Good length</span>
            )}
          </div>
          {steps.length > 7 && (
            <p className="text-sm text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/30 px-3 py-2 rounded-lg mb-3">
              Tip: Routines with 4-7 steps tend to feel more manageable. Consider combining related steps.
            </p>
          )}

          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm space-y-3 mb-4">
            <div className="flex gap-2">
              <input
                type="text"
                value={newStepName}
                onChange={(e) => setNewStepName(e.target.value)}
                placeholder="New step name"
                className="flex-1 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 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-indigo-500 outline-none"
              />
              <select
                value={newStepDuration}
                onChange={(e) => setNewStepDuration(Number(e.target.value))}
                className="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"
              >
                <option value={1}>1m</option>
                <option value={5}>5m</option>
                <option value={10}>10m</option>
                <option value={15}>15m</option>
                <option value={30}>30m</option>
              </select>
              <button
                onClick={handleAddStep}
                className="bg-indigo-600 text-white px-4 py-2 rounded-lg"
              >
                <PlusIcon size={20} />
              </button>
            </div>
          </div>

          {steps.length === 0 ? (
            <div className="bg-white dark:bg-gray-800 rounded-xl p-8 shadow-sm text-center">
              <p className="text-gray-500 dark:text-gray-400">No steps yet</p>
            </div>
          ) : (
            <div className="space-y-2">
              {steps.map((step, index) => (
                <div
                  key={step.id}
                  className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm flex items-center gap-3"
                >
                  <div className="w-8 h-8 bg-indigo-100 dark:bg-indigo-900/50 text-indigo-600 dark:text-indigo-400 rounded-full flex items-center justify-center font-semibold text-sm">
                    {index + 1}
                  </div>
                  <div className="flex-1">
                    <h3 className="font-medium text-gray-900 dark:text-gray-100">{step.name}</h3>
                    {step.duration_minutes && (
                      <p className="text-sm text-gray-500 dark:text-gray-400">{step.duration_minutes} min</p>
                    )}
                  </div>
                  <div className="flex flex-col">
                    <button
                      onClick={() => handleMoveStep(step.id, 'up')}
                      disabled={index === 0}
                      className="text-gray-400 dark:text-gray-500 p-1 disabled:opacity-30 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      ▲
                    </button>
                    <button
                      onClick={() => handleMoveStep(step.id, 'down')}
                      disabled={index === steps.length - 1}
                      className="text-gray-400 dark:text-gray-500 p-1 disabled:opacity-30 hover:text-gray-600 dark:hover:text-gray-300"
                    >
                      ▼
                    </button>
                  </div>
                  <button
                    onClick={() => handleDeleteStep(step.id)}
                    className="text-red-500 dark:text-red-400 p-2"
                  >
                    <TrashIcon size={18} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Bottom Save Button - shows when schedule editor is open */}
        {showScheduleEditor && !isEditing && (
          <div className="fixed bottom-4 left-4 right-4">
            <button
              onClick={handleSaveSchedule}
              className="w-full bg-indigo-600 text-white font-semibold py-4 rounded-xl shadow-lg shadow-indigo-500/25"
            >
              Save Schedule
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
