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

import { View, StyleSheet, ScrollView, Pressable, Dimensions, Text as RNText, Image as RNImage } 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 { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useHaptics } from '@/src/shared/hooks'
import { useUserStore, useActivityStore } from '@/src/shared/stores'
import {
  getFeaturedWorkouts,
  getPopularWorkouts,
  COLLECTIONS,
  WORKOUTS,
} from '@/src/shared/data'
import { useTranslatedWorkouts, useTranslatedCollections } 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

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

// ═══════════════════════════════════════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════════════════════════════════════

function PrimaryButton({ children, onPress }: { children: string; onPress?: () => void }) {
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  return (
    <Pressable style={styles.primaryButton} onPress={onPress}>
      <Ionicons name="play" size={16} color="#FFFFFF" style={styles.buttonIcon} />
      <RNText style={styles.primaryButtonText}>{children}</RNText>
    </Pressable>
  )
}

function PlainButton({ children, onPress }: { children: string; onPress?: () => void }) {
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  return (
    <Pressable onPress={onPress}>
      <RNText style={styles.plainButtonText}>{children}</RNText>
    </Pressable>
  )
}

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

export default function HomeScreen() {
  const { t } = useTranslation()
  const insets = useSafeAreaInsets()
  const router = useRouter()
  const haptics = useHaptics()
  const colors = useThemeColors()
  const styles = useMemo(() => createStyles(colors), [colors])
  const userName = useUserStore((s) => s.profile.name)
  const history = useActivityStore((s) => s.history)
  const recentWorkouts = useMemo(() => history.slice(0, 3), [history])

  const featured = getFeaturedWorkouts()[0] ?? WORKOUTS[0]
  const popular = getPopularWorkouts(4)
  const translatedPopular = useTranslatedWorkouts(popular)
  const translatedCollections = useTranslatedCollections(COLLECTIONS)

  const greeting = (() => {
    const hour = new Date().getHours()
    if (hour < 12) return t('greetings.morning')
    if (hour < 18) return t('greetings.afternoon')
    return t('greetings.evening')
  })()

  const featuredTitle = t(`content:workouts.${featured.id}`, { defaultValue: featured.title })

  const handleWorkoutPress = (id: string) => {
    haptics.buttonTap()
    router.push(`/workout/${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}>
          <View style={{ flex: 1, marginRight: SPACING[3] }}>
            <StyledText size={FONTS.SUBHEADLINE} color={colors.text.tertiary}>
              {greeting}
            </StyledText>
            <StyledText
              size={FONTS.LARGE_TITLE}
              weight="bold"
              color={colors.text.primary}
              numberOfLines={1}
            >
              {userName}
            </StyledText>
          </View>
          <Pressable style={styles.profileButton}>
            <Ionicons name="person-circle-outline" size={32} color={colors.text.primary} />
          </Pressable>
        </View>

        {/* Featured */}
        <Pressable
          style={styles.featuredCard}
          onPress={() => handleWorkoutPress(featured.id)}
        >
          {featured.thumbnailUrl ? (
            <RNImage
              source={{ uri: featured.thumbnailUrl }}
              style={StyleSheet.absoluteFill}
              resizeMode="cover"
            />
          ) : (
            <LinearGradient
              colors={[BRAND.PRIMARY, BRAND.PRIMARY_DARK]}
              style={StyleSheet.absoluteFill}
            />
          )}
          <LinearGradient
            colors={GRADIENTS.VIDEO_OVERLAY}
            style={StyleSheet.absoluteFill}
          />

          <View style={styles.featuredBadge}>
            <RNText style={styles.featuredBadgeText}>{'🔥 ' + t('screens:home.featured')}</RNText>
          </View>

          <View style={styles.featuredContent}>
            <StyledText size={FONTS.TITLE} weight="bold" color="#FFFFFF">
              {featuredTitle}
            </StyledText>
            <StyledText size={FONTS.SUBHEADLINE} color="rgba(255,255,255,0.8)">
              {t('workoutMeta', { duration: featured.duration, level: t(`levels.${featured.level.toLowerCase()}`), calories: featured.calories })}
            </StyledText>

            <View style={styles.featuredButtons}>
              <PrimaryButton onPress={() => handleWorkoutPress(featured.id)}>{t('start')}</PrimaryButton>
              <Pressable style={styles.saveButton}>
                <Ionicons name="heart-outline" size={24} color="#FFFFFF" />
              </Pressable>
            </View>
          </View>
        </Pressable>

        {/* Continue Watching — from activity store */}
        {recentWorkouts.length > 0 && (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <StyledText size={FONTS.TITLE_2} weight="semibold" color={colors.text.primary}>{t('screens:home.recent')}</StyledText>
              <PlainButton>{t('seeAll')}</PlainButton>
            </View>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              contentContainerStyle={styles.horizontalScroll}
            >
              {recentWorkouts.map((result) => {
                const workout = WORKOUTS.find(w => w.id === result.workoutId)
                if (!workout) return null
                const workoutTitle = t(`content:workouts.${workout.id}`, { defaultValue: workout.title })
                return (
                  <Pressable
                    key={result.id}
                    style={styles.continueCard}
                    onPress={() => handleWorkoutPress(result.workoutId)}
                  >
                    <View style={styles.continueThumb}>
                      <LinearGradient
                        colors={[BRAND.PRIMARY, BRAND.PRIMARY_LIGHT]}
                        style={StyleSheet.absoluteFill}
                      />
                      <Ionicons name="flame" size={32} color="#FFFFFF" />
                    </View>
                    <StyledText size={FONTS.SUBHEADLINE} weight="semibold" color={colors.text.primary}>{workoutTitle}</StyledText>
                    <StyledText size={FONTS.CAPTION_2} color={colors.text.tertiary}>
                      {t('calMin', { calories: result.calories, duration: result.durationMinutes })}
                    </StyledText>
                  </Pressable>
                )
              })}
            </ScrollView>
          </View>
        )}

        {/* Popular This Week */}
        <View style={styles.section}>
          <StyledText size={FONTS.TITLE_2} weight="semibold" color={colors.text.primary}>{t('screens:home.popularThisWeek')}</StyledText>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.horizontalScroll}
          >
            {translatedPopular.map((item) => (
              <Pressable
                key={item.id}
                style={styles.popularCard}
                onPress={() => handleWorkoutPress(item.id)}
              >
                <View style={styles.popularThumb}>
                  <Ionicons name="flame" size={24} color={BRAND.PRIMARY} />
                </View>
                <StyledText size={FONTS.SUBHEADLINE} weight="medium" color={colors.text.primary}>{item.title}</StyledText>
                <StyledText size={FONTS.CAPTION_2} color={colors.text.tertiary}>{t('units.minUnit', { count: item.duration })}</StyledText>
              </Pressable>
            ))}
          </ScrollView>
        </View>

        {/* Collections */}
        <View style={styles.section}>
          <StyledText size={FONTS.TITLE_2} weight="semibold" color={colors.text.primary}>{t('screens:home.collections')}</StyledText>
          {translatedCollections.map((item) => (
            <Pressable key={item.id} style={styles.collectionCard} onPress={() => { haptics.buttonTap(); router.push(`/collection/${item.id}`) }}>
              <BlurView intensity={colors.glass.blurMedium} tint={colors.glass.blurTint} style={StyleSheet.absoluteFill} />
              <View style={styles.collectionContent}>
                <RNText style={styles.collectionIcon}>{item.icon}</RNText>
                <View style={styles.collectionText}>
                  <StyledText size={FONTS.HEADLINE} weight="semibold" color={colors.text.primary}>{item.title}</StyledText>
                  <StyledText size={FONTS.CAPTION_1} color={colors.text.tertiary}>
                    {t('plurals.workout', { count: item.workoutIds.length }) + ' \u00B7 ' + item.description}
                  </StyledText>
                </View>
                <Ionicons name="chevron-forward" size={20} color={colors.text.tertiary} />
              </View>
            </Pressable>
          ))}
        </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: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: SPACING[6],
    },
    profileButton: {
      width: 40,
      height: 40,
      alignItems: 'center',
      justifyContent: 'center',
    },

    // Buttons
    primaryButton: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: BRAND.PRIMARY,
      paddingHorizontal: SPACING[4],
      paddingVertical: SPACING[3],
      borderRadius: RADIUS.SM,
    },
    buttonIcon: {
      marginRight: SPACING[2],
    },
    primaryButtonText: {
      fontSize: 14,
      fontWeight: '600',
      color: '#FFFFFF',
    },
    plainButtonText: {
      fontSize: FONTS.BODY,
      color: BRAND.PRIMARY,
    },

    // Featured
    featuredCard: {
      width: CARD_WIDTH,
      height: 220,
      borderRadius: RADIUS.GLASS_CARD,
      overflow: 'hidden',
      marginBottom: SPACING[8],
      ...colors.shadow.lg,
    },
    featuredBadge: {
      position: 'absolute',
      top: SPACING[4],
      left: SPACING[4],
      backgroundColor: 'rgba(255, 255, 255, 0.15)',
      paddingHorizontal: SPACING[3],
      paddingVertical: SPACING[1],
      borderRadius: RADIUS.SM,
      borderWidth: 1,
      borderColor: 'rgba(255, 255, 255, 0.2)',
    },
    featuredBadgeText: {
      fontSize: 11,
      fontWeight: 'bold',
      color: '#FFFFFF',
    },
    featuredContent: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      padding: SPACING[5],
    },
    featuredButtons: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: SPACING[3],
      marginTop: SPACING[4],
    },
    saveButton: {
      width: 44,
      height: 44,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
      borderRadius: 22,
      borderWidth: 1,
      borderColor: 'rgba(255, 255, 255, 0.15)',
    },

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

    // Continue Card
    continueCard: {
      width: 140,
    },
    continueThumb: {
      width: 140,
      height: 200,
      borderRadius: RADIUS.LG,
      overflow: 'hidden',
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: SPACING[2],
    },

    // Popular Card
    popularCard: {
      width: 120,
    },
    popularThumb: {
      width: 120,
      height: 120,
      borderRadius: RADIUS.LG,
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: SPACING[2],
      borderWidth: 1,
      borderColor: colors.border.glass,
      backgroundColor: colors.bg.overlay1,
    },

    // Collection Card
    collectionCard: {
      height: 80,
      borderRadius: RADIUS.LG,
      overflow: 'hidden',
      marginBottom: SPACING[3],
      borderWidth: 1,
      borderColor: colors.border.glass,
    },
    collectionContent: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: SPACING[5],
    },
    collectionIcon: {
      fontSize: 28,
      marginRight: SPACING[4],
    },
    collectionText: {
      flex: 1,
    },
  })
}
