/**
 * TabataFit Browse Screen
 * React Native UI — wired to shared data
 */

import { View, StyleSheet, ScrollView, Pressable, Dimensions, Text as RNText } 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 { useHaptics } from '@/src/shared/hooks'
import {
  COLLECTIONS,
  PROGRAMS,
  getFeaturedCollection,
  COLLECTION_COLORS,
  WORKOUTS,
  getTrainerById,
} from '@/src/shared/data'
import { StyledText } from '@/src/shared/components/StyledText'

import {
  BRAND,
  DARK,
  TEXT,
  GLASS,
  SHADOW,
} from '@/src/shared/constants/colors'
import { SPACING, LAYOUT } from '@/src/shared/constants/spacing'
import { RADIUS } from '@/src/shared/constants/borderRadius'

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,
}

function TextButton({ children, onPress }: { children: string; onPress?: () => void }) {
  return (
    <Pressable onPress={onPress} hitSlop={8}>
      <StyledText size={FONTS.SUBHEADLINE} color={BRAND.PRIMARY} weight="medium">
        {children}
      </StyledText>
    </Pressable>
  )
}

// New Releases: last 4 workouts
const NEW_RELEASES = WORKOUTS.slice(-4)

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

export default function BrowseScreen() {
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()

  const featuredCollection = getFeaturedCollection()

  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 */}
        <StyledText size={FONTS.LARGE_TITLE} weight="bold" color={TEXT.PRIMARY}>Browse</StyledText>

        {/* Featured Collection */}
        {featuredCollection && (
          <Pressable style={styles.featuredCard} onPress={() => handleCollectionPress(featuredCollection.id)}>
            <LinearGradient
              colors={featuredCollection.gradient ?? [BRAND.PRIMARY, '#FF3B30']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={StyleSheet.absoluteFill}
            />

            <View style={styles.featuredBadge}>
              <Ionicons name="star" size={12} color={TEXT.PRIMARY} />
              <RNText style={styles.featuredBadgeText}>FEATURED</RNText>
            </View>

            <View style={styles.featuredInfo}>
              <StyledText size={FONTS.TITLE} weight="bold" color={TEXT.PRIMARY}>{featuredCollection.title}</StyledText>
              <StyledText size={FONTS.HEADLINE} color={TEXT.SECONDARY}>{featuredCollection.description}</StyledText>

              <View style={styles.featuredStats}>
                <View style={styles.featuredStat}>
                  <Ionicons name="fitness" size={14} color={TEXT.PRIMARY} />
                  <StyledText size={FONTS.CAPTION_1} color={TEXT.PRIMARY}>{featuredCollection.workoutIds.length + ' workouts'}</StyledText>
                </View>
              </View>
            </View>
          </Pressable>
        )}

        {/* Collections Grid */}
        <View style={styles.section}>
          <StyledText size={FONTS.TITLE_2} weight="semibold" color={TEXT.PRIMARY}>Collections</StyledText>
          <View style={styles.collectionsGrid}>
            {COLLECTIONS.map((collection) => {
              const color = COLLECTION_COLORS[collection.id] ?? BRAND.PRIMARY
              return (
                <Pressable
                  key={collection.id}
                  style={styles.collectionCard}
                  onPress={() => handleCollectionPress(collection.id)}
                >
                  <BlurView intensity={GLASS.BLUR_LIGHT} tint="dark" style={StyleSheet.absoluteFill} />
                  <View style={[styles.collectionIconBg, { backgroundColor: `${color}20` }]}>
                    <RNText style={styles.collectionEmoji}>{collection.icon}</RNText>
                  </View>
                  <StyledText size={FONTS.SUBHEADLINE} weight="semibold" color={TEXT.PRIMARY} numberOfLines={1}>
                    {collection.title}
                  </StyledText>
                  <StyledText size={FONTS.CAPTION_1} color={color}>
                    {collection.workoutIds.length + ' workouts'}
                  </StyledText>
                </Pressable>
              )
            })}
          </View>
        </View>

        {/* Programs */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <StyledText size={FONTS.TITLE_2} weight="semibold" color={TEXT.PRIMARY}>Programs</StyledText>
            <TextButton>See All</TextButton>
          </View>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.programsScroll}
          >
            {PROGRAMS.map((program) => (
              <View key={program.id} style={styles.programCard}>
                <BlurView intensity={GLASS.BLUR_MEDIUM} tint="dark" style={StyleSheet.absoluteFill} />

                <View style={styles.programHeader}>
                  <View style={styles.programLevelBadge}>
                    <StyledText size={FONTS.CAPTION_2} weight="semibold" color={TEXT.PRIMARY}>{program.level}</StyledText>
                  </View>
                </View>

                <StyledText size={FONTS.HEADLINE} weight="semibold" color={TEXT.PRIMARY}>{program.title}</StyledText>

                <View style={styles.programMeta}>
                  <View style={styles.programMetaItem}>
                    <Ionicons name="calendar" size={14} color={TEXT.TERTIARY} />
                    <StyledText size={FONTS.CAPTION_1} color={TEXT.TERTIARY}>{program.weeks + ' weeks'}</StyledText>
                  </View>
                  <View style={styles.programMetaItem}>
                    <Ionicons name="repeat" size={14} color={TEXT.TERTIARY} />
                    <StyledText size={FONTS.CAPTION_1} color={TEXT.TERTIARY}>{program.workoutsPerWeek + 'x /week'}</StyledText>
                  </View>
                </View>
              </View>
            ))}
          </ScrollView>
        </View>

        {/* New Releases */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <StyledText size={FONTS.TITLE_2} weight="semibold" color={TEXT.PRIMARY}>New Releases</StyledText>
          </View>
          {NEW_RELEASES.map((workout) => {
            const trainer = getTrainerById(workout.trainerId)
            return (
              <Pressable
                key={workout.id}
                style={styles.releaseRow}
                onPress={() => handleWorkoutPress(workout.id)}
              >
                <View style={[styles.releaseAvatar, { backgroundColor: trainer?.color ?? BRAND.PRIMARY }]}>
                  <RNText style={styles.releaseInitial}>{trainer?.name[0] ?? 'T'}</RNText>
                </View>
                <View style={styles.releaseInfo}>
                  <StyledText size={FONTS.HEADLINE} weight="semibold" color={TEXT.PRIMARY}>{workout.title}</StyledText>
                  <StyledText size={FONTS.CAPTION_1} color={TEXT.TERTIARY}>
                    {(trainer?.name ?? '') + ' \u00B7 ' + workout.duration + ' min \u00B7 ' + workout.level}
                  </StyledText>
                </View>
                <Ionicons name="play-circle" size={32} color={BRAND.PRIMARY} />
              </Pressable>
            )
          })}
        </View>
      </ScrollView>
    </View>
  )
}

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

const COLLECTION_CARD_WIDTH = (SCREEN_WIDTH - LAYOUT.SCREEN_PADDING * 2 - SPACING[3]) / 2

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: DARK.BASE,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: LAYOUT.SCREEN_PADDING,
  },

  // Featured Collection
  featuredCard: {
    height: 200,
    borderRadius: RADIUS.GLASS_CARD,
    overflow: 'hidden',
    marginBottom: SPACING[8],
    marginTop: SPACING[4],
    ...SHADOW.lg,
  },
  featuredBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    paddingHorizontal: SPACING[2],
    paddingVertical: SPACING[1],
    borderRadius: RADIUS.SM,
    alignSelf: 'flex-start',
    margin: SPACING[4],
    gap: SPACING[1],
  },
  featuredBadgeText: {
    fontSize: 11,
    fontWeight: 'bold',
    color: TEXT.PRIMARY,
  },
  featuredInfo: {
    position: 'absolute',
    bottom: SPACING[5],
    left: SPACING[5],
    right: SPACING[5],
  },
  featuredStats: {
    flexDirection: 'row',
    gap: SPACING[4],
    marginTop: SPACING[3],
  },
  featuredStat: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING[1],
  },

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

  // Collections Grid
  collectionsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: SPACING[3],
    marginTop: SPACING[3],
  },
  collectionCard: {
    width: COLLECTION_CARD_WIDTH,
    paddingVertical: SPACING[4],
    paddingHorizontal: SPACING[3],
    borderRadius: RADIUS.LG,
    overflow: 'hidden',
    borderWidth: 1,
    borderColor: 'rgba(255, 255, 255, 0.1)',
    gap: SPACING[1],
  },
  collectionIconBg: {
    width: 44,
    height: 44,
    borderRadius: 12,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: SPACING[2],
  },
  collectionEmoji: {
    fontSize: 22,
  },

  // Programs
  programsScroll: {
    gap: SPACING[3],
  },
  programCard: {
    width: 200,
    height: 140,
    borderRadius: RADIUS.LG,
    overflow: 'hidden',
    padding: SPACING[4],
    borderWidth: 1,
    borderColor: 'rgba(255, 255, 255, 0.1)',
  },
  programHeader: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginBottom: SPACING[2],
  },
  programLevelBadge: {
    backgroundColor: 'rgba(255, 107, 53, 0.2)',
    paddingHorizontal: SPACING[2],
    paddingVertical: SPACING[1],
    borderRadius: RADIUS.SM,
  },
  programMeta: {
    flexDirection: 'row',
    gap: SPACING[3],
    marginTop: SPACING[3],
  },
  programMetaItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: SPACING[1],
  },

  // New Releases
  releaseRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: SPACING[3],
    paddingHorizontal: SPACING[4],
    backgroundColor: DARK.SURFACE,
    borderRadius: RADIUS.LG,
    marginBottom: SPACING[2],
    gap: SPACING[3],
  },
  releaseAvatar: {
    width: 44,
    height: 44,
    borderRadius: 22,
    alignItems: 'center',
    justifyContent: 'center',
  },
  releaseInitial: {
    fontSize: 18,
    fontWeight: '700',
    color: TEXT.PRIMARY,
  },
  releaseInfo: {
    flex: 1,
    gap: 2,
  },
})
