import React from 'react';
import {Image, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {AddonManifest, Stream} from '../../api/addonTypes';
import {colors, typography} from '../../utils/colors';
import {formatBytes, formatStreamTitle} from '../../utils/formatters';

interface Props {
  stream: Stream;
  addon: AddonManifest;
  isDebridCached?: boolean;
  onPress: () => void;
  onWatchLater?: () => void;
  watchLaterStatus?: 'queued' | 'resolving' | 'downloading' | 'ready' | 'error' | null;
  watchLaterProgress?: number;
}

// Extract quality from stream name/title
function extractQuality(stream: Stream): string | null {
  const text = (stream.name ?? '') + ' ' + (stream.title ?? '');
  if (/4k|2160p/i.test(text)) return '4K';
  if (/1080p/i.test(text)) return '1080p';
  if (/720p/i.test(text)) return '720p';
  if (/480p/i.test(text)) return '480p';
  return null;
}

const QUALITY_COLORS: Record<string, string> = {
  '4K': '#E040FB',
  '1080p': '#00D4FF',
  '720p': '#2ECC8A',
  '480p': '#F0A500',
};

export default function StreamItem({stream, addon, isDebridCached, onPress, onWatchLater, watchLaterStatus, watchLaterProgress}: Props) {
  const title = formatStreamTitle(stream);
  const size = formatBytes(stream.behaviorHints?.videoSize);
  const isTorrent = !!stream.infoHash && !stream.url;
  const isExternal = !!stream.externalUrl && !stream.url && !stream.infoHash;
  const quality = extractQuality(stream);
  return (
    <View style={styles.container}>
      {/* Play area — focusable for D-pad */}
      <TouchableOpacity style={styles.playArea} onPress={onPress} activeOpacity={0.78}>
        {/* Left: addon logo + name */}
        <View style={styles.left}>
          {addon.logo ? (
            <Image
              style={styles.logo}
              source={{uri: addon.logo}}
              resizeMode="contain"
            />
          ) : (
            <View style={[styles.logo, styles.logoPlaceholder]}>
              <Text style={styles.logoLetter}>{addon.name[0]}</Text>
            </View>
          )}
          <Text style={styles.addonName} numberOfLines={1}>
            {addon.name}
          </Text>
        </View>

        {/* Center: stream title + size */}
        <View style={styles.center}>
          <Text style={styles.streamTitle} numberOfLines={2}>
            {title}
          </Text>
          {size ? <Text style={styles.streamSize}>{size}</Text> : null}
          {/* Badges row */}
          <View style={styles.badges}>
            {isDebridCached && (
              <View style={[styles.badge, {backgroundColor: colors.success + '25', borderColor: colors.success}]}>
                <Text style={[styles.badgeText, {color: colors.success}]}>⚡ Cached</Text>
              </View>
            )}
            {isTorrent && !isDebridCached && (
              <View style={[styles.badge, {backgroundColor: colors.warning + '20', borderColor: colors.warning}]}>
                <Text style={[styles.badgeText, {color: colors.warning}]}>Torrent</Text>
              </View>
            )}
            {isExternal && (
              <View style={[styles.badge, {backgroundColor: colors.info + '20', borderColor: colors.info}]}>
                <Text style={[styles.badgeText, {color: colors.info}]}>External</Text>
              </View>
            )}
          </View>
        </View>

        {/* Quality badge + play icon */}
        <View style={styles.right}>
          {quality && (
            <View style={[styles.qualityBadge, {backgroundColor: QUALITY_COLORS[quality] + '22', borderColor: QUALITY_COLORS[quality] + '70'}]}>
              <Text style={[styles.qualityText, {color: QUALITY_COLORS[quality]}]}>{quality}</Text>
            </View>
          )}
          <View style={styles.playBtn}>
            <Text style={styles.playIcon}>▶</Text>
          </View>
        </View>
      </TouchableOpacity>

      {/* Watch Later button — separate focusable for D-pad */}
      {onWatchLater && isTorrent && (
        <TouchableOpacity
          style={[
            styles.watchLaterBtn,
            watchLaterStatus === 'ready' && styles.watchLaterReady,
            (watchLaterStatus === 'downloading' || watchLaterStatus === 'resolving') && styles.watchLaterActive,
          ]}
          onPress={onWatchLater}
          activeOpacity={0.7}>
          <Icon
            name={
              watchLaterStatus === 'ready' ? 'check-circle' :
              watchLaterStatus === 'downloading' || watchLaterStatus === 'resolving' ? 'progress-download' :
              'clock-plus-outline'
            }
            size={16}
            color={
              watchLaterStatus === 'ready' ? colors.success :
              watchLaterStatus === 'downloading' || watchLaterStatus === 'resolving' ? colors.primary :
              colors.textMuted
            }
          />
          {(watchLaterStatus === 'downloading' || watchLaterStatus === 'resolving') && watchLaterProgress != null && (
            <Text style={styles.watchLaterPct}>{watchLaterProgress}%</Text>
          )}
        </TouchableOpacity>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.surface,
    borderRadius: 12,
    padding: 12,
    marginBottom: 8,
    gap: 8,
    borderWidth: 0.5,
    borderColor: colors.border,
  },
  playArea: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
  },
  left: {
    alignItems: 'center',
    width: 52,
    gap: 4,
  },
  logo: {width: 36, height: 36, borderRadius: 8},
  logoPlaceholder: {
    backgroundColor: colors.primary + '33',
    borderWidth: 1,
    borderColor: colors.primary + '60',
    justifyContent: 'center',
    alignItems: 'center',
  },
  logoLetter: {
    color: colors.primaryLight,
    fontWeight: '800',
    fontSize: 16,
  },
  addonName: {
    fontSize: 9,
    color: colors.textMuted,
    textAlign: 'center',
    fontWeight: '500',
  },
  center: {flex: 1},
  streamTitle: {
    ...typography.body,
    color: colors.textPrimary,
    fontWeight: '500',
    marginBottom: 2,
    lineHeight: 18,
  },
  streamSize: {
    fontSize: 11,
    color: colors.textMuted,
    marginBottom: 4,
  },
  badges: {flexDirection: 'row', gap: 4, flexWrap: 'wrap'},
  badge: {
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 4,
    borderWidth: 1,
  },
  badgeText: {
    fontSize: 9,
    fontWeight: '700',
    letterSpacing: 0.3,
  },
  right: {
    alignItems: 'center',
    gap: 6,
  },
  watchLaterBtn: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: 'rgba(255,255,255,0.08)',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.12)',
  },
  watchLaterReady: {
    backgroundColor: colors.success + '20',
    borderColor: colors.success + '50',
  },
  watchLaterActive: {
    backgroundColor: colors.primary + '20',
    borderColor: colors.primary + '50',
  },
  watchLaterPct: {
    fontSize: 7,
    color: colors.primary,
    fontWeight: '700',
    position: 'absolute',
    bottom: 1,
  },
  qualityBadge: {
    paddingHorizontal: 6,
    paddingVertical: 3,
    borderRadius: 5,
    borderWidth: 1,
  },
  qualityText: {
    fontSize: 9,
    fontWeight: '800',
    letterSpacing: 0.5,
  },
  playBtn: {
    width: 34,
    height: 34,
    borderRadius: 17,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 3,
    shadowColor: colors.primary,
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.5,
    shadowRadius: 4,
  },
  playIcon: {
    color: '#fff',
    fontSize: 12,
    marginLeft: 2,
  },
});
