/**
 * TabataFit Activity Screen
 * React Native + SwiftUI Islands — wired to shared data
 */

import { View, StyleSheet, ScrollView, Dimensions, Text as RNText } from 'react-native'
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 {
  Host,
  Gauge,
  Text,
  HStack,
  VStack,
  Chart,
  List,
} from '@expo/ui/swift-ui'

import { useMemo } from 'react'
import { useActivityStore, getWeeklyActivity } from '@/src/shared/stores'
import { getWorkoutById } from '@/src/shared/data'
import { ACHIEVEMENTS } from '@/src/shared/data'
import { StyledText } from '@/src/shared/components/StyledText'

import {
  BRAND,
  DARK,
  TEXT as TEXT_COLORS,
  GLASS,
  GRADIENTS,
} 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_2: 22,
  SUBHEADLINE: 15,
  CAPTION_1: 12,
}

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

export default function ActivityScreen() {
  const insets = useSafeAreaInsets()
  const streak = useActivityStore((s) => s.streak)
  const history = useActivityStore((s) => s.history)
  const totalWorkouts = history.length
  const totalMinutes = useMemo(() => history.reduce((sum, r) => sum + r.durationMinutes, 0), [history])
  const totalCalories = useMemo(() => history.reduce((sum, r) => sum + r.calories, 0), [history])
  const recentWorkouts = useMemo(() => history.slice(0, 3), [history])
  const weeklyActivity = useMemo(() => getWeeklyActivity(history), [history])

  // Check achievements
  const unlockedAchievements = ACHIEVEMENTS.filter(a => {
    switch (a.type) {
      case 'workouts': return totalWorkouts >= a.requirement
      case 'streak': return streak.longest >= a.requirement
      case 'minutes': return totalMinutes >= a.requirement
      case 'calories': return totalCalories >= a.requirement
      default: return false
    }
  })
  const displayAchievements = ACHIEVEMENTS.slice(0, 5).map(a => ({
    ...a,
    unlocked: unlockedAchievements.some(u => u.id === a.id),
  }))

  // Format recent workout dates
  const formatDate = (timestamp: number) => {
    const now = Date.now()
    const diff = now - timestamp
    if (diff < 86400000) return 'Today'
    if (diff < 172800000) return 'Yesterday'
    return Math.floor(diff / 86400000) + ' days ago'
  }

  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_COLORS.PRIMARY}>Activity</StyledText>

        {/* Streak Banner */}
        <View style={styles.streakBanner}>
          <LinearGradient
            colors={GRADIENTS.CTA}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={StyleSheet.absoluteFill}
          />
          <View style={styles.streakContent}>
            <Ionicons name="flame" size={32} color={TEXT_COLORS.PRIMARY} />
            <View style={styles.streakText}>
              <StyledText size={FONTS.TITLE_2} weight="bold" color={TEXT_COLORS.PRIMARY}>
                {(streak.current || 0) + ' Day Streak'}
              </StyledText>
              <StyledText size={FONTS.SUBHEADLINE} color={TEXT_COLORS.SECONDARY}>
                {streak.current > 0 ? 'Keep it going!' : 'Start your streak today!'}
              </StyledText>
            </View>
          </View>
        </View>

        {/* SwiftUI Island: Stats Gauges */}
        <Host matchContents useViewportSizeMeasurement colorScheme="dark" style={styles.statsIsland}>
          <HStack spacing={12}>
            <VStack spacing={4}>
              <Gauge
                type="circularCapacity"
                current={{ value: Math.min(totalWorkouts / 100, 1), label: String(totalWorkouts) }}
                color={BRAND.PRIMARY}
              />
              <Text size={11} color={TEXT_COLORS.TERTIARY}>Workouts</Text>
            </VStack>
            <VStack spacing={4}>
              <Gauge
                type="circularCapacity"
                current={{ value: Math.min(totalMinutes / 300, 1), label: String(totalMinutes) }}
                color="#5AC8FA"
              />
              <Text size={11} color={TEXT_COLORS.TERTIARY}>Minutes</Text>
            </VStack>
            <VStack spacing={4}>
              <Gauge
                type="circularCapacity"
                current={{ value: Math.min(totalCalories / 5000, 1), label: String(totalCalories) }}
                color="#FFD60A"
              />
              <Text size={11} color={TEXT_COLORS.TERTIARY}>Calories</Text>
            </VStack>
            <VStack spacing={4}>
              <Gauge
                type="circularCapacity"
                current={{ value: Math.min(streak.longest / 30, 1), label: String(streak.longest) }}
                color="#30D158"
              />
              <Text size={11} color={TEXT_COLORS.TERTIARY}>Best Streak</Text>
            </VStack>
          </HStack>
        </Host>

        {/* SwiftUI Island: This Week Chart */}
        <View style={styles.section}>
          <StyledText size={FONTS.TITLE_2} weight="semibold" color={TEXT_COLORS.PRIMARY}>This Week</StyledText>
          <Host matchContents useViewportSizeMeasurement colorScheme="dark" style={styles.chartIsland}>
            <Chart
              type="bar"
              data={weeklyActivity.map(d => ({
                x: d.date,
                y: d.completed ? 1 : 0,
                color: d.completed ? BRAND.PRIMARY : '#333333',
              }))}
              barStyle={{ cornerRadius: 4 }}
              style={{ height: 160 }}
            />
          </Host>
        </View>

        {/* SwiftUI Island: Recent Workouts */}
        {recentWorkouts.length > 0 && (
          <View style={styles.section}>
            <StyledText size={FONTS.TITLE_2} weight="semibold" color={TEXT_COLORS.PRIMARY}>Recent</StyledText>
            <Host useViewportSizeMeasurement colorScheme="dark" style={{ height: 44 * recentWorkouts.length + 55 }}>
              <List listStyle="insetGrouped" scrollEnabled={false}>
                {recentWorkouts.map((result) => {
                  const workout = getWorkoutById(result.workoutId)
                  return (
                    <HStack key={result.id} spacing={12}>
                      <Text color={BRAND.PRIMARY} weight="bold">{workout?.title ?? 'Workout'}</Text>
                      <Text size={13} color={TEXT_COLORS.TERTIARY}>{formatDate(result.completedAt)}</Text>
                      <Text size={13} color={TEXT_COLORS.PRIMARY}>{result.durationMinutes + ' min'}</Text>
                      <Text size={13} color={BRAND.PRIMARY}>{result.calories + ' cal'}</Text>
                    </HStack>
                  )
                })}
              </List>
            </Host>
          </View>
        )}

        {/* Achievements */}
        <View style={styles.section}>
          <StyledText size={FONTS.TITLE_2} weight="semibold" color={TEXT_COLORS.PRIMARY}>Achievements</StyledText>
          <View style={styles.achievementsGrid}>
            {displayAchievements.map((achievement) => (
              <View
                key={achievement.id}
                style={[styles.achievementBadge, !achievement.unlocked && styles.achievementLocked]}
              >
                <BlurView intensity={GLASS.BLUR_LIGHT} tint="dark" style={StyleSheet.absoluteFill} />
                <View style={[styles.achievementIcon, !achievement.unlocked && styles.achievementIconLocked]}>
                  <Ionicons
                    name={achievement.unlocked ? 'trophy' : 'lock-closed'}
                    size={24}
                    color={achievement.unlocked ? BRAND.PRIMARY : TEXT_COLORS.TERTIARY}
                  />
                </View>
                <StyledText
                  size={FONTS.CAPTION_1}
                  weight={achievement.unlocked ? 'semibold' : 'regular'}
                  color={TEXT_COLORS.PRIMARY}
                >
                  {achievement.title}
                </StyledText>
              </View>
            ))}
          </View>
        </View>
      </ScrollView>
    </View>
  )
}

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

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

  // Streak Banner
  streakBanner: {
    height: 80,
    borderRadius: RADIUS.GLASS_CARD,
    overflow: 'hidden',
    marginBottom: SPACING[6],
    marginTop: SPACING[4],
  },
  streakContent: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: SPACING[5],
    gap: SPACING[4],
  },
  streakText: {
    flex: 1,
  },

  // Stats Island
  statsIsland: {
    marginBottom: SPACING[8],
  },

  // Chart Island
  chartIsland: {
    marginTop: SPACING[2],
  },

  // Section
  section: {
    marginBottom: SPACING[6],
  },

  // Achievements
  achievementsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: SPACING[3],
  },
  achievementBadge: {
    width: (SCREEN_WIDTH - LAYOUT.SCREEN_PADDING * 2 - SPACING[3] * 2) / 3,
    aspectRatio: 1,
    borderRadius: RADIUS.LG,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'rgba(255, 255, 255, 0.1)',
    overflow: 'hidden',
  },
  achievementLocked: {
    opacity: 0.5,
  },
  achievementIcon: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: 'rgba(255, 107, 53, 0.15)',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: SPACING[2],
  },
  achievementIconLocked: {
    backgroundColor: 'rgba(255, 255, 255, 0.05)',
  },
})
