'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<Routine | null>(null);
  const [steps, setSteps] = useState<Step[]>([]);
  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<string[]>([]);
  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 (
      <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">
      <header className="bg-white border-b border-gray-200 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">
              <ArrowLeftIcon size={24} />
            </button>
            <h1 className="text-xl font-bold text-gray-900">
              {isEditing ? 'Edit Routine' : routine.name}
            </h1>
          </div>
          {!isEditing && (
            <button
              onClick={() => setIsEditing(true)}
              className="text-indigo-600 font-medium"
            >
              Edit
            </button>
          )}
        </div>
      </header>

      <div className="p-4 space-y-6">
        {isEditing ? (
          <div className="bg-white rounded-xl p-4 shadow-sm space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 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 ring-2 ring-indigo-600' 
                        : 'bg-gray-100 hover:bg-gray-200'
                    }`}
                  >
                    {i}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 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 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 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 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 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 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 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 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Environment prompts</label>
              <p className="text-xs text-gray-500 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 bg-gray-50 px-3 py-2 rounded-lg">{prompt}</span>
                    <button
                      onClick={() => setEditEnvPrompts(editEnvPrompts.filter((_, j) => j !== i))}
                      className="text-red-500 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 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('');
                    }
                  }}
                />
                <button
                  onClick={() => {
                    if (newEnvPrompt.trim()) {
                      setEditEnvPrompts([...editEnvPrompts, newEnvPrompt.trim()]);
                      setNewEnvPrompt('');
                    }
                  }}
                  className="px-3 py-2 bg-gray-200 rounded-lg text-sm font-medium"
                >
                  Add
                </button>
              </div>
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => setIsEditing(false)}
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg font-medium"
              >
                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>
        ) : (
          <div className="bg-white 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 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">{routine.name}</h2>
                {routine.description && (
                  <p className="text-gray-500">{routine.description}</p>
                )}
                <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
                  <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>
        )}

        {/* Steps */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold text-gray-900">Steps</h2>
            {steps.length >= 4 && steps.length <= 7 && (
              <span className="text-xs text-green-600 bg-green-50 px-2 py-1 rounded-full">Good length</span>
            )}
          </div>
          {steps.length > 7 && (
            <p className="text-sm text-amber-600 bg-amber-50 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 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 rounded-lg 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 rounded-lg"
              >
                <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 rounded-xl p-8 shadow-sm text-center">
              <p className="text-gray-500">No steps yet</p>
            </div>
          ) : (
            <div className="space-y-2">
              {steps.map((step, index) => (
                <div
                  key={step.id}
                  className="bg-white rounded-xl p-4 shadow-sm flex items-center gap-3"
                >
                  <div className="w-8 h-8 bg-indigo-100 text-indigo-600 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">{step.name}</h3>
                    {step.duration_minutes && (
                      <p className="text-sm text-gray-500">{step.duration_minutes} min</p>
                    )}
                  </div>
                  <button
                    onClick={() => handleDeleteStep(step.id)}
                    className="text-red-500 p-2"
                  >
                    <TrashIcon size={18} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
