import React, {memo} from 'react';
import {
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withSpring,
} from 'react-native-reanimated';
import {MetaPreview} from '../../api/addonTypes';
import {colors, typography} from '../../utils/colors';
import {getPosterDimensions} from '../../utils/dimensions';
import {formatYear, formatRating} from '../../utils/formatters';
import {useTVFocus} from '../../hooks/useTVFocus';

interface CardProps {
  item: MetaPreview;
  onPress: (item: MetaPreview) => void;
  size?: 'small' | 'medium' | 'large';
  width?: number;
  style?: ViewStyle;
}

const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);

const Card = memo(function Card({item, onPress, size = 'medium', width: overrideWidth, style}: CardProps) {
  const scale = useSharedValue(1);
  const dims = getPosterDimensions(item.posterShape, size);
  const width = overrideWidth ?? dims.width;
  // Maintain aspect ratio when width is overridden
  const height = overrideWidth
    ? Math.round(overrideWidth * (dims.height / dims.width))
    : dims.height;
  const {focusProps, focusStyle} = useTVFocus();

  const animStyle = useAnimatedStyle(() => ({
    transform: [{scale: scale.value}],
  }));

  const handlePressIn = () => {
    scale.value = withSpring(0.94, {damping: 18, stiffness: 350});
  };

  const handlePressOut = () => {
    scale.value = withSpring(1, {damping: 18, stiffness: 350});
  };

  return (
    <AnimatedTouchable
      style={[animStyle, style]}
      onPress={() => onPress(item)}
      onPressIn={handlePressIn}
      onPressOut={handlePressOut}
      activeOpacity={1}
      {...focusProps}>
      <View style={[styles.card, {width}]}>
        <View style={[styles.posterContainer, {width, height}, focusStyle]}>
          {item.poster ? (
            <>
              <Image
                style={styles.poster}
                source={{uri: item.poster}}
                resizeMode="cover"
              />
              {/* Bottom gradient for title legibility */}
              <LinearGradient
                colors={['transparent', 'rgba(6,11,20,0.85)']}
                locations={[0.55, 1]}
                style={StyleSheet.absoluteFillObject}
              />
            </>
          ) : (
            <View style={[styles.poster, styles.posterPlaceholder]}>
              <Text style={styles.placeholderLetter}>
                {item.name?.[0]?.toUpperCase() ?? '?'}
              </Text>
              <Text style={styles.placeholderText} numberOfLines={2}>
                {item.name}
              </Text>
            </View>
          )}

          {/* IMDb rating badge */}
          {item.imdbRating && (
            <View style={styles.ratingBadge}>
              <Text style={styles.ratingText}>★ {formatRating(item.imdbRating)}</Text>
            </View>
          )}

          {/* Type badge */}
          {item.type === 'series' && (
            <View style={styles.typeBadge}>
              <Text style={styles.typeBadgeText}>TV</Text>
            </View>
          )}
        </View>

        <Text style={styles.title} numberOfLines={1}>
          {item.name}
        </Text>
        {item.releaseInfo && (
          <Text style={styles.year}>{formatYear(item.releaseInfo)}</Text>
        )}
      </View>
    </AnimatedTouchable>
  );
});

export default Card;

const styles = StyleSheet.create({
  card: {
    marginRight: 10,
  },
  posterContainer: {
    borderRadius: 10,
    overflow: 'hidden',
    backgroundColor: colors.surfaceLight,
    marginBottom: 6,
    elevation: 6,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 4},
    shadowOpacity: 0.35,
    shadowRadius: 6,
  },
  poster: {
    width: '100%',
    height: '100%',
  },
  posterPlaceholder: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 8,
    backgroundColor: colors.surfaceHighlight,
    gap: 6,
  },
  placeholderLetter: {
    fontSize: 28,
    fontWeight: '800',
    color: colors.primary,
    opacity: 0.8,
  },
  placeholderText: {
    ...typography.caption,
    color: colors.textMuted,
    textAlign: 'center',
  },
  ratingBadge: {
    position: 'absolute',
    bottom: 6,
    left: 6,
    backgroundColor: 'rgba(0,0,0,0.8)',
    paddingHorizontal: 5,
    paddingVertical: 2,
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: colors.imdbYellow + '50',
  },
  ratingText: {
    fontSize: 9,
    fontWeight: '700',
    color: colors.imdbYellow,
  },
  typeBadge: {
    position: 'absolute',
    top: 6,
    right: 6,
    backgroundColor: 'rgba(108,79,240,0.85)',
    paddingHorizontal: 5,
    paddingVertical: 2,
    borderRadius: 4,
  },
  typeBadgeText: {
    fontSize: 9,
    fontWeight: '800',
    color: '#fff',
    letterSpacing: 0.5,
  },
  title: {
    ...typography.caption,
    color: colors.textPrimary,
    fontWeight: '500',
    marginBottom: 1,
  },
  year: {
    fontSize: 11,
    color: colors.textMuted,
  },
});
