import React, {useCallback, useEffect, useRef, useState} from 'react';
import {
  Dimensions,
  FlatList,
  Image,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../components/common/TVTouchable';
import LinearGradient from 'react-native-linear-gradient';
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 {addonManager} from '../api/addonManager';
import {MetaPreview} from '../api/addonTypes';
import {useAddonStore} from '../store/addonStore';
import {colors, typography} from '../utils/colors';
import {IS_PHONE, SIDEBAR_W} from '../utils/dimensions';
import {IS_TV} from '../utils/tv';
import LoadingSpinner from '../components/common/LoadingSpinner';
import HelpModal from '../components/common/HelpModal';

const {width: SW, height: SH} = Dimensions.get('window');
const CONTENT_W = IS_PHONE ? SW : SW - SIDEBAR_W;

// Landscape card dimensions — 2 visible on phone, 3+ on larger screens
const VISIBLE_CARDS = IS_PHONE ? 2.2 : 3.1;
const CARD_W = Math.floor((CONTENT_W - 40) / VISIBLE_CARDS);
const CARD_H = Math.floor(CARD_W * 0.5625); // 16:9

type Nav = StackNavigationProp<RootStackParamList>;
type TypeFilter = 'all' | 'movie' | 'series';

const GENRE_ROWS: Array<{label: string; genre: string | null}> = [
  {label: 'Top Picks', genre: null},
  {label: 'Action', genre: 'Action'},
  {label: 'Comedy', genre: 'Comedy'},
  {label: 'Drama', genre: 'Drama'},
  {label: 'Thriller', genre: 'Thriller'},
  {label: 'Sci-Fi', genre: 'Sci-Fi'},
  {label: 'Horror', genre: 'Horror'},
  {label: 'Animation', genre: 'Animation'},
  {label: 'Documentary', genre: 'Documentary'},
];

interface ContentRow {
  label: string;
  genre: string | null;
  items: MetaPreview[];
  loading: boolean;
}

// Landscape card for CTV rows
function LandscapeCard({
  item,
  onPress,
}: {
  item: MetaPreview;
  onPress: () => void;
}) {
  return (
    <TouchableOpacity
      style={{width: CARD_W, marginRight: 10}}
      onPress={onPress}
      activeOpacity={0.82}
      focusable={IS_TV || undefined}>
      <View style={[lcStyles.container, {width: CARD_W, height: CARD_H}]}>
        {item.background || item.poster ? (
          <>
            <Image
              style={StyleSheet.absoluteFillObject}
              source={{uri: item.background || item.poster}}
              resizeMode="cover"
            />
            <LinearGradient
              colors={['transparent', 'rgba(6,11,20,0.92)']}
              locations={[0.35, 1]}
              style={StyleSheet.absoluteFillObject}
            />
          </>
        ) : (
          <View style={lcStyles.placeholder}>
            <Text style={lcStyles.placeholderLetter}>
              {item.name?.[0]?.toUpperCase() ?? '?'}
            </Text>
          </View>
        )}

        {/* IMDb rating */}
        {item.imdbRating && (
          <View style={lcStyles.ratingBadge}>
            <Text style={lcStyles.ratingText}>★ {item.imdbRating}</Text>
          </View>
        )}

        {/* Type badge */}
        {item.type === 'series' && (
          <View style={lcStyles.typeBadge}>
            <Text style={lcStyles.typeBadgeText}>TV</Text>
          </View>
        )}

        {/* Title overlay at bottom */}
        <View style={lcStyles.titleOverlay}>
          <Text style={lcStyles.title} numberOfLines={1}>
            {item.name}
          </Text>
          {item.releaseInfo && (
            <Text style={lcStyles.year}>{item.releaseInfo.slice(0, 4)}</Text>
          )}
        </View>
      </View>
    </TouchableOpacity>
  );
}

const lcStyles = StyleSheet.create({
  container: {
    borderRadius: 10,
    overflow: 'hidden',
    backgroundColor: colors.surfaceLight,
    elevation: 5,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 3},
    shadowOpacity: 0.35,
    shadowRadius: 5,
  },
  placeholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: colors.surfaceHighlight,
  },
  placeholderLetter: {
    fontSize: 32,
    fontWeight: '800',
    color: colors.primary,
    opacity: 0.8,
  },
  ratingBadge: {
    position: 'absolute',
    top: 6,
    left: 6,
    backgroundColor: 'rgba(0,0,0,0.75)',
    paddingHorizontal: 5,
    paddingVertical: 2,
    borderRadius: 4,
    borderWidth: 0.5,
    borderColor: colors.imdbYellow + '50',
  },
  ratingText: {
    fontSize: 9,
    fontWeight: '700',
    color: colors.imdbYellow,
  },
  typeBadge: {
    position: 'absolute',
    top: 6,
    right: 6,
    backgroundColor: 'rgba(108,79,240,0.85)',
    paddingHorizontal: 5,
    paddingVertical: 2,
    borderRadius: 4,
  },
  typeBadgeText: {
    fontSize: 9,
    fontWeight: '800',
    color: '#fff',
    letterSpacing: 0.5,
  },
  titleOverlay: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    paddingHorizontal: 8,
    paddingBottom: 7,
  },
  title: {
    fontSize: 12,
    fontWeight: '600',
    color: colors.textPrimary,
    textShadowColor: 'rgba(0,0,0,0.9)',
    textShadowOffset: {width: 0, height: 1},
    textShadowRadius: 3,
  },
  year: {
    fontSize: 10,
    color: colors.textSecondary,
    marginTop: 1,
  },
});

export default function DiscoverScreen() {
  const navigation = useNavigation<Nav>();
  // Re-trigger content load when addons finish loading from storage
  const addonCount = useAddonStore(s => s.addons.length);
  const addonsHydrated = useAddonStore(s => s.hydrated);
  const [typeFilter, setTypeFilter] = useState<TypeFilter>('all');
  const [rows, setRows] = useState<ContentRow[]>([]);
  const [featuredItem, setFeaturedItem] = useState<MetaPreview | null>(null);
  const [initialLoading, setInitialLoading] = useState(true);
  const [helpVisible, setHelpVisible] = useState(false);
  const featuredSetRef = useRef(false);

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

  const loadContent = useCallback(async () => {
    featuredSetRef.current = false;
    setInitialLoading(true);
    setFeaturedItem(null);

    const catalogs = addonManager.getAllCatalogs();
    const relevant = catalogs.filter(c =>
      typeFilter === 'all'
        ? c.catalog.type === 'movie' || c.catalog.type === 'series'
        : c.catalog.type === typeFilter,
    );

    const initialRows: ContentRow[] = GENRE_ROWS.map(r => ({
      ...r,
      items: [],
      loading: true,
    }));
    setRows(initialRows);
    setInitialLoading(false);

    // Load each genre row independently
    GENRE_ROWS.forEach(({label, genre}, idx) => {
      const extra: Record<string, string> = {};
      if (genre) {
        extra.genre = genre;
      }

      Promise.allSettled(
        relevant.map(c =>
          addonManager
            .getCatalog(c.addon.id, c.catalog.type, c.catalog.id, extra)
            .catch(() => [] as MetaPreview[]),
        ),
      ).then(results => {
        const all: MetaPreview[] = [];
        const seen = new Set<string>();
        for (const r of results) {
          if (r.status === 'fulfilled') {
            for (const i of r.value) {
              if (!seen.has(i.id)) {
                seen.add(i.id);
                all.push(i);
              }
            }
          }
        }

        setRows(prev =>
          prev.map((r, i) =>
            i === idx ? {...r, items: all.slice(0, 20), loading: false} : r,
          ),
        );

        // Use first item of Top Picks as the featured hero
        if (idx === 0 && all.length > 0 && !featuredSetRef.current) {
          featuredSetRef.current = true;
          const withBg = all.find(i => i.background) ?? all[0];
          setFeaturedItem(withBg);
        }
      });
    });
  }, [typeFilter]);

  useEffect(() => {
    // Load content whenever typeFilter changes OR when addons finish loading
    loadContent();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [typeFilter, addonCount]);

  if (initialLoading) {
    return <LoadingSpinner fullScreen />;
  }

  const isEmpty = rows.every(r => !r.loading && r.items.length === 0);

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

      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Discover</Text>
        <View style={styles.headerRight}>
          <TouchableOpacity
            style={styles.helpBtn}
            onPress={() => setHelpVisible(true)}
            activeOpacity={0.7}>
            <Icon name="help-circle-outline" size={22} color={colors.textSecondary} />
          </TouchableOpacity>
          <View style={styles.typeFilter}>
            {(['all', 'movie', 'series'] as TypeFilter[]).map(t => (
              <TouchableOpacity
                key={t}
                style={[
                  styles.typeChip,
                  typeFilter === t && styles.typeChipActive,
                ]}
                onPress={() => setTypeFilter(t)}
                focusable={IS_TV || undefined}>
                <Text
                  style={[
                    styles.typeChipText,
                    typeFilter === t && styles.typeChipTextActive,
                  ]}>
                  {t === 'all' ? 'All' : t === 'movie' ? 'Movies' : 'Series'}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </View>

      {/* Help Modal */}
      <HelpModal
        visible={helpVisible}
        onDismiss={() => setHelpVisible(false)}
        onBrowseAddons={() => navigation.navigate('AddonBrowse')}
      />

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scroll}>

        {/* Featured Hero */}
        {featuredItem && (
          <TouchableOpacity
            style={styles.hero}
            onPress={() => goToDetail(featuredItem)}
            activeOpacity={0.9}>
            <Image
              style={StyleSheet.absoluteFillObject}
              source={{uri: featuredItem.background || featuredItem.poster}}
              resizeMode="cover"
            />
            <LinearGradient
              colors={[
                'rgba(6,11,20,0.05)',
                'rgba(6,11,20,0.55)',
                '#060B14',
              ]}
              locations={[0, 0.55, 1]}
              style={StyleSheet.absoluteFillObject}
            />
            {/* Side vignette */}
            <LinearGradient
              colors={['#060B14', 'transparent', '#060B14']}
              start={{x: 0, y: 0.5}}
              end={{x: 1, y: 0.5}}
              locations={[0, 0.1, 1]}
              style={StyleSheet.absoluteFillObject}
            />
            <View style={styles.heroContent}>
              <View style={styles.featuredTag}>
                <Text style={styles.featuredTagText}>FEATURED</Text>
              </View>
              {featuredItem.genres && featuredItem.genres.length > 0 && (
                <View style={styles.heroGenres}>
                  {featuredItem.genres.slice(0, 3).map(g => (
                    <Text key={g} style={styles.heroGenreText}>
                      {g}
                    </Text>
                  ))}
                </View>
              )}
              <Text style={styles.heroTitle} numberOfLines={2}>
                {featuredItem.name}
              </Text>
              {featuredItem.description && (
                <Text style={styles.heroDesc} numberOfLines={2}>
                  {featuredItem.description}
                </Text>
              )}
              <View style={styles.heroActions}>
                <TouchableOpacity
                  style={styles.heroPlayBtn}
                  onPress={() => goToDetail(featuredItem)}
                  focusable={IS_TV || undefined}>
                  <Text style={styles.heroPlayIcon}>▶</Text>
                  <Text style={styles.heroPlayText}>Watch Now</Text>
                </TouchableOpacity>
                <View style={styles.heroMeta}>
                  {featuredItem.imdbRating && (
                    <Text style={styles.heroRating}>
                      ★ {featuredItem.imdbRating}
                    </Text>
                  )}
                  {featuredItem.releaseInfo && (
                    <Text style={styles.heroYear}>
                      {featuredItem.releaseInfo.slice(0, 4)}
                    </Text>
                  )}
                </View>
              </View>
            </View>
          </TouchableOpacity>
        )}

        {/* Genre rows */}
        {rows.map(row => {
          if (!row.loading && row.items.length === 0) return null;
          return (
            <View key={row.label} style={styles.rowSection}>
              <View style={styles.rowHeader}>
                <Text style={styles.rowTitle}>{row.label}</Text>
                <Icon
                  name="chevron-right"
                  size={18}
                  color={colors.textMuted}
                />
              </View>
              {row.loading ? (
                <View style={styles.shimmerRow}>
                  {[0, 1, 2].map(i => (
                    <View
                      key={i}
                      style={[
                        styles.shimmer,
                        {width: CARD_W, height: CARD_H},
                      ]}
                    />
                  ))}
                </View>
              ) : (
                <FlatList
                  data={row.items}
                  horizontal
                  keyExtractor={i => i.id}
                  showsHorizontalScrollIndicator={false}
                  contentContainerStyle={styles.rowList}
                  renderItem={({item}) => (
                    <LandscapeCard
                      item={item}
                      onPress={() => goToDetail(item)}
                    />
                  )}
                  removeClippedSubviews
                />
              )}
            </View>
          );
        })}

        {/* Empty state — rich onboarding (only after addon store hydrated) */}
        {!initialLoading && isEmpty && addonsHydrated && (
          <View style={styles.emptyState}>
            <Icon name="play-circle" size={56} color={colors.primary} />
            <Text style={styles.emptyTitle}>Welcome to StreamVault</Text>
            <Text style={styles.emptySubtitle}>
              Get started in 3 easy steps
            </Text>

            {/* Step 1 */}
            <View style={styles.step}>
              <View style={styles.stepNumber}>
                <Text style={styles.stepNumberText}>1</Text>
              </View>
              <View style={styles.stepContent}>
                <Text style={styles.stepTitle}>Install an addon</Text>
                <Text style={styles.stepDesc}>
                  Addons are community sources that provide movie & TV show catalogs and streams.
                </Text>
              </View>
            </View>

            {/* Step 2 */}
            <View style={styles.step}>
              <View style={styles.stepNumber}>
                <Text style={styles.stepNumberText}>2</Text>
              </View>
              <View style={styles.stepContent}>
                <Text style={styles.stepTitle}>Browse & discover</Text>
                <Text style={styles.stepDesc}>
                  Content appears here automatically once an addon is installed.
                </Text>
              </View>
            </View>

            {/* Step 3 */}
            <View style={styles.step}>
              <View style={styles.stepNumber}>
                <Text style={styles.stepNumberText}>3</Text>
              </View>
              <View style={styles.stepContent}>
                <Text style={styles.stepTitle}>Watch anything</Text>
                <Text style={styles.stepDesc}>
                  Tap a title to see available streams and start watching.
                </Text>
              </View>
            </View>

            {/* Actions */}
            <View style={styles.emptyActions}>
              <TouchableOpacity
                style={styles.primaryAction}
                onPress={() => navigation.navigate('AddonBrowse')}
                activeOpacity={0.8}
                focusable={IS_TV || undefined}>
                <Icon name="puzzle-outline" size={18} color="#fff" />
                <Text style={styles.primaryActionText}>Browse Addons</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={styles.secondaryAction}
                onPress={() => navigation.navigate('Addons' as any)}
                activeOpacity={0.8}
                focusable={IS_TV || undefined}>
                <Icon name="link-variant" size={16} color={colors.textSecondary} />
                <Text style={styles.secondaryActionText}>Install from URL</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: colors.background},
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingTop: 48,
    paddingBottom: 10,
  },
  headerTitle: {...typography.title, color: colors.textPrimary},
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
  },
  helpBtn: {
    width: 34,
    height: 34,
    borderRadius: 17,
    backgroundColor: colors.surfaceLight,
    justifyContent: 'center',
    alignItems: 'center',
  },
  typeFilter: {
    flexDirection: 'row',
    gap: 8,
  },
  typeChip: {
    paddingHorizontal: 14,
    paddingVertical: 6,
    borderRadius: 16,
    backgroundColor: colors.surfaceLight,
  },
  typeChipActive: {backgroundColor: colors.primary},
  typeChipText: {fontSize: 13, color: colors.textSecondary, fontWeight: '500'},
  typeChipTextActive: {color: colors.textPrimary, fontWeight: '700'},
  scroll: {paddingBottom: 32},

  // Hero
  hero: {
    width: '100%',
    height: SH * 0.44,
    marginBottom: 22,
  },
  heroContent: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    paddingHorizontal: 18,
    paddingBottom: 20,
  },
  featuredTag: {
    backgroundColor: colors.primary + 'DD',
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: 4,
    alignSelf: 'flex-start',
    marginBottom: 8,
  },
  featuredTagText: {
    fontSize: 9,
    fontWeight: '800',
    color: '#fff',
    letterSpacing: 1.2,
  },
  heroGenres: {
    flexDirection: 'row',
    gap: 8,
    marginBottom: 6,
  },
  heroGenreText: {
    fontSize: 11,
    color: colors.textSecondary,
    fontWeight: '500',
  },
  heroTitle: {
    fontSize: 26,
    fontWeight: '800',
    color: colors.textPrimary,
    marginBottom: 6,
    textShadowColor: 'rgba(0,0,0,0.9)',
    textShadowOffset: {width: 0, height: 2},
    textShadowRadius: 6,
  },
  heroDesc: {
    fontSize: 13,
    color: colors.textSecondary,
    lineHeight: 18,
    marginBottom: 14,
  },
  heroActions: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 16,
  },
  heroPlayBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.primary,
    paddingHorizontal: 22,
    paddingVertical: 10,
    borderRadius: 8,
    gap: 8,
    elevation: 4,
    shadowColor: colors.primary,
    shadowOffset: {width: 0, height: 4},
    shadowOpacity: 0.55,
    shadowRadius: 8,
  },
  heroPlayIcon: {color: '#fff', fontSize: 13},
  heroPlayText: {color: '#fff', fontSize: 14, fontWeight: '700'},
  heroMeta: {flexDirection: 'row', gap: 10, alignItems: 'center'},
  heroRating: {
    color: colors.imdbYellow,
    fontWeight: '700',
    fontSize: 13,
  },
  heroYear: {color: colors.textSecondary, fontSize: 13},

  // Rows
  rowSection: {marginBottom: 24},
  rowHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    marginBottom: 12,
  },
  rowTitle: {
    ...typography.subtitle,
    color: colors.textPrimary,
  },
  shimmerRow: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    gap: 10,
  },
  shimmer: {
    borderRadius: 10,
    backgroundColor: colors.surfaceLight,
    opacity: 0.6,
  },
  rowList: {
    paddingHorizontal: 16,
    paddingRight: 16,
  },

  // Empty — rich onboarding
  emptyState: {
    alignItems: 'center',
    paddingTop: 48,
    paddingBottom: 60,
    paddingHorizontal: 28,
  },
  emptyTitle: {
    ...typography.title,
    fontSize: 22,
    color: colors.textPrimary,
    textAlign: 'center',
    marginTop: 16,
    marginBottom: 4,
  },
  emptySubtitle: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    marginBottom: 28,
  },
  step: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    width: '100%',
    marginBottom: 18,
    gap: 14,
  },
  stepNumber: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: colors.primary + '22',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 2,
  },
  stepNumberText: {
    fontSize: 13,
    fontWeight: '800',
    color: colors.primary,
  },
  stepContent: {
    flex: 1,
  },
  stepTitle: {
    ...typography.subtitle,
    color: colors.textPrimary,
    marginBottom: 3,
  },
  stepDesc: {
    ...typography.body,
    color: colors.textSecondary,
    lineHeight: 20,
  },
  emptyActions: {
    flexDirection: 'row',
    gap: 10,
    marginTop: 10,
    width: '100%',
  },
  primaryAction: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
    backgroundColor: colors.surfaceHighlight,
    paddingVertical: 13,
    borderRadius: 10,
    borderWidth: 1.5,
    borderColor: colors.primary,
    elevation: 4,
    shadowColor: colors.primary,
    shadowOffset: {width: 0, height: 4},
    shadowOpacity: 0.4,
    shadowRadius: 8,
  },
  primaryActionText: {
    color: '#fff',
    fontSize: 15,
    fontWeight: '700',
  },
  secondaryAction: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 6,
    backgroundColor: colors.surfaceLight,
    paddingVertical: 13,
    borderRadius: 10,
  },
  secondaryActionText: {
    color: colors.textSecondary,
    fontSize: 14,
    fontWeight: '600',
  },
});
