import React, {useCallback, useEffect, useRef, useState} from 'react';
import {
  RefreshControl,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
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 {ContentType, MetaPreview} from '../api/addonTypes';
import {colors, typography} from '../utils/colors';
import HeroCarousel from '../components/common/HeroCarousel';
import Row from '../components/common/Row';
import LoadingSpinner from '../components/common/LoadingSpinner';

type Nav = StackNavigationProp<RootStackParamList>;

interface CatalogRow {
  key: string;
  title: string;
  addonId: string;
  type: ContentType;
  catalogId: string;
  items: MetaPreview[];
  loading: boolean;
  skip: number;
}

const PAGE_SIZE = 20;

export default function HomeScreen() {
  const navigation = useNavigation<Nav>();
  const [rows, setRows] = useState<CatalogRow[]>([]);
  const [initialLoading, setInitialLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const mountedRef = useRef(true);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  const loadCatalogs = useCallback(async () => {
    const catalogs = addonManager.getAllCatalogs();
    const newRows: CatalogRow[] = catalogs.map(({addon, catalog}) => ({
      key: `${addon.id}-${catalog.type}-${catalog.id}`,
      title: `${catalog.name}`,
      addonId: addon.id,
      type: catalog.type,
      catalogId: catalog.id,
      items: [],
      loading: true,
      skip: 0,
    }));

    if (mountedRef.current) {
      setRows(newRows);
      setInitialLoading(false);
    }

    // Load items for each row
    for (const row of newRows) {
      addonManager
        .getCatalog(row.addonId, row.type, row.catalogId)
        .then(items => {
          if (!mountedRef.current) return;
          setRows(prev =>
            prev.map(r =>
              r.key === row.key
                ? {...r, items: items.slice(0, PAGE_SIZE), loading: false}
                : r,
            ),
          );
        })
        .catch(() => {
          if (!mountedRef.current) return;
          setRows(prev =>
            prev.map(r => (r.key === row.key ? {...r, loading: false} : r)),
          );
        });
    }
  }, []);

  useEffect(() => {
    loadCatalogs();
  }, [loadCatalogs]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadCatalogs();
    setRefreshing(false);
  }, [loadCatalogs]);

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

  const heroItems = rows
    .flatMap(r => r.items)
    .filter(i => i.background || i.poster)
    .slice(0, 5);

  if (initialLoading) return <LoadingSpinner fullScreen />;

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

      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.logo}>StreamVault</Text>
        <TouchableOpacity
          onPress={() => navigation.navigate('Settings')}
          style={styles.headerBtn}>
          <Icon name="cog-outline" size={24} color={colors.textSecondary} />
        </TouchableOpacity>
      </View>

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scroll}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }>
        {/* Hero carousel */}
        {heroItems.length > 0 && (
          <HeroCarousel
            items={heroItems}
            onPress={goToDetail}
            onPressPlay={item =>
              navigation.navigate('Detail', {
                id: item.id,
                type: item.type,
                name: item.name,
                poster: item.poster,
              })
            }
          />
        )}

        {/* Catalog rows */}
        {rows.map(row => (
          <Row
            key={row.key}
            title={row.title}
            items={row.items}
            loading={row.loading}
            onPressItem={goToDetail}
          />
        ))}

        {rows.length === 0 && !initialLoading && (
          <View style={styles.emptyState}>
            <Icon name="puzzle" size={64} color={colors.textMuted} />
            <Text style={styles.emptyTitle}>No addons installed</Text>
            <Text style={styles.emptyText}>
              Go to the Addons tab to install addons and discover content.
            </Text>
          </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: 12,
  },
  logo: {
    fontSize: 24,
    fontWeight: '800',
    color: colors.primary,
    letterSpacing: 0.5,
  },
  headerBtn: {padding: 8},
  scroll: {paddingBottom: 20},
  emptyState: {
    alignItems: 'center',
    paddingTop: 80,
    paddingHorizontal: 32,
    gap: 12,
  },
  emptyTitle: {...typography.title, color: colors.textSecondary},
  emptyText: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
  },
});
