'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<Step[]>([]);
  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<string[]>(['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<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 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 (
    <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>

          {/* Frequency selector */}
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setScheduleFrequency('weekly')}
              className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium border transition-colors ${
                scheduleFrequency === 'weekly' ? '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'
              }`}
            >
              Weekly
            </button>
            <button
              type="button"
              onClick={() => setScheduleFrequency('every_n_days')}
              className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium border transition-colors ${
                scheduleFrequency === 'every_n_days' ? '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 N Days
            </button>
          </div>

          {scheduleFrequency === 'every_n_days' ? (
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Repeat every</label>
                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    min={2}
                    max={365}
                    value={scheduleIntervalDays}
                    onChange={(e) => 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"
                  />
                  <span className="text-sm text-gray-600 dark:text-gray-400">days</span>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Starting from</label>
                <input
                  type="date"
                  value={scheduleStartDate}
                  onChange={(e) => 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"
                />
              </div>
            </div>
          ) : (
            <>
              {/* 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>
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => {
                  setShowAiInput(!showAiInput);
                  if (!showAiInput && !aiGoal) setAiGoal(name);
                  setAiError('');
                }}
                className="flex items-center gap-1 text-sm font-medium text-purple-600 dark:text-purple-400 hover:text-purple-700 dark:hover:text-purple-300 transition-colors"
              >
                <SparklesIcon size={16} />
                Generate with AI
              </button>
              <span className="text-gray-300 dark:text-gray-600">|</span>
              <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>
          </div>

          {/* AI Generation Panel */}
          {showAiInput && (
            <div className="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-xl p-4 mb-4 space-y-3">
              <p className="text-sm font-medium text-purple-800 dark:text-purple-300">
                Describe your goal and AI will suggest steps
              </p>
              <textarea
                value={aiGoal}
                onChange={(e) => setAiGoal(e.target.value)}
                placeholder="e.g. help me build a morning routine that starts slow"
                rows={2}
                disabled={isGenerating}
                className="w-full px-3 py-2 border border-purple-300 dark:border-purple-700 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-purple-500 outline-none text-sm resize-none disabled:opacity-50"
              />
              {aiError && (
                <p className="text-sm text-red-600 dark:text-red-400">{aiError}</p>
              )}
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={handleGenerateSteps}
                  disabled={isGenerating}
                  className="flex items-center gap-2 bg-purple-600 text-white text-sm font-medium px-4 py-2 rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
                >
                  {isGenerating ? (
                    <>
                      <div className="w-3 h-3 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      Generating...
                    </>
                  ) : (
                    <>
                      <SparklesIcon size={14} />
                      Generate Steps
                    </>
                  )}
                </button>
                <button
                  type="button"
                  onClick={() => { setShowAiInput(false); setAiError(''); }}
                  disabled={isGenerating}
                  className="text-sm text-gray-500 dark:text-gray-400 px-3 py-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 transition-colors"
                >
                  Cancel
                </button>
              </div>
            </div>
          )}

          {steps.length === 0 ? (
            <div className="bg-white dark:bg-gray-800 rounded-xl p-8 shadow-sm text-center space-y-4">
              <p className="text-gray-500 dark:text-gray-400">Add steps to your routine</p>
              <div className="flex flex-col sm:flex-row gap-2 justify-center">
                <button
                  type="button"
                  onClick={() => { setShowAiInput(true); if (!aiGoal) setAiGoal(name); }}
                  className="flex items-center justify-center gap-2 bg-purple-600 text-white text-sm font-medium px-4 py-2 rounded-lg hover:bg-purple-700 transition-colors"
                >
                  <SparklesIcon size={16} />
                  Generate with AI
                </button>
                <button
                  type="button"
                  onClick={handleAddStep}
                  className="flex items-center justify-center gap-2 text-indigo-600 dark:text-indigo-400 font-medium text-sm px-4 py-2 rounded-lg border border-indigo-200 dark:border-indigo-800 hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors"
                >
                  <PlusIcon size={16} />
                  Add manually
                </button>
              </div>
            </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>
  );
}
