'use client';

import { useEffect, useState, useCallback, useRef } from 'react';
import { useRouter, useParams } from 'next/navigation';
import api from '@/lib/api';
import { ArrowLeftIcon, PauseIcon, PlayIcon, StopIcon, SkipForwardIcon, CheckIcon, XIcon } from '@/components/ui/Icons';
import AnimatedCheckmark from '@/components/ui/AnimatedCheckmark';
import VisualTimeline from '@/components/session/VisualTimeline';
import { playStepComplete, playCelebration } from '@/lib/sounds';
import { hapticSuccess, hapticCelebration } from '@/lib/haptics';

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

interface Routine {
  id: string;
  name: string;
  icon?: string;
}

interface Session {
  id: string;
  routine_id: string;
  status: string;
  current_step_index: number;
}

interface CelebrationData {
  streak_current: number;
  streak_longest: number;
  session_duration_minutes: number;
  total_completions: number;
  steps_completed: number;
  steps_skipped: number;
}

export default function SessionRunnerPage() {
  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 [session, setSession] = useState<Session | null>(null);
  const [currentStep, setCurrentStep] = useState<Step | null>(null);
  const [currentStepIndex, setCurrentStepIndex] = useState(0);
  const [status, setStatus] = useState<'loading' | 'active' | 'paused' | 'completed'>('loading');

  const [timerSeconds, setTimerSeconds] = useState(0);
  const [isTimerRunning, setIsTimerRunning] = useState(false);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // UI states
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);

  // Animation states
  const [completionPhase, setCompletionPhase] = useState<'idle' | 'completing' | 'transitioning' | 'arriving'>('idle');
  const [skipPhase, setSkipPhase] = useState<'idle' | 'skipping' | 'transitioning' | 'arriving'>('idle');
  const [completedSteps, setCompletedSteps] = useState<Set<number>>(new Set());
  const [celebrationData, setCelebrationData] = useState<CelebrationData | null>(null);
  const [celebrationPhase, setCelebrationPhase] = useState(0);
  const [reward, setReward] = useState<{ content: string; emoji?: string; rarity: string } | null>(null);
  const [soundEnabled, setSoundEnabled] = useState(false);
  const [hapticEnabled, setHapticEnabled] = useState(true);

  const touchStartX = useRef<number | null>(null);
  const touchStartY = useRef<number | null>(null);

  // Fetch session data
  useEffect(() => {
    const fetchSession = async () => {
      try {
        const sessionData = await api.sessions.getActive();
        setSession(sessionData.session);
        setRoutine(sessionData.routine);
        setSteps(await api.routines.getSteps(sessionData.routine.id).then(s => s));
        setCurrentStep(sessionData.current_step);
        setCurrentStepIndex(sessionData.session.current_step_index);
        setStatus(sessionData.session.status === 'paused' ? 'paused' : 'active');
        if (sessionData.session.status !== 'paused') {
          setIsTimerRunning(true);
        }

        // Mark previous steps as completed
        const completed = new Set<number>();
        for (let i = 0; i < sessionData.session.current_step_index; i++) {
          completed.add(i);
        }
        setCompletedSteps(completed);

        if (sessionData.current_step?.duration_minutes) {
          setTimerSeconds(sessionData.current_step.duration_minutes * 60);
        }

        // Fetch user preferences for sound/haptics
        api.preferences.get().then((prefs: { sound_enabled?: boolean; haptic_enabled?: boolean }) => {
          if (prefs.sound_enabled !== undefined) setSoundEnabled(prefs.sound_enabled);
          if (prefs.haptic_enabled !== undefined) setHapticEnabled(prefs.haptic_enabled);
        }).catch(() => {});
      } catch (err) {
        router.push('/dashboard');
      }
    };
    fetchSession();
  }, [router]);

  // Timer logic
  useEffect(() => {
    if (isTimerRunning && timerSeconds > 0) {
      timerRef.current = setInterval(() => {
        setTimerSeconds(s => Math.max(0, s - 1));
      }, 1000);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [isTimerRunning]);

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Touch handlers for swipe
  const handleTouchStart = (e: React.TouchEvent) => {
    if (completionPhase !== 'idle' || skipPhase !== 'idle') return;
    touchStartX.current = e.touches[0].clientX;
    touchStartY.current = e.touches[0].clientY;
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (touchStartX.current === null || touchStartY.current === null) return;
    if (completionPhase !== 'idle' || skipPhase !== 'idle') return;

    const touchEndX = e.changedTouches[0].clientX;
    const touchEndY = e.changedTouches[0].clientY;
    const diffX = touchEndX - touchStartX.current;
    const diffY = touchEndY - touchStartY.current;

    if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
      if (diffX < 0) {
        handleComplete();
      } else {
        handleSkip();
      }
    }

    touchStartX.current = null;
    touchStartY.current = null;
  };

  const handleComplete = async () => {
    if (!session || !currentStep || completionPhase !== 'idle') return;

    // Auto-resume if paused
    if (status === 'paused') {
      setStatus('active');
      setIsTimerRunning(true);
    }

    // Phase 1: Instant green glow + pulse on complete button
    setCompletionPhase('completing');
    if (soundEnabled) playStepComplete();
    if (hapticEnabled) hapticSuccess();

    try {
      const result = await api.sessions.completeStep(session.id, currentStep.id);

      // Mark current step as completed for progress bar
      setCompletedSteps(prev => new Set([...prev, currentStepIndex]));

      // Phase 2: Slide out (after brief glow)
      setTimeout(() => {
        setCompletionPhase('transitioning');
      }, 150);

      // Phase 3: Bring in next step
      setTimeout(() => {
        if (result.next_step) {
          setCurrentStep(result.next_step);
          setCurrentStepIndex(result.session.current_step_index!);
          setTimerSeconds((result.next_step.duration_minutes || 5) * 60);
          setIsTimerRunning(true);
          setCompletionPhase('arriving');
        } else {
          setCelebrationData(result.celebration || null);
          setStatus('completed');
          setCompletionPhase('idle');
        }
      }, 400);

      // Phase 4: Back to idle
      setTimeout(() => {
        setCompletionPhase('idle');
      }, 700);
    } catch (err) {
      console.error('Failed to complete step:', err);
      setCompletionPhase('idle');
    }
  };

  const handleSkip = async () => {
    if (!session || !currentStep || skipPhase !== 'idle') return;

    // Auto-resume if paused
    if (status === 'paused') {
      setStatus('active');
      setIsTimerRunning(true);
    }

    setSkipPhase('skipping');

    try {
      const result = await api.sessions.skipStep(session.id, currentStep.id);

      setTimeout(() => {
        setSkipPhase('transitioning');
      }, 150);

      setTimeout(() => {
        if (result.next_step) {
          setCurrentStep(result.next_step);
          setCurrentStepIndex(result.session.current_step_index!);
          setTimerSeconds((result.next_step.duration_minutes || 5) * 60);
          setIsTimerRunning(true);
          setSkipPhase('arriving');
        } else {
          setCelebrationData(result.celebration || null);
          setStatus('completed');
          setSkipPhase('idle');
        }
      }, 400);

      setTimeout(() => {
        setSkipPhase('idle');
      }, 700);
    } catch (err) {
      console.error('Failed to skip step:', err);
      setSkipPhase('idle');
    }
  };

  const handlePause = async () => {
    if (!session) return;
    try {
      await api.sessions.pause(session.id);
      setStatus('paused');
      setIsTimerRunning(false);
    } catch (err) {
      console.error('Failed to pause:', err);
    }
  };

  const handleResume = async () => {
    if (!session) return;
    try {
      await api.sessions.resume(session.id);
      setStatus('active');
      setIsTimerRunning(true);
    } catch (err) {
      console.error('Failed to resume:', err);
    }
  };

  const handleCancelRequest = () => {
    setShowCancelConfirm(true);
  };

  const handleCancelConfirm = async () => {
    if (!session) return;
    try {
      await api.sessions.cancel(session.id);
      router.push('/dashboard');
    } catch (err) {
      console.error('Failed to cancel:', err);
    }
  };

  // Celebration phase sequencing + reward fetch
  useEffect(() => {
    if (status !== 'completed') return;
    setCelebrationPhase(0);

    // Play celebration feedback
    if (soundEnabled) playCelebration();
    if (hapticEnabled) hapticCelebration();

    // Fetch random reward
    api.rewards.getRandom('completion').then(data => {
      if (data.reward) setReward(data.reward);
    }).catch(() => {});

    const timers = [
      setTimeout(() => setCelebrationPhase(1), 100),   // bg gradient
      setTimeout(() => setCelebrationPhase(2), 400),   // checkmark
      setTimeout(() => setCelebrationPhase(3), 900),   // message
      setTimeout(() => setCelebrationPhase(4), 1300),  // stats + reward
      setTimeout(() => setCelebrationPhase(5), 1700),  // done button
    ];
    return () => timers.forEach(clearTimeout);
  }, [status]);

  if (status === 'loading' || !currentStep) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-950">
        <div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  // ── Celebration Screen ──────────────────────────────────────
  if (status === 'completed') {
    const formatDuration = (mins: number) => {
      if (mins < 1) return 'less than a minute';
      if (mins < 60) return `${Math.round(mins)} minute${Math.round(mins) !== 1 ? 's' : ''}`;
      const h = Math.floor(mins / 60);
      const m = Math.round(mins % 60);
      return m > 0 ? `${h}h ${m}m` : `${h}h`;
    };

    const streakMessage = (streak: number) => {
      if (streak <= 1) return "You showed up today";
      if (streak <= 3) return `${streak} days and counting`;
      if (streak <= 7) return `${streak} days — you're building something real`;
      return `${streak} days — you're someone who shows up`;
    };

    return (
      <div className={`min-h-screen flex flex-col items-center justify-center p-6 transition-all duration-500 ${
        celebrationPhase >= 1
          ? 'bg-gradient-to-br from-indigo-500 via-purple-500 to-pink-500'
          : 'bg-gray-950'
      }`}>
        {/* Animated Checkmark */}
        <div className={`mb-8 ${celebrationPhase >= 2 ? 'animate-celebration-scale' : 'opacity-0'}`}>
          <div className="w-28 h-28 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center">
            {celebrationPhase >= 2 && (
              <AnimatedCheckmark size={64} color="#ffffff" strokeWidth={2.5} />
            )}
          </div>
        </div>

        {/* Message */}
        <div className={`text-center mb-8 ${celebrationPhase >= 3 ? 'animate-fade-in-up' : 'opacity-0'}`}>
          <h1 className="text-3xl font-bold text-white mb-2">
            {routine?.name || 'Routine'} complete
          </h1>
          <p className="text-white/80 text-lg">You showed up for yourself</p>
        </div>

        {/* Stats */}
        {celebrationData && (
          <div className={`w-full max-w-sm space-y-3 mb-10 ${celebrationPhase >= 4 ? 'animate-fade-in-up' : 'opacity-0'}`}
               style={{ animationDelay: '100ms' }}>
            {/* Streak */}
            <div className="bg-white/15 backdrop-blur-sm rounded-2xl p-4 text-center">
              <p className="text-white/60 text-sm mb-1">Your streak</p>
              <p className="text-white text-xl font-semibold">
                {streakMessage(celebrationData.streak_current)}
              </p>
            </div>

            {/* Duration + Steps */}
            <div className="flex gap-3">
              <div className="flex-1 bg-white/15 backdrop-blur-sm rounded-2xl p-4 text-center">
                <p className="text-white/60 text-sm mb-1">Time</p>
                <p className="text-white text-lg font-semibold">
                  {formatDuration(celebrationData.session_duration_minutes)}
                </p>
              </div>
              <div className="flex-1 bg-white/15 backdrop-blur-sm rounded-2xl p-4 text-center">
                <p className="text-white/60 text-sm mb-1">Steps done</p>
                <p className="text-white text-lg font-semibold">
                  {celebrationData.steps_completed}/{celebrationData.steps_completed + celebrationData.steps_skipped}
                </p>
              </div>
            </div>

            {/* Total completions */}
            {celebrationData.total_completions > 1 && (
              <p className="text-white/50 text-sm text-center">
                That&apos;s {celebrationData.total_completions} total completions
              </p>
            )}

            {/* Variable Reward */}
            {reward && (
              <div className={`bg-white/10 backdrop-blur-sm rounded-2xl p-4 text-center border ${
                reward.rarity === 'rare' ? 'border-yellow-400/50' : 'border-white/10'
              }`}>
                <span className="text-2xl">{reward.emoji || '✨'}</span>
                <p className="text-white text-sm mt-1">{reward.content}</p>
              </div>
            )}
          </div>
        )}

        {/* Done button */}
        <button
          onClick={() => router.push('/dashboard')}
          className={`bg-white text-indigo-600 px-10 py-3.5 rounded-full font-semibold text-lg shadow-lg ${
            celebrationPhase >= 5 ? 'animate-fade-in-up' : 'opacity-0'
          }`}
        >
          Done
        </button>
      </div>
    );
  }

  // ── Active Session ──────────────────────────────────────────

  // Card animation class
  const getCardAnimation = () => {
    if (completionPhase === 'completing') return 'animate-green-glow';
    if (completionPhase === 'transitioning') return 'animate-slide-out-left';
    if (completionPhase === 'arriving') return 'animate-slide-in-right';
    if (skipPhase === 'skipping') return '';
    if (skipPhase === 'transitioning') return 'animate-slide-out-right';
    if (skipPhase === 'arriving') return 'animate-slide-in-right';
    return '';
  };

  return (
    <div
      className="min-h-screen bg-gray-950 text-white flex flex-col"
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      {/* Header */}
      <header className="flex items-center justify-between px-4 py-4">
        <button onClick={handleCancelRequest} className="p-2">
          <XIcon size={24} />
        </button>
        <div className="text-center">
          <p className="text-white/40 text-xs tracking-wide uppercase mb-0.5">Focus Mode</p>
          <p className="text-white/60 text-sm">{routine?.name}</p>
          <p className="font-semibold">Step {currentStepIndex + 1} of {steps.length}</p>
        </div>
        <button onClick={status === 'paused' ? handleResume : handlePause} className="p-2">
          {status === 'paused' ? <PlayIcon size={24} /> : <PauseIcon size={24} />}
        </button>
      </header>

      {/* Segmented Progress Bar */}
      <div className="px-4 pb-2">
        <div className="flex gap-1">
          {steps.map((_, i) => (
            <div key={i} className="flex-1 h-2 rounded-full overflow-hidden bg-gray-800">
              <div
                className={`h-full rounded-full transition-all duration-500 ${
                  completedSteps.has(i)
                    ? 'bg-indigo-500 w-full'
                    : i === currentStepIndex
                    ? 'bg-indigo-400 w-full animate-gentle-pulse'
                    : 'w-0'
                }`}
              />
            </div>
          ))}
        </div>
      </div>

      {/* Visual Timeline — collapsible step overview */}
      <VisualTimeline
        steps={steps}
        currentStepIndex={currentStepIndex}
        completedSteps={completedSteps}
      />

      {/* Main Card */}
      <div className="flex-1 flex flex-col items-center justify-center p-6">
        <div
          className={`
            w-full max-w-md bg-gray-800 rounded-3xl p-8 text-center
            shadow-2xl shadow-indigo-500/10
            ${getCardAnimation()}
          `}
        >
          {/* Timer */}
          <div className="mb-6">
            <div className="text-7xl font-bold font-mono mb-2" style={{ textShadow: '0 0 20px rgba(99, 102, 241, 0.3)' }}>
              {formatTime(timerSeconds)}
            </div>
            <p className="text-white/60">remaining</p>
          </div>

          {/* Step Name */}
          <h2 className="text-3xl font-bold mb-4">{currentStep.name}</h2>

          {/* Instructions */}
          {currentStep.instructions && (
            <p className="text-white/80 text-lg mb-6">{currentStep.instructions}</p>
          )}

        </div>
      </div>

      {/* Action Buttons — pinned to bottom for one-handed use */}
      <div className="px-6 pb-8 pt-4">
        <div className="flex justify-center items-center gap-6">
          <button
            onClick={handleSkip}
            disabled={skipPhase !== 'idle' || completionPhase !== 'idle'}
            className="w-16 h-16 bg-gray-700 rounded-full flex items-center justify-center hover:bg-gray-600 transition disabled:opacity-50"
          >
            <SkipForwardIcon size={28} />
          </button>
          <button
            onClick={status === 'paused' ? handleResume : handlePause}
            className="w-20 h-20 bg-indigo-600 rounded-full flex items-center justify-center hover:bg-indigo-500 transition"
          >
            {status === 'paused' ? <PlayIcon size={32} /> : <PauseIcon size={32} />}
          </button>
          <button
            onClick={handleComplete}
            disabled={completionPhase !== 'idle' || skipPhase !== 'idle'}
            className={`w-16 h-16 rounded-full flex items-center justify-center transition disabled:opacity-50 ${
              completionPhase === 'completing'
                ? 'bg-green-500 animate-step-complete'
                : 'bg-green-600 hover:bg-green-500'
            }`}
          >
            <CheckIcon size={28} />
          </button>
        </div>
        {/* Swipe Hints */}
        <div className="flex justify-between mt-4 text-white/30 text-xs">
          <span>Swipe left to complete</span>
          <span>Swipe right to skip</span>
        </div>
      </div>

      {/* Gentle Cancel Confirmation */}
      {showCancelConfirm && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-6">
          <div className="bg-gray-800 rounded-2xl p-6 max-w-sm w-full text-center">
            <p className="text-white text-lg font-semibold mb-2">Step away for now?</p>
            <p className="text-white/60 text-sm mb-6">You can always come back. Your progress today still counts.</p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowCancelConfirm(false)}
                className="flex-1 py-3 bg-indigo-600 text-white rounded-xl font-medium"
              >
                Keep Going
              </button>
              <button
                onClick={handleCancelConfirm}
                className="flex-1 py-3 bg-gray-700 text-white/70 rounded-xl font-medium"
              >
                Leave
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
