/**
 * Body Zone Detail Screen
 * Shows workout programs filtered by body zone with difficulty pills
 */

import { useState, useMemo, useEffect, useCallback } from 'react'
import { View, StyleSheet, ScrollView, Pressable } from 'react-native'
import { useRouter, useLocalSearchParams } from 'expo-router'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { Icon } from '@/src/shared/components/Icon'

import { useTranslation } from 'react-i18next'
import { useHaptics } from '@/src/shared/hooks'
import { usePurchases } from '@/src/shared/hooks/usePurchases'
import { StyledText } from '@/src/shared/components/StyledText'
import { useThemeColors } from '@/src/shared/theme'
import type { ThemeColors } from '@/src/shared/theme/types'
import { BRAND, GREEN, TEXT, NAVY, BORDER_COLORS } from '@/src/shared/constants/colors'
import { SPACING, LAYOUT } from '@/src/shared/constants/spacing'
import { RADIUS } from '@/src/shared/constants/borderRadius'
import { canAccessWorkoutProgram } from '@/src/shared/services/access'
import { useWorkoutProgramStore } from '@/src/shared/stores/workoutProgramStore'
import { fetchProgramsByBodyZone, buildWorkoutProgramId } from '@/src/shared/data/workoutPrograms'
import type { WorkoutProgram, BodyZone, ProgramLevel } from '@/src/shared/types/workoutProgram'
import { BODY_ZONE_META, LEVEL_META } from '@/src/shared/types/workoutProgram'

const LEVELS: ProgramLevel[] = ['Beginner', 'Intermediate', 'Advanced']

export default function BodyZoneDetailScreen() {
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const { t } = useTranslation('screens')
  const { id } = useLocalSearchParams<{ id: string }>()
  const colors = useThemeColors()
  const { isPremium } = usePurchases()
  const isProgramCompleted = useWorkoutProgramStore(s => s.isProgramCompleted)

  const bodyZone = (id ?? 'full-body') as BodyZone
  const meta = BODY_ZONE_META[bodyZone]

  const [programs, setPrograms] = useState<WorkoutProgram[]>([])
  const [selectedLevel, setSelectedLevel] = useState<ProgramLevel>('Beginner')

  useEffect(() => {
    fetchProgramsByBodyZone(bodyZone).then((data) => {
      setPrograms(data)
      // Default to first level that has programs
      const firstAvailable = LEVELS.find(l => data.some(p => p.level === l))
      if (firstAvailable) setSelectedLevel(firstAvailable)
    })
  }, [bodyZone])

  const filteredPrograms = useMemo(
    () => programs.filter(p => p.level === selectedLevel),
    [programs, selectedLevel],
  )

  const handleProgramPress = (program: WorkoutProgram) => {
    haptics.buttonTap()
    const isLocked = !canAccessWorkoutProgram(program, isPremium)
    if (isLocked) {
      router.push('/paywall')
      return
    }
    router.push(`/workout/${buildWorkoutProgramId(program.id)}` as any)
  }

  const handleLevelPress = (level: ProgramLevel) => {
    haptics.buttonTap()
    setSelectedLevel(level)
  }

  const accentColor = meta.color

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

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 20 }]}
        showsVerticalScrollIndicator={false}
      >
        {/* Difficulty Pills */}
        <View style={styles.pillsRow}>
          {LEVELS.map((level) => {
            const levelMeta = LEVEL_META[level]
            const isActive = selectedLevel === level

            return (
              <Pressable
                key={level}
                onPress={() => handleLevelPress(level)}
                style={[
                  styles.pill,
                  {
                    backgroundColor: isActive ? accentColor + '20' : NAVY[800],
                    borderColor: isActive ? accentColor : BORDER_COLORS.DIM,
                  },
                ]}
              >
                <StyledText
                  size={14}
                  weight={isActive ? 'semibold' : 'regular'}
                  color={isActive ? accentColor : colors.text.secondary}
                >
                  {levelMeta.label}
                </StyledText>
              </Pressable>
            )
          })}
        </View>

        {/* Program Count */}
        <StyledText size={13} color={colors.text.tertiary} style={styles.resultCount}>
          {filteredPrograms.length} programme{filteredPrograms.length !== 1 ? 's' : ''} {LEVEL_META[selectedLevel].label.toLowerCase()}
        </StyledText>

        {/* Program List */}
        {filteredPrograms.map((program) => (
          <ProgramCard
            key={program.id}
            program={program}
            accentColor={accentColor}
            onPress={() => handleProgramPress(program)}
            isPremium={isPremium}
            isCompleted={isProgramCompleted(program.id)}
          />
        ))}

        {filteredPrograms.length === 0 && (
          <View style={styles.emptyState}>
            <Icon name="dumbbell" size={32} tintColor={colors.text.tertiary} />
            <StyledText preset="CALLOUT" color={colors.text.tertiary} style={{ marginTop: SPACING[3], textAlign: 'center' }}>
              Aucun programme disponible pour ce niveau
            </StyledText>
          </View>
        )}
      </ScrollView>
    </View>
  )
}

// ═══════════════════════════════════════════════════════════════════════════
// PROGRAM CARD (full-width)
// ═══════════════════════════════════════════════════════════════════════════

function ProgramCard({
  program,
  accentColor,
  onPress,
  isPremium,
  isCompleted,
}: {
  program: WorkoutProgram
  accentColor: string
  onPress: () => void
  isPremium: boolean
  isCompleted: boolean
}) {
  const { t } = useTranslation('screens')
  const colors = useThemeColors()
  const isLocked = !canAccessWorkoutProgram(program, isPremium)
  const levelMeta = LEVEL_META[program.level]
  const color = program.accentColor ?? accentColor

  return (
    <Pressable
      onPress={onPress}
      style={({ pressed }) => [
        {
          borderRadius: RADIUS.XL,
          overflow: 'hidden',
          borderWidth: 1,
          borderCurve: 'continuous' as const,
          borderColor: colors.border.dim,
          backgroundColor: colors.surface.default.backgroundColor,
          marginBottom: SPACING[3],
          opacity: pressed ? 0.85 : 1,
        },
      ]}
    >
      {/* Accent line */}
      <View style={{ height: 3, width: '100%', backgroundColor: color }} />

      <View style={{ padding: SPACING[5] }}>
        {/* Title row */}
        <View style={{ flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between' }}>
          <StyledText preset="TITLE_3" color={colors.text.primary} style={{ flex: 1, marginRight: SPACING[3] }}>
            {program.title}
          </StyledText>

          {isCompleted ? (
            <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: SPACING[3], paddingVertical: SPACING[1], borderRadius: RADIUS.PILL, backgroundColor: GREEN['500'] + '20' }}>
              <Icon name="checkmark" size={12} tintColor={GREEN['500']} />
              <StyledText size={11} weight="semibold" color={GREEN['500']} style={{ marginLeft: 4 }}>
                Complété
              </StyledText>
            </View>
          ) : isLocked ? (
            <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: SPACING[3], paddingVertical: SPACING[1], borderRadius: RADIUS.PILL, backgroundColor: color + '15' }}>
              <Icon name="lock" size={12} tintColor={color} />
              <StyledText size={11} weight="semibold" color={color} style={{ marginLeft: 4 }}>
                {t('home.premiumBadge')}
              </StyledText>
            </View>
          ) : (
            <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: SPACING[3], paddingVertical: SPACING[1], borderRadius: RADIUS.PILL, backgroundColor: GREEN.DIM }}>
              <StyledText size={11} weight="semibold" color={GREEN['500']}>
                {t('home.freeBadge')}
              </StyledText>
            </View>
          )}
        </View>

        {/* Description */}
        {program.description ? (
          <StyledText size={13} color={colors.text.tertiary} style={{ marginTop: SPACING[2] }} numberOfLines={2}>
            {program.description}
          </StyledText>
        ) : null}

        {/* Meta row */}
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: SPACING[4], marginTop: SPACING[4] }}>
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: SPACING[1] }}>
            <Icon name="timer" size={14} tintColor={colors.text.tertiary} />
            <StyledText size={12} color={colors.text.tertiary}>{program.estimatedDuration} min</StyledText>
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: SPACING[1] }}>
            <Icon name="flame" size={14} tintColor={colors.text.tertiary} />
            <StyledText size={12} color={colors.text.tertiary}>{program.estimatedCalories} kcal</StyledText>
          </View>
          <View style={{ flexDirection: 'row', alignItems: 'center', gap: SPACING[1] }}>
            <Icon name="list.bullet" size={14} tintColor={colors.text.tertiary} />
            <StyledText size={12} color={colors.text.tertiary}>{program.tabatas.length} tabatas</StyledText>
          </View>
        </View>

        {/* CTA */}
        <View style={{ marginTop: SPACING[4], alignSelf: 'flex-start', flexDirection: 'row', alignItems: 'center', paddingHorizontal: SPACING[4], paddingVertical: SPACING[2], borderRadius: RADIUS.PILL, backgroundColor: isLocked ? color + '15' : GREEN.DIM }}>
          <Icon name={isLocked ? 'lock' : 'play.fill'} size={12} tintColor={isLocked ? color : GREEN['500']} />
          <StyledText size={13} weight="semibold" color={isLocked ? color : GREEN['500']} style={{ marginLeft: SPACING[2] }}>
            {isLocked ? t('home.unlockPremium') : t('home.startProgram')}
          </StyledText>
        </View>
      </View>
    </Pressable>
  )
}

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

const createStyles = (colors: ThemeColors, accentColor: string) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: NAVY[900],
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
    },

    // Difficulty pills
    pillsRow: {
      flexDirection: 'row',
      gap: SPACING[2],
      marginBottom: SPACING[5],
    },
    pill: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: SPACING[3],
      borderRadius: RADIUS.PILL,
      borderWidth: 1,
      borderCurve: 'continuous',
    },

    // Results
    resultCount: {
      marginBottom: SPACING[4],
    },

    // Empty state
    emptyState: {
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: SPACING[10],
    },
  })
