'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import api from '@/lib/api';
import { ArrowLeftIcon, PlusIcon, TrashIcon, GripVerticalIcon } 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' },
];

export default function NewRoutinePage() {
  const router = useRouter();
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [icon, setIcon] = useState('✨');
  const [steps, setSteps] = useState<Step[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  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<Step>) => {
    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 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,
        });
      }

      router.push('/dashboard/routines');
    } catch (err) {
      setError((err as Error).message || 'Failed to create routine');
    } finally {
      setIsLoading(false);
    }
  };

  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 gap-3 px-4 py-3">
          <button onClick={() => router.back()} className="p-1">
            <ArrowLeftIcon size={24} />
          </button>
          <h1 className="text-xl font-bold text-gray-900">New Routine</h1>
        </div>
      </header>

      <form onSubmit={handleSubmit} className="p-4 space-y-6">
        {error && (
          <div className="bg-red-50 text-red-600 px-4 py-3 rounded-lg text-sm">
            {error}
          </div>
        )}

        {/* Basic Info */}
        <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={() => setIcon(i)}
                  className={`w-10 h-10 rounded-lg text-xl flex items-center justify-center transition ${
                    icon === 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={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Morning Routine"
              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 (optional)</label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Start your day right"
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
            />
          </div>
        </div>

        {/* Steps */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-semibold text-gray-900">Steps</h2>
            <button
              type="button"
              onClick={handleAddStep}
              className="text-indigo-600 text-sm font-medium flex items-center gap-1"
            >
              <PlusIcon size={16} />
              Add Step
            </button>
          </div>

          {steps.length === 0 ? (
            <div className="bg-white rounded-xl p-8 shadow-sm text-center">
              <p className="text-gray-500 mb-4">Add steps to your routine</p>
              <button
                type="button"
                onClick={handleAddStep}
                className="text-indigo-600 font-medium"
              >
                + Add your first step
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {steps.map((step, index) => (
                <div
                  key={step.id}
                  className="bg-white rounded-xl p-4 shadow-sm flex items-start gap-3"
                >
                  <div className="pt-3 text-gray-400 cursor-grab">
                    <GripVerticalIcon size={20} />
                  </div>
                  <div className="flex-1 space-y-3">
                    <input
                      type="text"
                      value={step.name}
                      onChange={(e) => handleUpdateStep(index, { name: e.target.value })}
                      placeholder="Step name"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 outline-none"
                    />
                    <div className="flex items-center gap-3">
                      <label className="text-sm text-gray-500">Duration:</label>
                      <select
                        value={step.duration_minutes || 5}
                        onChange={(e) => handleUpdateStep(index, { duration_minutes: Number(e.target.value) })}
                        className="px-3 py-1 border border-gray-300 rounded-lg text-sm"
                      >
                        <option value={1}>1 min</option>
                        <option value={2}>2 min</option>
                        <option value={5}>5 min</option>
                        <option value={10}>10 min</option>
                        <option value={15}>15 min</option>
                        <option value={20}>20 min</option>
                        <option value={30}>30 min</option>
                        <option value={45}>45 min</option>
                        <option value={60}>60 min</option>
                      </select>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => handleDeleteStep(index)}
                    className="text-red-500 p-2"
                  >
                    <TrashIcon size={18} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        <button
          type="submit"
          disabled={isLoading}
          className="w-full bg-indigo-600 text-white font-semibold py-4 rounded-xl hover:bg-indigo-700 disabled:opacity-50"
        >
          {isLoading ? 'Creating...' : 'Create Routine'}
        </button>
      </form>
    </div>
  );
}
