/**
 * TabataFit Browse Screen - Premium Redesign
 * React Native UI with glassmorphism
 */

import { View, StyleSheet, ScrollView, Pressable, Dimensions, TextInput } from 'react-native'
import { useRouter } from 'expo-router'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { BlurView } from 'expo-blur'
import Ionicons from '@expo/vector-icons/Ionicons'

import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useHaptics } from '@/src/shared/hooks'
import {
  COLLECTIONS,
  getFeaturedCollection,
  WORKOUTS,
} from '@/src/shared/data'
import { useTranslatedCollections, useTranslatedWorkouts } from '@/src/shared/data/useTranslatedData'
import { StyledText } from '@/src/shared/components/StyledText'
import { WorkoutCard } from '@/src/shared/components/WorkoutCard'
import { CollectionCard } from '@/src/shared/components/CollectionCard'

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'
import type { WorkoutCategory } from '@/src/shared/types'

const { width: SCREEN_WIDTH } = Dimensions.get('window')

const FONTS = {
  LARGE_TITLE: 34,
  TITLE: 28,
  TITLE_2: 22,
  HEADLINE: 17,
  SUBHEADLINE: 15,
  CAPTION_1: 12,
  CAPTION_2: 11,
}

const CATEGORIES: { id: WorkoutCategory | 'all'; translationKey: string }[] = [
  { id: 'all', translationKey: 'common:categories.all' },
  { id: 'full-body', translationKey: 'common:categories.fullBody' },
  { id: 'core', translationKey: 'common:categories.core' },
  { id: 'upper-body', translationKey: 'common:categories.upperBody' },
  { id: 'lower-body', translationKey: 'common:categories.lowerBody' },
  { id: 'cardio', translationKey: 'common:categories.cardio' },
]

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

export default function BrowseScreen() {
  const { t } = useTranslation()
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])

  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<WorkoutCategory | 'all'>('all')

  const featuredCollection = getFeaturedCollection()
  const translatedCollections = useTranslatedCollections(COLLECTIONS)
  const translatedWorkouts = useTranslatedWorkouts(WORKOUTS)

  // Filter workouts based on search and category
  const filteredWorkouts = useMemo(() => {
    let filtered = translatedWorkouts

    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase()
      filtered = filtered.filter(
        (w) =>
          w.title.toLowerCase().includes(query) ||
          w.category.toLowerCase().includes(query)
      )
    }

    if (selectedCategory !== 'all') {
      filtered = filtered.filter((w) => w.category === selectedCategory)
    }

    return filtered
  }, [translatedWorkouts, searchQuery, selectedCategory])

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

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

  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={FONTS.LARGE_TITLE} weight="bold" color={colors.text.primary}>
            {t('screens:browse.title')}
          </StyledText>
        </View>

        {/* Search Bar */}
        <View style={styles.searchContainer}>
          <BlurView
            intensity={colors.glass.blurLight}
            tint={colors.glass.blurTint}
            style={StyleSheet.absoluteFill}
          />
          <Ionicons name="search" size={20} color={colors.text.tertiary} />
          <TextInput
            style={styles.searchInput}
            placeholder={t('screens:browse.searchPlaceholder') || 'Search workouts...'}
            placeholderTextColor={colors.text.tertiary}
            value={searchQuery}
            onChangeText={setSearchQuery}
          />
          {searchQuery.length > 0 && (
            <Pressable
              onPress={() => setSearchQuery('')}
              hitSlop={8}
            >
              <Ionicons name="close-circle" size={20} color={colors.text.tertiary} />
            </Pressable>
          )}
        </View>

        {/* Category Filter Chips */}
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.categoriesScroll}
          style={styles.categoriesContainer}
        >
          {CATEGORIES.map((cat) => (
            <Pressable
              key={cat.id}
              style={[
                styles.categoryChip,
                selectedCategory === cat.id && styles.categoryChipActive,
              ]}
              onPress={() => {
                haptics.buttonTap()
                setSelectedCategory(cat.id)
              }}
            >
              {selectedCategory === cat.id && (
                <BlurView
                  intensity={colors.glass.blurMedium}
                  tint={colors.glass.blurTint}
                  style={StyleSheet.absoluteFill}
                />
              )}
              <StyledText
                size={14}
                weight={selectedCategory === cat.id ? 'semibold' : 'medium'}
                color={selectedCategory === cat.id ? '#FFFFFF' : colors.text.secondary}
              >
                {t(cat.translationKey)}
              </StyledText>
            </Pressable>
          ))}
        </ScrollView>

        {/* Featured Collection */}
        {featuredCollection && !searchQuery && selectedCategory === 'all' && (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <StyledText size={FONTS.TITLE_2} weight="semibold" color={colors.text.primary}>
                {t('screens:browse.featured')}
              </StyledText>
            </View>
            <CollectionCard
              collection={featuredCollection}
              onPress={() => handleCollectionPress(featuredCollection.id)}
            />
          </View>
        )}

        {/* Collections Grid */}
        {!searchQuery && selectedCategory === 'all' && (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <StyledText size={FONTS.TITLE_2} weight="semibold" color={colors.text.primary}>
                {t('screens:browse.collections')}
              </StyledText>
            </View>
            <View style={styles.collectionsGrid}>
              {translatedCollections.map((collection) => (
                <CollectionCard
                  key={collection.id}
                  collection={collection}
                  onPress={() => handleCollectionPress(collection.id)}
                />
              ))}
            </View>
          </View>
        )}

        {/* All Workouts Grid */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <StyledText size={FONTS.TITLE_2} weight="semibold" color={colors.text.primary}>
              {searchQuery ? t('screens:browse.searchResults') || 'Results' : t('screens:browse.allWorkouts') || 'All Workouts'}
            </StyledText>
            <StyledText size={FONTS.CAPTION_1} color={colors.text.tertiary}>
              {filteredWorkouts.length} {t('plurals.workout', { count: filteredWorkouts.length })}
            </StyledText>
          </View>

          {filteredWorkouts.length > 0 ? (
            <View style={styles.workoutsGrid}>
              {filteredWorkouts.map((workout) => (
                <WorkoutCard
                  key={workout.id}
                  workout={workout}
                  variant="grid"
                  onPress={() => handleWorkoutPress(workout.id)}
                />
              ))}
            </View>
          ) : (
            <View style={styles.emptyState}>
              <Ionicons name="fitness-outline" size={48} color={colors.text.tertiary} />
              <StyledText
                size={FONTS.HEADLINE}
                weight="medium"
                color={colors.text.secondary}
                style={{ marginTop: SPACING[4] }}
              >
                {t('screens:browse.noResults') || 'No workouts found'}
              </StyledText>
              <StyledText
                size={FONTS.SUBHEADLINE}
                color={colors.text.tertiary}
                style={{ marginTop: SPACING[2], textAlign: 'center' }}
              >
                {t('screens:browse.tryDifferentSearch') || 'Try a different search or category'}
              </StyledText>
            </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],
    },

    // Search Bar
    searchContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      height: 48,
      borderRadius: RADIUS.LG,
      borderWidth: 1,
      borderColor: colors.border.glass,
      paddingHorizontal: SPACING[4],
      marginBottom: SPACING[4],
      overflow: 'hidden',
    },
    searchInput: {
      flex: 1,
      marginLeft: SPACING[3],
      marginRight: SPACING[2],
      fontSize: FONTS.HEADLINE,
      color: colors.text.primary,
      height: '100%',
    },

    // Categories
    categoriesContainer: {
      marginBottom: SPACING[6],
    },
    categoriesScroll: {
      gap: SPACING[2],
      paddingRight: SPACING[4],
    },
    categoryChip: {
      paddingHorizontal: SPACING[4],
      paddingVertical: SPACING[2],
      borderRadius: RADIUS.FULL,
      overflow: 'hidden',
      borderWidth: 1,
      borderColor: colors.border.glass,
    },
    categoryChipActive: {
      borderColor: BRAND.PRIMARY,
      backgroundColor: `${BRAND.PRIMARY}30`,
    },

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

    // Collections
    collectionsGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: SPACING[3],
    },

    // Workouts Grid
    workoutsGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: SPACING[3],
    },

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