'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 } 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<Step[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  // Schedule
  const [scheduleDays, setScheduleDays] = useState<string[]>(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']);
  const [scheduleTime, setScheduleTime] = useState('08:00');
  const [scheduleRemind, setScheduleRemind] = useState(true);

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

      if (scheduleDays.length > 0) {
        await api.routines.setSchedule(routine.id, {
          days: scheduleDays,
          time: scheduleTime,
          remind: scheduleRemind,
        });
      }

      router.push(`/dashboard/routines/${routine.id}?new=1`);
    } catch (err) {
      setError((err as Error).message || 'Failed to create routine');
    } finally {
      setIsLoading(false);
    }
  };

  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 gap-3 px-4 py-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">New Routine</h1>
        </div>
      </header>

      <Link
        href="/dashboard/templates"
        className="mx-4 mt-4 flex items-center gap-3 bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/30 dark:to-purple-900/30 border-2 border-indigo-200 dark:border-indigo-800 rounded-xl p-4 hover:border-indigo-400 dark:hover:border-indigo-600 transition-colors"
      >
        <div className="w-12 h-12 bg-indigo-100 dark:bg-indigo-900/50 rounded-xl flex items-center justify-center flex-shrink-0">
          <CopyIcon size={24} className="text-indigo-600 dark:text-indigo-400" />
        </div>
        <div className="flex-1">
          <p className="font-semibold text-gray-900 dark:text-gray-100">Start from a template</p>
          <p className="text-sm text-gray-500 dark:text-gray-400">Browse pre-made routines</p>
        </div>
        <div className="bg-indigo-600 text-white text-xs font-medium px-2 py-1 rounded-full">
          Recommended
        </div>
      </Link>

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

        {/* Basic Info */}
        <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={() => setIcon(i)}
                  className={`w-10 h-10 rounded-lg text-xl flex items-center justify-center transition ${
                    icon === 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={name}
              onChange={(e) => 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"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 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 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>

        {/* Schedule */}
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm space-y-4">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Schedule <span className="text-sm font-normal text-gray-400">(optional)</span></h2>
          
          {/* Quick select buttons */}
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setScheduleDays(['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'])}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
                scheduleDays.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={() => setScheduleDays(['mon', 'tue', 'wed', 'thu', 'fri'])}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
                scheduleDays.length === 5 && !scheduleDays.includes('sat') && !scheduleDays.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={() => setScheduleDays(['sat', 'sun'])}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${
                scheduleDays.length === 2 && scheduleDays.includes('sat') && scheduleDays.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>
            <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 ${
                    scheduleDays.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>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Time</label>
            <input
              type="time"
              value={scheduleTime}
              onChange={(e) => 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"
            />
          </div>
          
          <div className="flex items-center justify-between">
            <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
              type="button"
              onClick={() => setScheduleRemind(!scheduleRemind)}
              className={`w-12 h-7 rounded-full transition-colors ${
                scheduleRemind ? '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 ${
                scheduleRemind ? 'translate-x-5' : ''
              }`} />
            </button>
          </div>
        </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>
            <button
              type="button"
              onClick={handleAddStep}
              className="text-indigo-600 dark:text-indigo-400 text-sm font-medium flex items-center gap-1"
            >
              <PlusIcon size={16} />
              Add Step
            </button>
          </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 mb-4">Add steps to your routine</p>
              <button
                type="button"
                onClick={handleAddStep}
                className="text-indigo-600 dark:text-indigo-400 font-medium"
              >
                + Add your first step
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {steps.map((step, index) => (
                <div
                  key={step.id}
                  className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm flex items-start gap-3"
                >
                  <div className="pt-3 text-gray-400 dark:text-gray-500 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 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 className="flex items-center gap-3">
                      <label className="text-sm text-gray-500 dark:text-gray-400">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 dark:border-gray-600 rounded-lg text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                      >
                        <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 dark:text-red-400 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>
  );
}
