import React, {useCallback, useState} from 'react';
import {
  Alert,
  FlatList,
  Image,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  ToastAndroid,
  TouchableOpacity as RNTouchableOpacity,
  View,
} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../components/common/TVTouchable';
import {useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {RootStackParamList} from '../navigation/types';
import {useLibraryStore, LibraryItem} from '../store/libraryStore';
import {useWatchLaterStore, WatchLaterItem} from '../store/watchLaterStore';
import {playPreloadedTorrent, cancelPreload, preloadTorrent} from '../utils/torrentStreamService';
import {colors, typography} from '../utils/colors';
import {IS_TV} from '../utils/tv';
import Card from '../components/common/Card';
import {MetaPreview} from '../api/addonTypes';

type Nav = StackNavigationProp<RootStackParamList>;
type Section = 'downloads' | 'continue' | 'watchlist' | 'favorites' | 'history';

const SECTIONS: {key: Section; label: string; icon: string}[] = [
  {key: 'downloads', label: 'Downloads', icon: 'download-circle'},
  {key: 'continue', label: 'Continue', icon: 'play-circle'},
  {key: 'watchlist', label: 'Watchlist', icon: 'bookmark'},
  {key: 'favorites', label: 'Favorites', icon: 'star'},
  {key: 'history', label: 'History', icon: 'history'},
];

function libraryItemToMeta(item: LibraryItem): MetaPreview {
  return {
    id: item.id,
    type: item.type,
    name: item.name,
    poster: item.poster,
  };
}

function DownloadItem({
  item,
  onPlay,
  onRemove,
  onRetry,
  onViewDetails,
}: {
  item: WatchLaterItem;
  onPlay: () => void;
  onRemove: () => void;
  onRetry: () => void;
  onViewDetails: () => void;
}) {
  const isActive = item.status === 'downloading' || item.status === 'resolving';
  const isReady = item.status === 'ready';
  const isError = item.status === 'error';
  const isQueued = item.status === 'queued';
  const canPlay = isReady || (item.status === 'downloading' && item.progress > 5);

  // Tapping the whole row: play if possible, retry if queued/error, otherwise open details
  const handleRowPress = canPlay ? onPlay : (isQueued || isError) ? onRetry : onViewDetails;

  const posterBlock = (
    <View>
      {item.poster ? (
        <Image style={dlStyles.poster} source={{uri: item.poster}} resizeMode="cover" />
      ) : (
        <View style={[dlStyles.poster, dlStyles.posterPlaceholder]}>
          <Text style={dlStyles.placeholderText}>{item.name?.[0]?.toUpperCase() ?? '?'}</Text>
        </View>
      )}
      {isActive && (
        <View style={dlStyles.posterBadge}>
          <Text style={dlStyles.posterBadgeText}>{item.progress}%</Text>
        </View>
      )}
      {isReady && (
        <View style={[dlStyles.posterBadge, {backgroundColor: colors.success}]}>
          <Icon name="check" size={10} color="#fff" />
        </View>
      )}
    </View>
  );

  const infoBlock = (
    <View style={dlStyles.info}>
      <Text style={dlStyles.name} numberOfLines={1}>
        {item.name}
        {item.season != null && item.episode != null
          ? ` — S${item.season}E${item.episode}`
          : ''}
      </Text>
      {item.episodeTitle ? (
        <Text style={dlStyles.episodeTitle} numberOfLines={1}>{item.episodeTitle}</Text>
      ) : null}

      {item.status === 'queued' && (
        <Text style={[dlStyles.statusLabel, {color: colors.primary}]}>Tap to start download</Text>
      )}
      {item.status === 'resolving' && (
        <Text style={[dlStyles.statusLabel, {color: colors.primary}]}>Finding peers...</Text>
      )}
      {item.status === 'downloading' && (
        <View style={dlStyles.progressRow}>
          <View style={dlStyles.progressBarWrap}>
            <View style={[dlStyles.progressBarFill, {width: `${item.progress}%`}]} />
          </View>
          <Text style={dlStyles.progressPct}>{item.progress}%</Text>
        </View>
      )}
      {isReady && (
        <Text style={[dlStyles.statusLabel, {color: colors.success}]}>Ready — tap to play</Text>
      )}
      {isError && (
        <Text style={[dlStyles.statusLabel, {color: colors.error}]} numberOfLines={1}>
          {item.errorMsg || 'Download failed'}
        </Text>
      )}
    </View>
  );

  // ── TV layout: each button is an independent focusable sibling ──
  if (IS_TV) {
    return (
      <View style={dlStyles.container}>
        {/* Poster + info area — focusable, navigates to details or plays */}
        <RNTouchableOpacity
          style={dlStyles.tvInfoArea}
          onPress={handleRowPress}
          activeOpacity={0.78}
          focusable={true}>
          {posterBlock}
          {infoBlock}
        </RNTouchableOpacity>

        {/* Action buttons — each independently focusable */}
        <View style={dlStyles.rightCol}>
          {canPlay ? (
            <RNTouchableOpacity style={dlStyles.bigPlayBtn} onPress={onPlay} activeOpacity={0.8} focusable={true}>
              <Icon name="play" size={22} color="#fff" />
            </RNTouchableOpacity>
          ) : isQueued ? (
            <RNTouchableOpacity style={dlStyles.bigPlayBtn} onPress={onRetry} activeOpacity={0.8} focusable={true}>
              <Icon name="download" size={22} color="#fff" />
            </RNTouchableOpacity>
          ) : isError ? (
            <RNTouchableOpacity style={[dlStyles.bigPlayBtn, {backgroundColor: colors.error}]} onPress={onRetry} activeOpacity={0.8} focusable={true}>
              <Icon name="refresh" size={22} color="#fff" />
            </RNTouchableOpacity>
          ) : (
            <Icon name="loading" size={20} color={colors.textMuted} />
          )}
          {!isError && (
            <RNTouchableOpacity
              style={dlStyles.tvRemoveBtn}
              onPress={onRemove}
              activeOpacity={0.8}
              focusable={true}>
              <Icon name="close" size={16} color={colors.error} />
            </RNTouchableOpacity>
          )}
        </View>
      </View>
    );
  }

  // ── Phone layout: whole row is one touchable ──
  return (
    <TouchableOpacity
      style={dlStyles.container}
      onPress={handleRowPress}
      activeOpacity={0.78}>
      {posterBlock}
      {infoBlock}

      {/* Right side: play button, retry, or loading */}
      <View style={dlStyles.rightCol}>
        {canPlay ? (
          <TouchableOpacity style={dlStyles.bigPlayBtn} onPress={onPlay} activeOpacity={0.8}>
            <Icon name="play" size={22} color="#fff" />
          </TouchableOpacity>
        ) : isQueued ? (
          <TouchableOpacity style={dlStyles.bigPlayBtn} onPress={onRetry} activeOpacity={0.8}>
            <Icon name="download" size={22} color="#fff" />
          </TouchableOpacity>
        ) : isError ? (
          <TouchableOpacity style={[dlStyles.bigPlayBtn, {backgroundColor: colors.error}]} onPress={onRetry} activeOpacity={0.8}>
            <Icon name="refresh" size={22} color="#fff" />
          </TouchableOpacity>
        ) : (
          <Icon name="loading" size={20} color={colors.textMuted} />
        )}
        {!isError && (
          <TouchableOpacity
            style={dlStyles.smallRemoveBtn}
            onPress={(e) => { e.stopPropagation(); onRemove(); }}
            activeOpacity={0.8}>
            <Icon name="close" size={12} color={colors.textMuted} />
          </TouchableOpacity>
        )}
      </View>
    </TouchableOpacity>
  );
}

export default function LibraryScreen() {
  const navigation = useNavigation<Nav>();
  const [activeSection, setActiveSection] = useState<Section>('downloads');
  const [playingHash, setPlayingHash] = useState<string | null>(null);
  const {watchlist, favorites, history} = useLibraryStore();
  const watchLaterItems = useWatchLaterStore(s => s.items);
  const removeWatchLater = useWatchLaterStore(s => s.removeItem);
  const updateProgress = useWatchLaterStore(s => s.updateProgress);
  const updateStatus = useWatchLaterStore(s => s.updateStatus);

  const continueWatching = history.filter(
    i => i.watchProgress !== undefined && i.watchProgress > 0.02 && i.watchProgress < 0.95,
  );

  const getItems = (): LibraryItem[] => {
    switch (activeSection) {
      case 'continue': return continueWatching;
      case 'watchlist': return watchlist;
      case 'favorites': return favorites;
      case 'history': return history;
      default: return [];
    }
  };

  const items = getItems();

  const goToDetail = (item: MetaPreview) => {
    navigation.navigate('Detail', {
      id: item.id,
      type: item.type,
      name: item.name,
      poster: item.poster,
    });
  };

  const handlePlayDownload = useCallback(async (item: WatchLaterItem) => {
    if (playingHash) return;
    setPlayingHash(item.infoHash);
    try {
      const result = await playPreloadedTorrent(item.infoHash);
      setPlayingHash(null);
      navigation.navigate('Player', {
        id: item.id,
        type: item.type as any,
        name: item.name,
        stream: {infoHash: item.infoHash, url: result.url},
        poster: item.poster,
      });
    } catch (e) {
      setPlayingHash(null);
      Alert.alert('Play Error', `Could not play: ${String(e)}`);
    }
  }, [navigation, playingHash]);

  const handleRemoveDownload = useCallback((item: WatchLaterItem) => {
    Alert.alert(
      'Remove Download',
      `Remove "${item.name}" from downloads?`,
      [
        {text: 'Cancel', style: 'cancel'},
        {
          text: 'Remove',
          style: 'destructive',
          onPress: () => {
            cancelPreload(item.infoHash);
            removeWatchLater(item.infoHash);
            ToastAndroid.show('Removed', ToastAndroid.SHORT);
          },
        },
      ],
    );
  }, [removeWatchLater]);

  const handleRetryDownload = useCallback((item: WatchLaterItem) => {
    // Cancel any existing preload for this hash first
    cancelPreload(item.infoHash);
    updateProgress(item.infoHash, 0, 'resolving');
    preloadTorrent(item.infoHash, p => {
      if (p.status === 'complete') {
        updateProgress(item.infoHash, 100, 'ready');
      } else {
        updateProgress(
          item.infoHash,
          p.progress,
          p.status === 'resolving' ? 'resolving' : 'downloading',
        );
      }
    }).catch(e => {
      updateStatus(item.infoHash, 'error', String(e));
    });
  }, [updateProgress, updateStatus]);

  const handleViewDetails = useCallback((item: WatchLaterItem) => {
    navigation.navigate('Detail', {
      id: item.id,
      type: item.type as any,
      name: item.name,
      poster: item.poster,
    });
  }, [navigation]);

  const downloadCount = watchLaterItems.length;

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />

      <View style={styles.header}>
        <Text style={styles.headerTitle}>Library</Text>
      </View>

      {/* Section tabs — plain View on TV to avoid ScrollView focus trap */}
      {IS_TV ? (
        <View style={styles.tvSectionRow}>
          {SECTIONS.map(s => (
            <RNTouchableOpacity
              key={s.key}
              style={[styles.sectionChip, activeSection === s.key && styles.sectionChipActive]}
              onPress={() => setActiveSection(s.key)}
              focusable={true}>
              <Icon
                name={s.icon}
                size={14}
                color={activeSection === s.key ? colors.textPrimary : colors.textMuted}
              />
              <Text
                style={[
                  styles.sectionText,
                  activeSection === s.key && styles.sectionTextActive,
                ]}>
                {s.key === 'downloads' && downloadCount > 0
                  ? `${s.label} (${downloadCount})`
                  : s.label}
              </Text>
            </RNTouchableOpacity>
          ))}
        </View>
      ) : (
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.sectionList}
          style={styles.sectionScroll}>
          {SECTIONS.map(s => (
            <TouchableOpacity
              key={s.key}
              style={[styles.sectionChip, activeSection === s.key && styles.sectionChipActive]}
              onPress={() => setActiveSection(s.key)}>
              <Icon
                name={s.icon}
                size={14}
                color={activeSection === s.key ? colors.textPrimary : colors.textMuted}
              />
              <Text
                style={[
                  styles.sectionText,
                  activeSection === s.key && styles.sectionTextActive,
                ]}>
                {s.key === 'downloads' && downloadCount > 0
                  ? `${s.label} (${downloadCount})`
                  : s.label}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      )}

      {/* Downloads section */}
      {activeSection === 'downloads' ? (
        watchLaterItems.length === 0 ? (
          <View style={styles.emptyState}>
            <Icon name="download-circle" size={64} color={colors.textMuted} />
            <Text style={styles.emptyTitle}>No downloads</Text>
            <Text style={styles.emptyText}>
              Find a movie or show, tap the Streams tab, then tap the clock icon next to a torrent stream to download it for later.
            </Text>
          </View>
        ) : (
          <FlatList
            data={watchLaterItems}
            keyExtractor={i => i.infoHash}
            contentContainerStyle={styles.downloadList}
            renderItem={({item}) => (
              <DownloadItem
                item={item}
                onPlay={() => handlePlayDownload(item)}
                onRemove={() => handleRemoveDownload(item)}
                onRetry={() => handleRetryDownload(item)}
                onViewDetails={() => handleViewDetails(item)}
              />
            )}
          />
        )
      ) : items.length === 0 ? (
        <View style={styles.emptyState}>
          <Icon
            name={SECTIONS.find(s => s.key === activeSection)?.icon ?? 'bookmark'}
            size={64}
            color={colors.textMuted}
          />
          <Text style={styles.emptyTitle}>Nothing here yet</Text>
          <Text style={styles.emptyText}>
            {activeSection === 'continue'
              ? 'Start watching something to see it here.'
              : activeSection === 'watchlist'
              ? 'Add movies and shows to your watchlist.'
              : activeSection === 'favorites'
              ? 'Mark your favorite content.'
              : 'Your watch history will appear here.'}
          </Text>
        </View>
      ) : (
        <FlatList
          data={items}
          numColumns={3}
          keyExtractor={i => i.id}
          contentContainerStyle={styles.grid}
          columnWrapperStyle={styles.row}
          renderItem={({item}) => (
            <View style={styles.cardWrapper}>
              <Card
                item={libraryItemToMeta(item)}
                onPress={goToDetail}
                size="small"
              />
              {activeSection === 'continue' && item.watchProgress && (
                <View style={styles.progressBar}>
                  <View
                    style={[
                      styles.progressFill,
                      {width: `${item.watchProgress * 100}%`},
                    ]}
                  />
                </View>
              )}
            </View>
          )}
        />
      )}

      {/* Loading overlay when starting playback */}
      {playingHash && (
        <View style={styles.playingOverlay}>
          <View style={styles.playingCard}>
            <Icon name="loading" size={28} color={colors.primary} />
            <Text style={styles.playingText}>Starting playback...</Text>
          </View>
        </View>
      )}
    </View>
  );
}

const dlStyles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surface,
    borderRadius: 12,
    padding: 12,
    marginBottom: 10,
    gap: 12,
    borderWidth: 0.5,
    borderColor: colors.border,
  },
  poster: {
    width: 60,
    height: 86,
    borderRadius: 8,
  },
  posterPlaceholder: {
    backgroundColor: colors.surfaceHighlight,
    justifyContent: 'center',
    alignItems: 'center',
  },
  placeholderText: {
    fontSize: 22,
    fontWeight: '800',
    color: colors.primary,
  },
  posterBadge: {
    position: 'absolute',
    bottom: 4,
    right: 4,
    backgroundColor: colors.primary,
    borderRadius: 8,
    paddingHorizontal: 5,
    paddingVertical: 2,
    minWidth: 20,
    alignItems: 'center',
  },
  posterBadgeText: {
    fontSize: 8,
    fontWeight: '800',
    color: '#fff',
  },
  info: {
    flex: 1,
    justifyContent: 'center',
    gap: 5,
  },
  name: {
    ...typography.body,
    color: colors.textPrimary,
    fontWeight: '600',
    fontSize: 15,
  },
  episodeTitle: {
    fontSize: 12,
    color: colors.textMuted,
    fontWeight: '500',
  },
  statusLabel: {
    fontSize: 12,
    fontWeight: '500',
  },
  progressRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  progressBarWrap: {
    flex: 1,
    height: 5,
    backgroundColor: 'rgba(255,255,255,0.1)',
    borderRadius: 3,
    overflow: 'hidden',
  },
  progressBarFill: {
    height: '100%',
    backgroundColor: colors.primary,
    borderRadius: 3,
  },
  progressPct: {
    fontSize: 12,
    fontWeight: '700',
    color: colors.primary,
    minWidth: 36,
    textAlign: 'right',
  },
  rightCol: {
    alignItems: 'center',
    gap: 6,
  },
  bigPlayBtn: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 4,
    shadowColor: colors.primary,
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.5,
    shadowRadius: 4,
  },
  removeBtn: {
    width: 40,
    height: 40,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: colors.error + '40',
    justifyContent: 'center',
    alignItems: 'center',
  },
  smallRemoveBtn: {
    width: 22,
    height: 22,
    borderRadius: 11,
    backgroundColor: 'rgba(255,255,255,0.08)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  // TV: poster+info as a single focusable row
  tvInfoArea: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
  },
  // TV: bigger remove button so D-pad focus highlight is visible
  tvRemoveBtn: {
    width: 36,
    height: 36,
    borderRadius: 18,
    borderWidth: 1,
    borderColor: colors.error + '60',
    backgroundColor: colors.error + '15',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: colors.background},
  header: {
    paddingHorizontal: 16,
    paddingTop: 48,
    paddingBottom: 12,
  },
  headerTitle: {...typography.title, color: colors.textPrimary},
  sectionScroll: {
    flexGrow: 0,
    marginBottom: 12,
  },
  sectionList: {
    paddingHorizontal: 16,
    gap: 8,
  },
  tvSectionRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 16,
    gap: 8,
    marginBottom: 12,
  },
  sectionChip: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 5,
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: colors.surfaceLight,
  },
  sectionChipActive: {backgroundColor: colors.primary},
  sectionText: {...typography.caption, color: colors.textMuted},
  sectionTextActive: {color: colors.textPrimary, fontWeight: '600'},
  grid: {paddingHorizontal: 16, paddingBottom: 20},
  downloadList: {paddingHorizontal: 16, paddingBottom: 20},
  row: {justifyContent: 'space-between', marginBottom: 12},
  cardWrapper: {position: 'relative'},
  progressBar: {
    height: 3,
    backgroundColor: colors.border,
    borderRadius: 2,
    marginTop: -3,
  },
  progressFill: {
    height: '100%',
    backgroundColor: colors.primary,
    borderRadius: 2,
  },
  emptyState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 40,
    gap: 12,
  },
  emptyTitle: {...typography.title, color: colors.textSecondary},
  emptyText: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
  },
  playingOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 100,
  },
  playingCard: {
    backgroundColor: colors.surface,
    borderRadius: 16,
    padding: 24,
    alignItems: 'center',
    gap: 12,
  },
  playingText: {
    ...typography.body,
    color: colors.textPrimary,
    fontWeight: '500',
  },
});
