import React, {useState, useMemo} from 'react';
import {
  FlatList,
  Image,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../common/TVTouchable';
import {Video} from '../../api/addonTypes';
import {colors, typography} from '../../utils/colors';
import {IS_TV} from '../../utils/tv';
import {formatDate} from '../../utils/formatters';

interface Props {
  videos: Video[];
  onSelectEpisode: (video: Video) => void;
  currentVideoId?: string;
}

export default function EpisodeList({videos, onSelectEpisode, currentVideoId}: Props) {
  const seasons = useMemo(() => {
    const map = new Map<number, Video[]>();
    for (const v of videos) {
      const s = v.season ?? 1;
      if (!map.has(s)) map.set(s, []);
      map.get(s)!.push(v);
    }
    return Array.from(map.entries()).sort(([a], [b]) => a - b);
  }, [videos]);

  const [selectedSeason, setSelectedSeason] = useState<number>(
    seasons[0]?.[0] ?? 1,
  );

  const currentEpisodes = useMemo(
    () =>
      seasons.find(([s]) => s === selectedSeason)?.[1]?.sort(
        (a, b) => (a.episode ?? 0) - (b.episode ?? 0),
      ) ?? [],
    [seasons, selectedSeason],
  );

  return (
    <View style={styles.container}>
      {/* Season selector */}
      <FlatList
        data={seasons}
        horizontal
        showsHorizontalScrollIndicator={false}
        keyExtractor={([s]) => String(s)}
        contentContainerStyle={styles.seasonList}
        renderItem={({item: [seasonNum]}) => (
          <TouchableOpacity
            style={[
              styles.seasonChip,
              selectedSeason === seasonNum && styles.seasonChipActive,
            ]}
            onPress={() => setSelectedSeason(seasonNum)}
            focusable={IS_TV || undefined}>
            <Text
              style={[
                styles.seasonText,
                selectedSeason === seasonNum && styles.seasonTextActive,
              ]}>
              Season {seasonNum}
            </Text>
          </TouchableOpacity>
        )}
      />

      {/* Episodes */}
      <FlatList
        data={currentEpisodes}
        keyExtractor={v => v.id}
        scrollEnabled={false}
        renderItem={({item: video}) => {
          const isActive = video.id === currentVideoId;
          return (
            <TouchableOpacity
              style={[styles.episode, isActive && styles.episodeActive]}
              onPress={() => onSelectEpisode(video)}
              focusable={IS_TV || undefined}>
              {video.thumbnail ? (
                <Image
                  style={styles.thumbnail}
                  source={{uri: video.thumbnail}}
                  resizeMode="cover"
                />
              ) : (
                <View style={[styles.thumbnail, styles.thumbnailPlaceholder]}>
                  <Text style={styles.epNumber}>
                    {video.episode}
                  </Text>
                </View>
              )}
              <View style={styles.epInfo}>
                <Text style={styles.epTitle} numberOfLines={1}>
                  {video.episode}. {video.title}
                </Text>
                {video.released && (
                  <Text style={styles.epDate}>{formatDate(video.released)}</Text>
                )}
                {video.overview && (
                  <Text style={styles.epOverview} numberOfLines={2}>
                    {video.overview}
                  </Text>
                )}
              </View>
            </TouchableOpacity>
          );
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {paddingBottom: 16},
  seasonList: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    gap: 8,
  },
  seasonChip: {
    paddingHorizontal: 14,
    paddingVertical: 7,
    borderRadius: 20,
    backgroundColor: colors.surfaceLight,
    marginRight: 8,
  },
  seasonChipActive: {backgroundColor: colors.primary},
  seasonText: {...typography.caption, color: colors.textSecondary},
  seasonTextActive: {color: colors.textPrimary, fontWeight: '600'},
  episode: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 10,
    gap: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: colors.border,
  },
  episodeActive: {backgroundColor: colors.surfaceLight},
  thumbnail: {
    width: 100,
    height: 60,
    borderRadius: 6,
  },
  thumbnailPlaceholder: {
    backgroundColor: colors.surfaceHighlight,
    justifyContent: 'center',
    alignItems: 'center',
  },
  epNumber: {...typography.title, color: colors.textMuted},
  epInfo: {flex: 1},
  epTitle: {...typography.body, color: colors.textPrimary, fontWeight: '600'},
  epDate: {...typography.caption, color: colors.textMuted, marginTop: 2},
  epOverview: {...typography.caption, color: colors.textSecondary, marginTop: 4},
});
