/**
 * TabataFit Pre-Workout Detail Screen
 * Clean modal with workout info
 */

import { useState, useEffect, useMemo } from 'react'
import { View, Text as RNText, StyleSheet, ScrollView, Pressable } from 'react-native'
import { useRouter, useLocalSearchParams } from 'expo-router'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { BlurView } from 'expo-blur'
import Ionicons from '@expo/vector-icons/Ionicons'
import { useTranslation } from 'react-i18next'
import { Host, Button, HStack } from '@expo/ui/swift-ui'
import { glassEffect, padding } from '@expo/ui/swift-ui/modifiers'

import { useHaptics } from '@/src/shared/hooks'
import { track } from '@/src/shared/services/analytics'
import { getWorkoutById } from '@/src/shared/data'
import { useTranslatedWorkout, useMusicVibeLabel } from '@/src/shared/data/useTranslatedData'

import { useThemeColors, BRAND } from '@/src/shared/theme'
import type { ThemeColors } from '@/src/shared/theme/types'
import { TYPOGRAPHY } from '@/src/shared/constants/typography'
import { SPACING, LAYOUT } from '@/src/shared/constants/spacing'
import { RADIUS } from '@/src/shared/constants/borderRadius'

// ═══════════════════════════════════════════════════════════════════════════
// MAIN SCREEN
// ═══════════════════════════════════════════════════════════════════════════

export default function WorkoutDetailScreen() {
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const { t } = useTranslation()
  const { id } = useLocalSearchParams<{ id: string }>()
  const [isSaved, setIsSaved] = useState(false)

  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])

  const rawWorkout = getWorkoutById(id ?? '1')
  const workout = useTranslatedWorkout(rawWorkout)
  const musicVibeLabel = useMusicVibeLabel(rawWorkout?.musicVibe ?? '')

  useEffect(() => {
    if (workout) {
      track('workout_detail_viewed', {
        workout_id: workout.id,
        workout_title: workout.title,
        level: workout.level,
        duration: workout.duration,
      })
    }
  }, [workout?.id])

  if (!workout) {
    return (
      <View style={[styles.container, styles.centered]}>
        <RNText style={{ color: colors.text.primary, fontSize: 17 }}>{t('screens:workout.notFound')}</RNText>
      </View>
    )
  }

  const handleStartWorkout = () => {
    haptics.phaseChange()
    router.push(`/player/${workout.id}`)
  }

  const toggleSave = () => {
    haptics.selection()
    setIsSaved(!isSaved)
  }

  const repeatCount = Math.max(1, Math.floor(workout.rounds / workout.exercises.length))

  return (
    <View style={styles.container}>
      {/* Header with SwiftUI glass button */}
      <View style={[styles.header, { paddingTop: insets.top + SPACING[3] }]}>
        <RNText style={styles.headerTitle} numberOfLines={1}>
          {workout.title}
        </RNText>

        {/* SwiftUI glass button */}
        <View style={styles.glassButtonContainer}>
          <Host matchContents useViewportSizeMeasurement colorScheme="dark">
            <HStack
              alignment="center"
              modifiers={[
                padding({ all: 8 }),
                glassEffect({ glass: { variant: 'regular' } }),
              ]}
            >
              <Button
                variant="borderless"
                onPress={toggleSave}
                color={isSaved ? '#FF3B30' : '#FFFFFF'}
              >
                {isSaved ? '♥' : '♡'}
              </Button>
            </HStack>
          </Host>
        </View>
      </View>

      {/* Content */}
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 100 }]}
        showsVerticalScrollIndicator={false}
      >
        {/* Quick stats */}
        <View style={styles.quickStats}>
          <View style={[styles.statBadge, { backgroundColor: 'rgba(255, 107, 53, 0.15)' }]}>
            <Ionicons name="barbell" size={14} color={BRAND.PRIMARY} />
            <RNText style={[styles.statBadgeText, { color: BRAND.PRIMARY }]}>
              {t(`levels.${workout.level.toLowerCase()}`)}
            </RNText>
          </View>
          <View style={[styles.statBadge, { backgroundColor: colors.bg.surface }]}>
            <Ionicons name="time" size={14} color={colors.text.secondary} />
            <RNText style={styles.statBadgeText}>{t('units.minUnit', { count: workout.duration })}</RNText>
          </View>
          <View style={[styles.statBadge, { backgroundColor: colors.bg.surface }]}>
            <Ionicons name="flame" size={14} color={colors.text.secondary} />
            <RNText style={styles.statBadgeText}>{t('units.calUnit', { count: workout.calories })}</RNText>
          </View>
        </View>

        {/* Equipment */}
        <View style={styles.section}>
          <RNText style={styles.sectionTitle}>{t('screens:workout.whatYoullNeed')}</RNText>
          {workout.equipment.map((item, index) => (
            <View key={index} style={styles.equipmentItem}>
              <Ionicons name="checkmark-circle" size={20} color="#30D158" />
              <RNText style={styles.equipmentText}>{item}</RNText>
            </View>
          ))}
        </View>

        <View style={styles.divider} />

        {/* Exercises */}
        <View style={styles.section}>
          <RNText style={styles.sectionTitle}>{t('screens:workout.exercises', { count: workout.rounds })}</RNText>
          <View style={styles.exercisesList}>
            {workout.exercises.map((exercise, index) => (
              <View key={index} style={styles.exerciseRow}>
                <View style={styles.exerciseNumber}>
                  <RNText style={styles.exerciseNumberText}>{index + 1}</RNText>
                </View>
                <RNText style={styles.exerciseName}>{exercise.name}</RNText>
                <RNText style={styles.exerciseDuration}>{exercise.duration}s</RNText>
              </View>
            ))}
            <View style={styles.repeatNote}>
              <Ionicons name="repeat" size={16} color={colors.text.tertiary} />
              <RNText style={styles.repeatText}>{t('screens:workout.repeatRounds', { count: repeatCount })}</RNText>
            </View>
          </View>
        </View>

        <View style={styles.divider} />

        {/* Music */}
        <View style={styles.section}>
          <RNText style={styles.sectionTitle}>{t('screens:workout.music')}</RNText>
          <View style={styles.musicCard}>
            <View style={styles.musicIcon}>
              <Ionicons name="musical-notes" size={24} color={BRAND.PRIMARY} />
            </View>
            <View style={styles.musicInfo}>
              <RNText style={styles.musicName}>{t('screens:workout.musicMix', { vibe: musicVibeLabel })}</RNText>
              <RNText style={styles.musicDescription}>{t('screens:workout.curatedForWorkout')}</RNText>
            </View>
          </View>
        </View>
      </ScrollView>

      {/* Fixed Start Button */}
      <View style={[styles.bottomBar, { paddingBottom: insets.bottom + SPACING[4] }]}>
        <BlurView intensity={80} tint="dark" style={StyleSheet.absoluteFill} />
        <Pressable
          style={({ pressed }) => [
            styles.startButton,
            pressed && styles.startButtonPressed,
          ]}
          onPress={handleStartWorkout}
        >
          <RNText style={styles.startButtonText}>{t('screens:workout.startWorkout')}</RNText>
        </Pressable>
      </View>
    </View>
  )
}

// ═══════════════════════════════════════════════════════════════════════════
// STYLES
// ═══════════════════════════════════════════════════════════════════════════

function createStyles(colors: ThemeColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.bg.base,
    },
    centered: {
      alignItems: 'center',
      justifyContent: 'center',
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
    },

    // Header
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: SPACING[4],
      paddingBottom: SPACING[3],
    },
    headerTitle: {
      flex: 1,
      ...TYPOGRAPHY.HEADLINE,
      color: colors.text.primary,
      marginRight: SPACING[3],
    },
    glassButtonContainer: {
      width: 44,
      height: 44,
    },

    // Quick Stats
    quickStats: {
      flexDirection: 'row',
      gap: SPACING[2],
      marginBottom: SPACING[5],
    },
    statBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: SPACING[3],
      paddingVertical: SPACING[2],
      borderRadius: RADIUS.FULL,
      gap: SPACING[1],
    },
    statBadgeText: {
      ...TYPOGRAPHY.CAPTION_1,
      color: colors.text.secondary,
      fontWeight: '600',
    },

    // Section
    section: {
      paddingVertical: SPACING[3],
    },
    sectionTitle: {
      ...TYPOGRAPHY.HEADLINE,
      color: colors.text.primary,
      marginBottom: SPACING[3],
    },

    // Divider
    divider: {
      height: 1,
      backgroundColor: colors.border.glass,
      marginVertical: SPACING[2],
    },

    // Equipment
    equipmentItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: SPACING[3],
      marginBottom: SPACING[2],
    },
    equipmentText: {
      ...TYPOGRAPHY.BODY,
      color: colors.text.secondary,
    },

    // Exercises
    exercisesList: {
      gap: SPACING[2],
    },
    exerciseRow: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingVertical: SPACING[3],
      paddingHorizontal: SPACING[4],
      backgroundColor: colors.bg.surface,
      borderRadius: RADIUS.LG,
      gap: SPACING[3],
    },
    exerciseNumber: {
      width: 28,
      height: 28,
      borderRadius: 14,
      backgroundColor: 'rgba(255, 107, 53, 0.15)',
      alignItems: 'center',
      justifyContent: 'center',
    },
    exerciseNumberText: {
      ...TYPOGRAPHY.CALLOUT,
      color: BRAND.PRIMARY,
      fontWeight: '700',
    },
    exerciseName: {
      ...TYPOGRAPHY.BODY,
      color: colors.text.primary,
      flex: 1,
    },
    exerciseDuration: {
      ...TYPOGRAPHY.CAPTION_1,
      color: colors.text.tertiary,
    },
    repeatNote: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: SPACING[2],
      marginTop: SPACING[2],
      paddingHorizontal: SPACING[2],
    },
    repeatText: {
      ...TYPOGRAPHY.CAPTION_1,
      color: colors.text.tertiary,
    },

    // Music
    musicCard: {
      flexDirection: 'row',
      alignItems: 'center',
      padding: SPACING[4],
      backgroundColor: colors.bg.surface,
      borderRadius: RADIUS.LG,
      gap: SPACING[3],
    },
    musicIcon: {
      width: 48,
      height: 48,
      borderRadius: 24,
      backgroundColor: 'rgba(255, 107, 53, 0.15)',
      alignItems: 'center',
      justifyContent: 'center',
    },
    musicInfo: {
      flex: 1,
    },
    musicName: {
      ...TYPOGRAPHY.HEADLINE,
      color: colors.text.primary,
    },
    musicDescription: {
      ...TYPOGRAPHY.CAPTION_1,
      color: colors.text.tertiary,
      marginTop: 2,
    },

    // Bottom Bar
    bottomBar: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
      paddingTop: SPACING[4],
      borderTopWidth: 1,
      borderTopColor: colors.border.glass,
    },

    // Start Button
    startButton: {
      height: 56,
      borderRadius: RADIUS.LG,
      backgroundColor: BRAND.PRIMARY,
      alignItems: 'center',
      justifyContent: 'center',
    },
    startButtonPressed: {
      backgroundColor: BRAND.PRIMARY_DARK,
      transform: [{ scale: 0.98 }],
    },
    startButtonText: {
      ...TYPOGRAPHY.HEADLINE,
      color: '#FFFFFF',
      letterSpacing: 1,
    },
  })
}
