/**
 * WorkoutCard - Dark Medical workout card
 * Flat navy surface with border-dim, no glassmorphism
 */

import { useMemo, useRef, useCallback } from 'react'
import {
  View,
  StyleSheet,
  Pressable,
  Animated,
  ImageBackground,
  useWindowDimensions,
  Text as RNText,
  ViewStyle,
} from 'react-native'
import { LinearGradient } from 'expo-linear-gradient'
import { Icon } from './Icon'

import { useThemeColors } from '@/src/shared/theme'
import { BRAND, GRADIENTS, TEXT, NAVY, BORDER_COLORS, PHASE } from '@/src/shared/constants/colors'
import { FONT_FAMILY_SANS_SEMIBOLD } from '@/src/shared/constants/typography'
import type { ThemeColors } from '@/src/shared/theme/types'
import { RADIUS } from '@/src/shared/constants/borderRadius'
import { SPACING } from '@/src/shared/constants/spacing'
import { StyledText } from './StyledText'
import type { Workout, WorkoutCategory } from '@/src/shared/types'

const AnimatedPressable = Animated.createAnimatedComponent(Pressable)

export type WorkoutCardVariant = 'horizontal' | 'grid' | 'featured'

interface WorkoutCardProps {
  workout: Workout
  variant?: WorkoutCardVariant
  onPress?: () => void
  title?: string
  metadata?: string
  trainerName?: string
  isLocked?: boolean
}

export const CATEGORY_COLORS: Record<WorkoutCategory, string> = {
  'full-body': BRAND.PRIMARY,
  'core': BRAND.INFO,
  'upper-body': TEXT.SECONDARY,
  'lower-body': BRAND.PRIMARY,
  'cardio': PHASE.PREP,
}

const CATEGORY_LABELS: Record<WorkoutCategory, string> = {
  'full-body': 'Full Body',
  'core': 'Core',
  'upper-body': 'Upper Body',
  'lower-body': 'Lower Body',
  'cardio': 'Cardio',
}

function getVariantDimensions(variant: WorkoutCardVariant, screenWidth: number): ViewStyle {
  switch (variant) {
    case 'featured':
      return {
        width: screenWidth - SPACING[6] * 2,
        height: 320,
      }
    case 'horizontal':
      return {
        width: 200,
        height: 280,
      }
    case 'grid':
    default:
      return {
        flex: 1,
        aspectRatio: 0.75,
      }
  }
}

export function WorkoutCard({
  workout,
  variant = 'horizontal',
  onPress,
  title,
  metadata,
  trainerName,
  isLocked,
}: WorkoutCardProps) {
  const colors = useThemeColors()
  const { width: screenWidth } = useWindowDimensions()
  const styles = useMemo(() => createStyles(colors), [colors])
  const dimensions = useMemo(() => getVariantDimensions(variant, screenWidth), [variant, screenWidth])

  // Press animation
  const scaleValue = useRef(new Animated.Value(1)).current
  const handlePressIn = useCallback(() => {
    Animated.spring(scaleValue, {
      toValue: 0.97,
      useNativeDriver: true,
      speed: 50,
      bounciness: 4,
    }).start()
  }, [scaleValue])
  const handlePressOut = useCallback(() => {
    Animated.spring(scaleValue, {
      toValue: 1,
      useNativeDriver: true,
      speed: 30,
      bounciness: 6,
    }).start()
  }, [scaleValue])

  const displayTitle = title ?? workout.title
  const metaParts = [
    `${workout.duration} min`,
    `${workout.calories} cal`,
    ...(trainerName ? [trainerName] : []),
  ]
  const displayMetadata = metadata ?? metaParts.join(' · ')
  const categoryColor = CATEGORY_COLORS[workout.category]

  return (
    <AnimatedPressable
      style={[styles.container, dimensions, { transform: [{ scale: scaleValue }] }]}
      onPress={onPress}
      onPressIn={handlePressIn}
      onPressOut={handlePressOut}
    >
      {/* Background Image */}
      <ImageBackground
        source={workout.thumbnailUrl ? { uri: workout.thumbnailUrl } : undefined}
        style={StyleSheet.absoluteFill}
        imageStyle={{ borderRadius: RADIUS.LG }}
        resizeMode="cover"
      >
        {/* Dark overlay for text readability */}
        <LinearGradient
          colors={GRADIENTS.CARD_OVERLAY}
          style={StyleSheet.absoluteFill}
        />
      </ImageBackground>

      {/* Category Badge — flat navy */}
      <View style={[styles.categoryBadge, { backgroundColor: `${categoryColor}20`, borderColor: `${categoryColor}40` }]}>
        <RNText style={[styles.categoryText, { color: categoryColor }]}>
          {CATEGORY_LABELS[workout.category]}
        </RNText>
      </View>

      {/* Play Button — flat navy circle */}
      <View style={styles.playButtonContainer}>
        <View style={styles.playButton}>
          <Icon name={isLocked ? 'lock.fill' : 'play.fill'} size={24} tintColor={TEXT.PRIMARY} style={isLocked ? undefined : { marginLeft: 2 }} />
        </View>
      </View>

      {/* Content at Bottom */}
      <View style={styles.content}>
        <StyledText
          preset={variant === 'featured' ? 'TITLE_2' : 'HEADLINE'}
          color={TEXT.PRIMARY}
          numberOfLines={2}
          style={styles.title}
        >
          {displayTitle}
        </StyledText>
        <StyledText
          preset="CARD_METADATA"
          color={TEXT.SECONDARY}
          numberOfLines={1}
        >
          {displayMetadata}
        </StyledText>
      </View>
    </AnimatedPressable>
  )
}

function createStyles(_colors: ThemeColors) {
  return StyleSheet.create({
    container: {
      borderRadius: RADIUS.LG,
      borderCurve: 'continuous',
      overflow: 'hidden',
      backgroundColor: NAVY[800],
      borderWidth: 1,
      borderColor: BORDER_COLORS.DIM,
    },
    categoryBadge: {
      position: 'absolute',
      top: SPACING[3],
      left: SPACING[3],
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: SPACING[3],
      paddingVertical: SPACING[1],
      borderRadius: RADIUS.SM,
      borderCurve: 'continuous',
      borderWidth: 1,
      overflow: 'hidden',
    },
    categoryText: {
      fontSize: 11,
      fontFamily: FONT_FAMILY_SANS_SEMIBOLD,
    },
    playButtonContainer: {
      ...StyleSheet.absoluteFillObject,
      justifyContent: 'center',
      alignItems: 'center',
    },
    playButton: {
      width: 56,
      height: 56,
      borderRadius: RADIUS.FULL,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'rgba(17,34,64,0.7)', // Semi-transparent NAVY[800] overlay
      borderWidth: 1,
      borderColor: BORDER_COLORS.DIM,
    },
    content: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      padding: SPACING[4],
    },
    title: {
      marginBottom: SPACING[1],
    },
  })
}
