'use client';

import { useEffect, useState } from 'react';
import { useRouter, useParams } from 'next/navigation';
import api from '@/lib/api';
import { ArrowLeftIcon, PlayIcon, CheckIcon, ClockIcon } from '@/components/ui/Icons';

interface Routine {
  id: string;
  name: string;
  description?: string;
  icon?: string;
  location?: string;
  environment_prompts?: string[];
  habit_stack_after?: string;
}

interface Step {
  id: string;
  name: string;
  duration_minutes?: number;
}

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

const EMOTION_OPTIONS = [
  { emoji: '💪', label: 'Accomplished' },
  { emoji: '😌', label: 'Relieved' },
  { emoji: '🌟', label: 'Proud' },
  { emoji: '😊', label: 'Good' },
];

export default function LaunchScreen() {
  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 [schedule, setSchedule] = useState<Schedule | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isStarting, setIsStarting] = useState(false);
  const [selectedEmotion, setSelectedEmotion] = useState<string | null>(null);
  const [environmentChecked, setEnvironmentChecked] = useState<Set<number>>(new Set());

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [routineData, scheduleData] = await Promise.all([
          api.routines.get(routineId),
          api.routines.getSchedule(routineId).catch(() => null),
        ]);
        setRoutine(routineData.routine as Routine);
        setSteps(routineData.steps);
        setSchedule(scheduleData);
      } catch (err) {
        console.error('Failed to load routine:', err);
        router.push('/dashboard');
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, [routineId, router]);

  const handleStart = async () => {
    setIsStarting(true);
    try {
      await api.sessions.start(routineId);
      router.push(`/dashboard/routines/${routineId}/run`);
    } catch (err) {
      const msg = (err as Error).message;
      if (msg.includes('already have active session')) {
        router.push(`/dashboard/routines/${routineId}/run`);
      } else {
        console.error('Failed to start:', err);
        setIsStarting(false);
      }
    }
  };

  const toggleEnvironmentCheck = (index: number) => {
    setEnvironmentChecked(prev => {
      const next = new Set(prev);
      if (next.has(index)) next.delete(index);
      else next.add(index);
      return next;
    });
  };

  const totalDuration = steps.reduce((acc, s) => acc + (s.duration_minutes || 0), 0);
  const envPrompts = routine?.environment_prompts || [];

  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 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">Ready to start</h1>
        </div>
      </header>

      <div className="p-4 space-y-6">
        {/* Routine info */}
        <div className="text-center py-4">
          <div className="w-20 h-20 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 mx-auto mb-3">
            <span className="text-5xl">{routine.icon || '✨'}</span>
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">{routine.name}</h2>
          <div className="flex items-center justify-center gap-2 text-gray-500 dark:text-gray-400 mt-2">
            <ClockIcon size={16} />
            <span>~{totalDuration} minutes</span>
            <span>·</span>
            <span>{steps.length} steps</span>
          </div>
        </div>

        {/* Implementation Intention */}
        {(routine.habit_stack_after || schedule) && (
          <div className="bg-indigo-50 dark:bg-indigo-900/30 border border-indigo-200 dark:border-indigo-800 rounded-2xl p-4">
            {routine.habit_stack_after && (
              <p className="text-indigo-800 dark:text-indigo-200 text-sm mb-2">
                After <span className="font-semibold">{routine.habit_stack_after}</span>, I will start{' '}
                <span className="font-semibold">{routine.name}</span>
              </p>
            )}
            {schedule && (
              <p className="text-indigo-700 dark:text-indigo-300 text-sm">
                {schedule.days.length > 0 && (
                  <span className="font-semibold">
                    {schedule.days.length === 7 ? 'Every day' :
                     schedule.days.length === 5 && ['mon','tue','wed','thu','fri'].every(d => schedule.days.includes(d)) ? 'Weekdays' :
                     schedule.days.map(d => d.charAt(0).toUpperCase() + d.slice(1)).join(', ')}
                  </span>
                )}
                {schedule.time && (
                  <>{schedule.days.length > 0 ? ' at ' : 'At '}<span className="font-semibold">{schedule.time}</span></>
                )}
                {routine.location && (
                  <> in <span className="font-semibold">{routine.location}</span></>
                )}
              </p>
            )}
          </div>
        )}

        {/* Environment Check */}
        {envPrompts.length > 0 && (
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
            <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-3">Quick check</h3>
            <div className="space-y-2">
              {envPrompts.map((prompt, i) => (
                <button
                  key={i}
                  onClick={() => toggleEnvironmentCheck(i)}
                  className={`w-full flex items-center gap-3 p-3 rounded-xl transition ${
                    environmentChecked.has(i)
                      ? 'bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800'
                      : 'bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600'
                  }`}
                >
                  <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center ${
                    environmentChecked.has(i)
                      ? 'border-green-500 bg-green-500'
                      : 'border-gray-300 dark:border-gray-500'
                  }`}>
                    {environmentChecked.has(i) && <CheckIcon size={14} className="text-white" />}
                  </div>
                  <span className={`text-sm ${environmentChecked.has(i) ? 'text-green-800 dark:text-green-200' : 'text-gray-700 dark:text-gray-300'}`}>
                    {prompt}
                  </span>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Emotion Bridge */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 shadow-sm">
          <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-1">
            When you finish in ~{totalDuration} minutes, how will you feel?
          </h3>
          <p className="text-gray-500 dark:text-gray-400 text-sm mb-3">You <em>get to</em> do this</p>
          <div className="grid grid-cols-2 gap-2">
            {EMOTION_OPTIONS.map((option) => (
              <button
                key={option.label}
                onClick={() => setSelectedEmotion(option.label)}
                className={`flex items-center gap-2 p-3 rounded-xl border transition ${
                  selectedEmotion === option.label
                    ? 'border-indigo-500 bg-indigo-50 dark:bg-indigo-900/30'
                    : 'border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500'
                }`}
              >
                <span className="text-xl">{option.emoji}</span>
                <span className="text-sm font-medium text-gray-900 dark:text-gray-100">{option.label}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Start Button */}
        <button
          onClick={handleStart}
          disabled={isStarting}
          className="w-full bg-indigo-600 text-white font-semibold py-4 rounded-2xl flex items-center justify-center gap-2 text-lg disabled:opacity-50 shadow-lg shadow-indigo-500/25"
        >
          {isStarting ? (
            <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
          ) : (
            <>
              <PlayIcon size={24} />
              Let&apos;s Go
            </>
          )}
        </button>
      </div>
    </div>
  );
}
