import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {AddonStreamResult} from '../../api/addonTypes';
import {colors, typography} from '../../utils/colors';
import StreamItem from './StreamItem';
import LoadingSpinner from '../common/LoadingSpinner';

interface Props {
  results: AddonStreamResult[];
  loading: boolean;
  onSelectStream: (result: AddonStreamResult, streamIdx: number) => void;
}

export default function StreamList({results, loading, onSelectStream}: Props) {
  const allStreams = results.flatMap((r, ri) =>
    r.streams.map((s, si) => ({result: r, stream: s, ri, si})),
  );

  if (loading) return <LoadingSpinner />;

  if (allStreams.length === 0) {
    return (
      <View style={styles.empty}>
        <Icon name="movie-off" size={48} color={colors.textMuted} />
        <Text style={styles.emptyText}>
          No streams found. Install a stream provider addon.
        </Text>
      </View>
    );
  }

  return (
    <View>
      {allStreams.map(({result, stream, ri, si}) => (
        <StreamItem
          key={`${ri}-${si}`}
          stream={stream}
          addon={result.addon}
          isDebridCached={result.isDebridCached}
          onPress={() => onSelectStream(result, si)}
        />
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  empty: {
    alignItems: 'center',
    paddingVertical: 40,
    gap: 12,
    paddingHorizontal: 24,
  },
  emptyText: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
  },
});
