/**
 * Tabata Player Screen
 * Handles multi-block tabata sessions with warmup, blocks, inter-block rest, cooldown
 */

import React, { useRef, useEffect, useCallback, useState } from 'react'
import {
  View, Text, StyleSheet, Pressable, Animated, StatusBar,
} from 'react-native'
import { useRouter } from 'expo-router'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useKeepAwake } from 'expo-keep-awake'

import { useTabataTimer } from '@/src/shared/hooks/useTabataTimer'
import { useHaptics } from '@/src/shared/hooks/useHaptics'
import { useAudio } from '@/src/shared/hooks/useAudio'
import { useMusicPlayer } from '@/src/shared/hooks/useMusicPlayer'
import { useActivityStore } from '@/src/shared/stores'
import { useTabataProgramStore } from '@/src/shared/stores/tabataProgramStore'
import { useWorkoutProgramStore } from '@/src/shared/stores/workoutProgramStore'
import { getSessionProgramId } from '@/src/shared/services/access'
import { track } from '@/src/shared/services/analytics'
import type { TabataSession } from '@/src/shared/types/program'
import { PHASE_COLORS, darkColors } from '@/src/shared/theme'
import { TYPOGRAPHY, FONT_FAMILY } from '@/src/shared/constants/typography'
import { SPACING } from '@/src/shared/constants/spacing'
import { RADIUS } from '@/src/shared/constants/borderRadius'
import { GREEN, NAVY, BORDER_COLORS, TEXT, PHASE, AMBER } from '@/src/shared/constants/colors'
import { Icon } from '@/src/shared/components/Icon'

import { TimerRing, PhaseIndicator, RoundIndicator, PlayerControls, StatsOverlay, CoachEncouragement, NowPlaying } from '@/src/features/player'
import { TabataTip } from '@/src/features/player/components/TabataTip'
import { BlockIndicator } from '@/src/features/player/components/BlockIndicator'
import { WarmupOverlay } from '@/src/features/player/components/WarmupOverlay'

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

const TABATA_PHASE_COLORS: Record<string, string> = {
  WARMUP: PHASE.PREP,
  WORK: PHASE.WORK,
  REST: PHASE.REST,
  INTER_BLOCK_REST: AMBER[500],
  COOLDOWN: GREEN[500],
  COMPLETE: GREEN[500],
}

interface TabataPlayerScreenProps {
  session: TabataSession
}

export function TabataPlayerScreen({ session }: TabataPlayerScreenProps) {
  useKeepAwake()
  const router = useRouter()
  const insets = useSafeAreaInsets()
  const haptics = useHaptics()
  const audio = useAudio()
  const addWorkoutResult = useActivityStore(s => s.addWorkoutResult)
  const completeSession = useTabataProgramStore(s => s.completeSession)
  const completeProgram = useWorkoutProgramStore(s => s.completeProgram)

  const timer = useTabataTimer(session)
  const music = useMusicPlayer({
    vibe: session.musicVibe ?? 'electronic',
    isPlaying: timer.isRunning && !timer.isPaused && timer.phase !== 'WARMUP',
  })
  const [showControls, setShowControls] = useState(true)
  const timerScaleAnim = useRef(new Animated.Value(0.8)).current

  const phaseColor = TABATA_PHASE_COLORS[timer.phase] ?? PHASE.WORK

  // ─── Actions ─────────────────────────────────────────────────

  const startTimer = useCallback(() => {
    timer.start()
    haptics.buttonTap()
    track('tabata_session_started', { session_id: session.id, blocks: session.blocks.length })
  }, [timer, haptics, session])

  const togglePause = useCallback(() => {
    if (timer.isPaused) {
      timer.resume()
      track('tabata_session_resumed', { session_id: session.id })
    } else {
      timer.pause()
      track('tabata_session_paused', { session_id: session.id })
    }
    haptics.selection()
  }, [timer, haptics, session])

  const stopWorkout = useCallback(() => {
    haptics.phaseChange()
    timer.stop()
    router.back()
  }, [router, timer, haptics])

  const completeWorkout = useCallback(() => {
    haptics.workoutComplete()
    track('tabata_session_completed', {
      session_id: session.id,
      calories: timer.calories,
      total_rounds: timer.totalRounds,
      blocks: timer.totalBlocks,
    })
    addWorkoutResult({
      id: Date.now().toString(),
      workoutId: session.id,
      completedAt: Date.now(),
      calories: timer.calories,
      durationMinutes: session.totalDuration,
      rounds: timer.totalRounds,
      completionRate: 1,
    })
    // Mark session complete in program store
    if (session.id.startsWith('wp-')) {
      const programId = session.id.slice(3)
      completeProgram(programId)
    } else {
      const programId = getSessionProgramId(session.id)
      if (programId) {
        completeSession(programId, session.id)
      }
    }
    router.replace(`/complete/${session.id}`)
  }, [router, session, timer, haptics, addWorkoutResult, completeSession, completeProgram])

  const handleSkip = useCallback(() => {
    timer.skip()
    haptics.selection()
  }, [timer, haptics])

  // ─── Animations & side-effects ───────────────────────────────

  useEffect(() => {
    Animated.spring(timerScaleAnim, {
      toValue: 1, friction: 6, tension: 100, useNativeDriver: true,
    }).start()
  }, [])

  useEffect(() => {
    timerScaleAnim.setValue(0.9)
    Animated.spring(timerScaleAnim, {
      toValue: 1, friction: 4, tension: 150, useNativeDriver: true,
    }).start()
    haptics.phaseChange()
    if (timer.phase === 'COMPLETE') {
      audio.workoutComplete()
    } else if (timer.isRunning) {
      audio.phaseStart()
    }
  }, [timer.phase])

  useEffect(() => {
    if (timer.isRunning && timer.timeRemaining <= 3 && timer.timeRemaining > 0) {
      audio.countdownBeep()
      haptics.countdownTick()
    }
  }, [timer.timeRemaining])

  // ─── Render ──────────────────────────────────────────────────

  const isWarmup = timer.phase === 'WARMUP'
  const isCooldown = timer.phase === 'COOLDOWN'
  const isInterBlockRest = timer.phase === 'INTER_BLOCK_REST'
  const isBlockPhase = timer.phase === 'WORK' || timer.phase === 'REST'

  return (
    <View style={styles.container}>
      <StatusBar hidden />
      <View style={[styles.phaseBg, { backgroundColor: phaseColor }]} />

      <Pressable style={styles.content} onPress={() => setShowControls(s => !s)}>
        {/* Header */}
        {showControls && (
          <View style={[styles.header, { paddingTop: insets.top + SPACING[4] }]}>
            <Pressable onPress={stopWorkout} style={styles.closeBtn}>
              <View style={StyleSheet.absoluteFill} />
              <Icon name="xmark" size={24} tintColor={TEXT.PRIMARY} />
            </Pressable>
            <View style={styles.headerCenter}>
              <Text style={styles.title}>{session.title}</Text>
              <Text style={styles.subtitle}>Semaine {session.week} · Séance {session.order}</Text>
            </View>
            <View style={styles.closeBtn} />
          </View>
        )}

        {/* Stats overlay */}
        {showControls && timer.isRunning && !timer.isComplete && !isWarmup && !isCooldown && (
          <View style={styles.statsContainer}>
            <StatsOverlay
              calories={timer.calories}
              heartRate={null}
              elapsedRounds={timer.currentRound - 1}
              totalRounds={timer.totalRounds}
            />
          </View>
        )}

        {/* Warmup/Cooldown overlay */}
        {(isWarmup || isCooldown) && timer.currentWarmupMovement && (
          <WarmupOverlay
            movementName={isWarmup ? timer.currentWarmupMovement.name : (timer.currentCooldownMovement?.name ?? '')}
            movementIndex={isWarmup ? (timer as ReturnType<typeof useTabataTimer>).currentBlockIndex : 0}
            totalMovements={isWarmup ? session.warmup.movements.length : session.cooldown.movements.length}
            timeRemaining={timer.timeRemaining}
            isCooldown={isCooldown}
          />
        )}

        {/* Inter-block rest */}
        {isInterBlockRest && (
          <View style={styles.interBlockContainer}>
            <Text style={styles.interBlockLabel}>RÉCUPÉRATION</Text>
            <Text style={styles.interBlockTime}>{formatTime(timer.timeRemaining)}</Text>
            <BlockIndicator
              currentBlock={timer.currentBlockIndex}
              totalBlocks={timer.totalBlocks}
            />
            <Text style={styles.interBlockNext}>
              Prochain: Bloc {timer.currentBlockIndex + 1}
            </Text>
          </View>
        )}

        {/* Main timer ring for WORK/REST phases */}
        {isBlockPhase && (
          <>
            <BlockIndicator
              currentBlock={timer.currentBlockIndex}
              totalBlocks={timer.totalBlocks}
            />
            <Animated.View style={[styles.timerContainer, { transform: [{ scale: timerScaleAnim }] }]}>
              <TimerRing progress={timer.progress} phase={timer.phase === 'WORK' ? 'WORK' : 'REST'} />
              <View style={styles.timerInner}>
                <PhaseIndicator phase={timer.phase === 'WORK' ? 'WORK' : 'REST'} />
                <Text selectable style={styles.timerTime}>{formatTime(timer.timeRemaining)}</Text>
                <RoundIndicator current={timer.currentRound} total={session.blocks[timer.currentBlockIndex]?.rounds ?? 8} />
              </View>
            </Animated.View>

            {/* Exercise + tabata tip */}
            <Text style={styles.exerciseName}>{timer.currentExercise?.name}</Text>
            <TabataTip tip={timer.currentConseil} visible={timer.phase === 'WORK'} />

            <CoachEncouragement
              phase={timer.phase === 'WORK' ? 'WORK' : 'REST'}
              currentRound={timer.currentRound}
              totalRounds={timer.totalRounds}
            />
          </>
        )}

        {/* Complete state */}
        {timer.isComplete && (
          <View style={styles.completeSection}>
            <Text style={styles.completeTitle}>Séance terminée !</Text>
            <Text style={[styles.completeSubtitle, { color: GREEN[500] }]}>Excellent travail</Text>
            <View style={styles.completeStats}>
              <View style={styles.completeStat}>
                <Text selectable style={styles.completeStatValue}>{timer.totalBlocks}</Text>
                <Text style={styles.completeStatLabel}>Blocs</Text>
              </View>
              <View style={styles.completeStat}>
                <Text selectable style={styles.completeStatValue}>{timer.totalRounds}</Text>
                <Text style={styles.completeStatLabel}>Rounds</Text>
              </View>
              <View style={styles.completeStat}>
                <Text selectable style={styles.completeStatValue}>{timer.calories}</Text>
                <Text style={styles.completeStatLabel}>Calories</Text>
              </View>
            </View>
          </View>
        )}

        {/* Now Playing music pill */}
        {showControls && timer.isRunning && !timer.isComplete && (
          <View style={[styles.nowPlayingContainer, { bottom: insets.bottom + 100 }]}>
            <NowPlaying
              track={music.currentTrack}
              isReady={music.isReady}
              onSkipTrack={music.nextTrack}
            />
          </View>
        )}

        {/* Controls */}
        {showControls && !timer.isComplete && (
          <View style={[styles.controls, { paddingBottom: insets.bottom + SPACING[6] }]}>
            <PlayerControls
              isRunning={timer.isRunning}
              isPaused={timer.isPaused}
              onStart={startTimer}
              onPause={() => { timer.pause(); haptics.selection() }}
              onResume={() => { timer.resume(); haptics.selection() }}
              onStop={stopWorkout}
              onSkip={handleSkip}
            />
          </View>
        )}

        {/* Complete CTA */}
        {timer.isComplete && (
          <View style={[styles.controls, { paddingBottom: insets.bottom + SPACING[6] }]}>
            <Pressable style={styles.doneButton} onPress={completeWorkout}>
              <Text style={styles.doneButtonText}>Terminé</Text>
            </Pressable>
          </View>
        )}
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: NAVY[900] },
  phaseBg: { ...StyleSheet.absoluteFillObject, opacity: 0.15 },
  content: { flex: 1 },

  header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: SPACING[4] },
  closeBtn: { width: 44, height: 44, borderRadius: RADIUS.FULL, alignItems: 'center', justifyContent: 'center', overflow: 'hidden', borderWidth: 1, borderColor: BORDER_COLORS.DIM, backgroundColor: NAVY[800] },
  headerCenter: { alignItems: 'center' },
  title: { ...TYPOGRAPHY.HEADLINE, color: TEXT.PRIMARY },
  subtitle: { ...TYPOGRAPHY.CAPTION_1, color: TEXT.TERTIARY },

  statsContainer: { marginTop: SPACING[4], marginHorizontal: SPACING[4] },

  timerContainer: { alignItems: 'center', justifyContent: 'center', marginTop: SPACING[6] },
  timerInner: { position: 'absolute', alignItems: 'center' },
  timerTime: { ...TYPOGRAPHY.TIMER_NUMBER, color: TEXT.PRIMARY, fontVariant: ['tabular-nums'] },

  exerciseName: { ...TYPOGRAPHY.TITLE_2, color: TEXT.PRIMARY, textAlign: 'center', marginTop: SPACING[4], marginHorizontal: SPACING[4] },

  interBlockContainer: { alignItems: 'center', justifyContent: 'center', flex: 1 },
  interBlockLabel: { ...TYPOGRAPHY.FOOTNOTE, fontFamily: FONT_FAMILY.SANS_BOLD, letterSpacing: 2, color: AMBER[500], marginBottom: SPACING[2] },
  interBlockTime: { ...TYPOGRAPHY.TIMER_NUMBER, color: TEXT.PRIMARY, fontVariant: ['tabular-nums'] },
  interBlockNext: { ...TYPOGRAPHY.CAPTION_1, color: TEXT.TERTIARY, marginTop: SPACING[3] },

  controls: { position: 'absolute', bottom: 0, left: 0, right: 0, alignItems: 'center' },
  nowPlayingContainer: { position: 'absolute', left: SPACING[6], right: SPACING[6] },

  completeSection: { alignItems: 'center', marginTop: SPACING[8] },
  completeTitle: { ...TYPOGRAPHY.LARGE_TITLE, color: TEXT.PRIMARY },
  completeSubtitle: { ...TYPOGRAPHY.TITLE_3, marginTop: SPACING[1] },
  completeStats: { flexDirection: 'row', marginTop: SPACING[6], gap: SPACING[8] },
  completeStat: { alignItems: 'center' },
  completeStatValue: { ...TYPOGRAPHY.TITLE_1, color: TEXT.PRIMARY, fontVariant: ['tabular-nums'] },
  completeStatLabel: { ...TYPOGRAPHY.CAPTION_1, color: TEXT.TERTIARY, marginTop: SPACING[1] },
  doneButton: { width: 200, height: 56, borderRadius: RADIUS.MD, borderCurve: 'continuous', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', backgroundColor: GREEN[500] },
  doneButtonText: { ...TYPOGRAPHY.BUTTON_MEDIUM, color: NAVY[900], letterSpacing: 1 },
})
