/**
 * TabataFit Category Detail Screen
 * Filtered workout list for a specific category with level sub-filter
 */

import { useState, useMemo } from 'react'
import { View, StyleSheet, ScrollView, Pressable, Text as RNText } 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 {
  Host,
  Picker,
} from '@expo/ui/swift-ui'

import { useTranslation } from 'react-i18next'

import { useHaptics } from '@/src/shared/hooks'
import { getWorkoutsByCategory, CATEGORIES } from '@/src/shared/data'
import { useTranslatedCategories, useTranslatedWorkouts } from '@/src/shared/data/useTranslatedData'
import { StyledText } from '@/src/shared/components/StyledText'
import type { WorkoutCategory, WorkoutLevel } from '@/src/shared/types'

import { useThemeColors, BRAND } 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 LEVEL_IDS: (WorkoutLevel | 'all')[] = ['all', 'Beginner', 'Intermediate', 'Advanced']

export default function CategoryDetailScreen() {
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const { t } = useTranslation()
  const { id } = useLocalSearchParams<{ id: string }>()

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

  const [selectedLevelIndex, setSelectedLevelIndex] = useState(0)

  const translatedCategories = useTranslatedCategories()

  const levelLabels = [
    t('screens:category.allLevels'),
    t('levels.beginner'),
    t('levels.intermediate'),
    t('levels.advanced'),
  ]

  const selectedLevel = LEVEL_IDS[selectedLevelIndex]
  const category = translatedCategories.find(c => c.id === id)
  const categoryLabel = category?.label ?? id ?? 'Category'

  const allWorkouts = useMemo(
    () => (id && id !== 'all') ? getWorkoutsByCategory(id as WorkoutCategory) : [],
    [id]
  )

  const filteredWorkouts = useMemo(() => {
    if (selectedLevel === 'all') return allWorkouts
    return allWorkouts.filter(w => w.level === selectedLevel)
  }, [allWorkouts, selectedLevel])

  const translatedWorkouts = useTranslatedWorkouts(filteredWorkouts)

  const handleBack = () => {
    haptics.selection()
    router.back()
  }

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

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      {/* Header */}
      <View style={styles.header}>
        <Pressable onPress={handleBack} style={styles.backButton}>
          <Icon name="chevron.left" size={24} color={colors.text.primary} />
        </Pressable>
        <StyledText size={22} weight="bold" color={colors.text.primary}>{categoryLabel}</StyledText>
        <View style={styles.backButton} />
      </View>

      {/* Level Filter */}
      <View style={styles.filterContainer}>
        <Host matchContents useViewportSizeMeasurement colorScheme={colors.colorScheme}>
          <Picker
            selectedIndex={selectedLevelIndex}
            onOptionSelected={(e) => {
              haptics.selection()
              setSelectedLevelIndex(e.nativeEvent.index)
            }}
            variant="segmented"
            options={levelLabels}
            color={BRAND.PRIMARY}
          />
        </Host>
      </View>

      <StyledText
        size={13}
        color={colors.text.tertiary}
        style={{ paddingHorizontal: LAYOUT.SCREEN_PADDING, marginBottom: SPACING[3] }}
      >
        {t('plurals.workout', { count: translatedWorkouts.length })}
      </StyledText>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: insets.bottom + 100 }]}
        showsVerticalScrollIndicator={false}
      >
        {translatedWorkouts.map((workout) => (
            <Pressable
              key={workout.id}
              style={styles.workoutCard}
              onPress={() => handleWorkoutPress(workout.id)}
            >
              <View style={[styles.workoutAvatar, { backgroundColor: BRAND.PRIMARY }]}>
                <Icon name="flame.fill" size={20} color="#FFFFFF" />
              </View>
              <View style={styles.workoutInfo}>
                <StyledText size={17} weight="semibold" color={colors.text.primary}>{workout.title}</StyledText>
                <StyledText size={13} color={colors.text.tertiary}>
                  {t('durationLevel', { duration: workout.duration, level: t(`levels.${(workout.level ?? 'Beginner').toLowerCase()}`) })}
                </StyledText>
              </View>
              <View style={styles.workoutMeta}>
                <StyledText size={13} color={BRAND.PRIMARY}>{t('units.calUnit', { count: workout.calories })}</StyledText>
                <Icon name="chevron.right" size={16} color={colors.text.tertiary} />
              </View>
            </Pressable>
        ))}

        {translatedWorkouts.length === 0 && (
          <View style={styles.emptyState}>
            <Icon name="dumbbell" size={48} color={colors.text.tertiary} />
            <StyledText size={17} color={colors.text.tertiary} style={{ marginTop: SPACING[3] }}>
              No workouts found
            </StyledText>
          </View>
        )}
      </ScrollView>
    </View>
  )
}

function createStyles(colors: ThemeColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.bg.base,
    },
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
      paddingVertical: SPACING[3],
    },
    backButton: {
      width: 44,
      height: 44,
      alignItems: 'center',
      justifyContent: 'center',
    },
    filterContainer: {
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
      marginBottom: SPACING[4],
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      paddingHorizontal: LAYOUT.SCREEN_PADDING,
    },
    workoutCard: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingVertical: SPACING[3],
      paddingHorizontal: SPACING[4],
      backgroundColor: colors.bg.surface,
      borderRadius: RADIUS.LG,
      marginBottom: SPACING[2],
      gap: SPACING[3],
    },
    workoutAvatar: {
      width: 44,
      height: 44,
      borderRadius: 22,
      alignItems: 'center',
      justifyContent: 'center',
    },
    workoutInitial: {
      fontSize: 18,
      fontWeight: '700',
      color: colors.text.primary,
    },
    workoutInfo: {
      flex: 1,
      gap: 2,
    },
    workoutMeta: {
      alignItems: 'flex-end',
      gap: 4,
    },
    emptyState: {
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: SPACING[12],
    },
  })
}
