/**
 * TabataFit Workouts Screen
 * Premium workout browser — scrollable category pills, trainers, workout grid
 */

import { useState, useRef, useMemo } from 'react'
import { View, StyleSheet, ScrollView, Pressable, Dimensions, Animated } from 'react-native'
import { useRouter } from 'expo-router'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { LinearGradient } from 'expo-linear-gradient'
import { BlurView } from 'expo-blur'
import Ionicons from '@expo/vector-icons/Ionicons'

import { useTranslation } from 'react-i18next'
import { useHaptics } from '@/src/shared/hooks'
import { WORKOUTS } from '@/src/shared/data'
import { useTranslatedCategories, useTranslatedWorkouts } from '@/src/shared/data/useTranslatedData'
import { StyledText } from '@/src/shared/components/StyledText'

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

const { width: SCREEN_WIDTH } = Dimensions.get('window')
const CARD_WIDTH = (SCREEN_WIDTH - LAYOUT.SCREEN_PADDING * 2 - SPACING[3]) / 2

// ═══════════════════════════════════════════════════════════════════════════
// CATEGORY PILL
// ═══════════════════════════════════════════════════════════════════════════

function CategoryPill({
  label,
  selected,
  onPress,
}: {
  label: string
  selected: boolean
  onPress: () => void
}) {
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  return (
    <Pressable
      style={[styles.pill, selected && styles.pillSelected]}
      onPress={onPress}
    >
      {selected && (
        <LinearGradient
          colors={GRADIENTS.CTA}
          style={[StyleSheet.absoluteFill, { borderRadius: 20 }]}
        />
      )}
      <StyledText
        size={14}
        weight={selected ? 'semibold' : 'regular'}
        color={selected ? '#FFFFFF' : colors.text.tertiary}
      >
        {label}
      </StyledText>
    </Pressable>
  )
}

// ═══════════════════════════════════════════════════════════════════════════
// WORKOUT CARD
// ═══════════════════════════════════════════════════════════════════════════

function WorkoutCard({
  title,
  duration,
  level,
  levelLabel,
  onPress,
}: {
  title: string
  duration: number
  level: string
  levelLabel: string
  onPress: () => void
}) {
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  return (
    <Pressable style={styles.workoutCard} onPress={onPress}>
      <BlurView intensity={colors.glass.blurMedium} tint={colors.glass.blurTint} style={StyleSheet.absoluteFill} />

      {/* Subtle gradient accent at top */}
      <LinearGradient
        colors={[levelColor(level, colors) + '30', 'transparent']}
        style={styles.cardGradient}
      />

      {/* Duration badge */}
      <View style={styles.durationBadge}>
        <Ionicons name="time-outline" size={10} color={colors.text.secondary} />
        <StyledText size={11} weight="semibold" color={colors.text.secondary} style={{ marginLeft: 3 }}>
          {duration + ' min'}
        </StyledText>
      </View>

      {/* Play button */}
      <View style={styles.playArea}>
        <View style={styles.playCircle}>
          <Ionicons name="play" size={18} color={colors.text.primary} />
        </View>
      </View>

      {/* Info */}
      <View style={styles.workoutInfo}>
        <StyledText size={14} weight="semibold" color={colors.text.primary} numberOfLines={2}>
          {title}
        </StyledText>
        <View style={styles.levelRow}>
          <View style={[styles.levelDot, { backgroundColor: levelColor(level, colors) }]} />
          <StyledText size={11} color={colors.text.tertiary}>
            {levelLabel}
          </StyledText>
        </View>
      </View>
    </Pressable>
  )
}

function levelColor(level: string, colors: ThemeColors): string {
  switch (level.toLowerCase()) {
    case 'beginner': return BRAND.SUCCESS
    case 'intermediate': return BRAND.SECONDARY
    case 'advanced': return BRAND.DANGER
    default: return colors.text.tertiary
  }
}

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

export default function WorkoutsScreen() {
  const { t } = useTranslation()
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  const [selectedCategory, setSelectedCategory] = useState('all')
  const categories = useTranslatedCategories()

  const filteredWorkouts = selectedCategory === 'all'
    ? WORKOUTS
    : WORKOUTS.filter(w => w.category === selectedCategory)

  const translatedFiltered = useTranslatedWorkouts(filteredWorkouts)

  const handleWorkoutPress = (id: string) => {
    haptics.buttonTap()
    router.push(`/workout/${id}`)
  }

  const selectedLabel = categories.find(c => c.id === selectedCategory)?.label ?? t('screens:workouts.allWorkouts')

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 100 }]}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <StyledText size={34} weight="bold" color={colors.text.primary}>
            {t('screens:workouts.title')}
          </StyledText>
          <StyledText size={15} color={colors.text.tertiary}>
            {t('screens:workouts.available', { count: WORKOUTS.length })}
          </StyledText>
        </View>

        {/* Category Pills — horizontal scroll, no truncation */}
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.pillsRow}
          style={styles.pillsScroll}
        >
          {categories.map((cat) => (
            <CategoryPill
              key={cat.id}
              label={cat.label}
              selected={selectedCategory === cat.id}
              onPress={() => {
                haptics.selection()
                setSelectedCategory(cat.id)
              }}
            />
          ))}
        </ScrollView>

        {/* Workouts Grid */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <StyledText size={20} weight="semibold" color={colors.text.primary}>
              {selectedCategory === 'all' ? t('screens:workouts.allWorkouts') : selectedLabel}
            </StyledText>
            {selectedCategory !== 'all' && (
              <Pressable onPress={() => { haptics.buttonTap(); router.push(`/workout/category/${selectedCategory}`) }}>
                <StyledText size={14} color={BRAND.PRIMARY} weight="medium">{t('seeAll')}</StyledText>
              </Pressable>
            )}
          </View>
          <View style={styles.workoutsGrid}>
            {translatedFiltered.map((workout) => (
              <WorkoutCard
                key={workout.id}
                title={workout.title}
                duration={workout.duration}
                level={workout.level}
                levelLabel={t(`levels.${workout.level.toLowerCase()}`)}
                onPress={() => handleWorkoutPress(workout.id)}
              />
            ))}
          </View>
        </View>
      </ScrollView>
    </View>
  )
}

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

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

    // Header
    header: {
      marginBottom: SPACING[4],
    },

    // Pills
    pillsScroll: {
      marginHorizontal: -LAYOUT.SCREEN_PADDING,
      marginBottom: SPACING[6],
    },
    pillsRow: {
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
      gap: SPACING[2],
    },
    pill: {
      paddingHorizontal: SPACING[4],
      paddingVertical: SPACING[2],
      borderRadius: 20,
      backgroundColor: colors.bg.surface,
      borderWidth: 1,
      borderColor: colors.border.glassLight,
    },
    pillSelected: {
      borderColor: BRAND.PRIMARY,
      backgroundColor: 'transparent',
    },

    // Section
    section: {
      marginBottom: SPACING[6],
    },
    sectionHeader: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: SPACING[4],
    },

    // Workouts Grid
    workoutsGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: SPACING[3],
    },
    workoutCard: {
      width: CARD_WIDTH,
      height: 190,
      borderRadius: RADIUS.GLASS_CARD,
      overflow: 'hidden',
      borderWidth: 1,
      borderColor: colors.bg.overlay2,
    },
    cardGradient: {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      height: 80,
    },
    durationBadge: {
      position: 'absolute',
      top: SPACING[3],
      right: SPACING[3],
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      paddingHorizontal: SPACING[2],
      paddingVertical: 3,
      borderRadius: RADIUS.SM,
    },
    playArea: {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 64,
      alignItems: 'center',
      justifyContent: 'center',
    },
    playCircle: {
      width: 40,
      height: 40,
      borderRadius: 20,
      backgroundColor: colors.border.glassStrong,
      alignItems: 'center',
      justifyContent: 'center',
      borderWidth: 1,
      borderColor: 'rgba(255, 255, 255, 0.25)',
    },
    workoutInfo: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      padding: SPACING[3],
      paddingTop: SPACING[2],
    },
    levelRow: {
      flexDirection: 'row',
      alignItems: 'center',
      marginTop: 3,
      gap: 5,
    },
    levelDot: {
      width: 6,
      height: 6,
      borderRadius: 3,
    },
  })
}
