import React from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  Image,
} from 'react-native';
import { useTheme } from '../theme/ThemeContext';
import { Track } from '../types';
import { usePlayerControls } from '../hooks/usePlayer';
import { usePlayerStore } from '../store/playerStore';

interface TrackListProps {
  tracks: Track[];
  onTrackPress?: (track: Track, index: number) => void;
  onTrackLongPress?: (track: Track, index: number) => void;
  showIndex?: boolean;
  emptyMessage?: string;
}

export function TrackList({
  tracks,
  onTrackPress,
  onTrackLongPress,
  showIndex = false,
  emptyMessage = 'No tracks',
}: TrackListProps) {
  const { colors } = useTheme();
  const { playQueue } = usePlayerControls();
  const currentTrack = usePlayerStore((s) => s.currentTrack);

  const handlePress = (track: Track, index: number) => {
    if (onTrackPress) {
      onTrackPress(track, index);
    } else {
      // Default: play this track and queue the rest
      playQueue(tracks, index);
    }
  };

  const renderItem = ({ item, index }: { item: Track; index: number }) => {
    const isActive = currentTrack?.id === item.id;

    return (
      <TouchableOpacity
        style={[styles.trackItem, { backgroundColor: colors.surface }]}
        onPress={() => handlePress(item, index)}
        onLongPress={() => onTrackLongPress?.(item, index)}
        activeOpacity={0.7}
      >
        {showIndex && (
          <Text style={[styles.index, { color: colors.textMuted }]}>
            {index + 1}
          </Text>
        )}

        <View style={[styles.artwork, { backgroundColor: colors.surfaceVariant }]}>
          {item.artwork ? (
            <Image source={{ uri: item.artwork }} style={styles.artworkImage} />
          ) : (
            <Text style={[styles.artworkPlaceholder, { color: colors.textMuted }]}>
              {'\u266B'}
            </Text>
          )}
        </View>

        <View style={styles.info}>
          <Text
            style={[
              styles.title,
              { color: isActive ? colors.primary : colors.text },
            ]}
            numberOfLines={1}
          >
            {item.title}
          </Text>
          <Text
            style={[styles.artist, { color: colors.textSecondary }]}
            numberOfLines={1}
          >
            {item.artist || 'Unknown Artist'}
          </Text>
        </View>

        {isActive && (
          <View style={styles.playingIndicator}>
            <Text style={{ color: colors.primary }}>{'\u266B'}</Text>
          </View>
        )}
      </TouchableOpacity>
    );
  };

  if (tracks.length === 0) {
    return (
      <View style={styles.emptyContainer}>
        <Text style={[styles.emptyText, { color: colors.textMuted }]}>
          {emptyMessage}
        </Text>
      </View>
    );
  }

  return (
    <FlatList
      data={tracks}
      renderItem={renderItem}
      keyExtractor={(item) => item.id}
      contentContainerStyle={styles.list}
      showsVerticalScrollIndicator={false}
    />
  );
}

const styles = StyleSheet.create({
  list: {
    paddingBottom: 80, // Space for mini player
  },
  trackItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    marginHorizontal: 12,
    marginVertical: 4,
    borderRadius: 8,
  },
  index: {
    width: 24,
    fontSize: 14,
    textAlign: 'center',
  },
  artwork: {
    width: 48,
    height: 48,
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
  },
  artworkImage: {
    width: '100%',
    height: '100%',
  },
  artworkPlaceholder: {
    fontSize: 20,
  },
  info: {
    flex: 1,
    marginLeft: 12,
  },
  title: {
    fontSize: 15,
    fontWeight: '500',
  },
  artist: {
    fontSize: 13,
    marginTop: 2,
  },
  playingIndicator: {
    marginLeft: 8,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 48,
  },
  emptyText: {
    fontSize: 16,
  },
});
