import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { View, StyleSheet, RefreshControl } from 'react-native';
import { FlashList, FlashListRef } from '@shopify/flash-list';
import type { ListRenderItem } from '@shopify/flash-list';
import { useAppColors, type AppColors } from '../../theme';
import { Text, Loading, EmptyState } from '../../components/common';
import { TradeCard } from '../../components/business/TradeCard/TradeCard';
import { tradeService } from '../../services/trade/tradeService';
import { useIsAuthenticated } from '../../stores/auth';
import type {
  TradeItemDTO,
  TradeCategory,
  TradeType,
} from '../../types/trade';
import { useRouter } from 'expo-router';
import { useResponsive, useResponsiveSpacing } from '../../hooks/useResponsive';

type TradeFilterType = 'all' | 'sell' | 'buy';

const PAGE_SIZE = 20;

function createMarketStyles(colors: AppColors, gap: number, padding: number) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.default,
    },
    listContent: {
      paddingHorizontal: padding,
      paddingTop: gap / 2,
      paddingBottom: 80,
    },
  });
}

interface MarketViewProps {
  onCreateTrade: () => void;
  filterType?: TradeFilterType;
  onFilterTypeChange?: (type: TradeFilterType) => void;
  selectedCategory?: TradeCategory | 'all';
  onSelectedCategoryChange?: (cat: TradeCategory | 'all') => void;
}

export function MarketView({
  onCreateTrade,
  filterType: filterTypeProp,
  onFilterTypeChange,
  selectedCategory: selectedCategoryProp,
  onSelectedCategoryChange,
}: MarketViewProps) {
  const colors = useAppColors();
  const router = useRouter();
  const isAuth = useIsAuthenticated();
  const { width } = useResponsive();

  const gap = useResponsiveSpacing({ xs: 6, sm: 8, md: 10, lg: 12, xl: 16 });
  const padding = useResponsiveSpacing({ xs: 8, sm: 10, md: 12, lg: 16, xl: 20 });
  const styles = useMemo(() => createMarketStyles(colors, gap, padding), [colors, gap, padding]);

  const [items, setItems] = useState<TradeItemDTO[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [cursor, setCursor] = useState<string | undefined>();
  const [filterTypeLocal, setFilterTypeLocal] = useState<TradeFilterType>('all');
  const [selectedCategoryLocal, setSelectedCategoryLocal] = useState<TradeCategory | 'all'>('all');

  const filterType = filterTypeProp ?? filterTypeLocal;
  const selectedCategory = selectedCategoryProp ?? selectedCategoryLocal;
  const setFilterType = onFilterTypeChange ?? setFilterTypeLocal;
  const setSelectedCategory = onSelectedCategoryChange ?? setSelectedCategoryLocal;

  const flashListRef = useRef<FlashListRef<any>>(null);

  // 网格列数：移动端2列，平板3列，桌面4列
  const numColumns = useMemo(() => {
    if (width >= 1200) return 4;
    if (width >= 768) return 3;
    return 2;
  }, [width]);

  const fetchItems = useCallback(async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setIsRefreshing(true);
      } else if (!isLoading) {
        return;
      }

      const tradeType = filterType === 'all' ? undefined : (filterType as TradeType);
      const category = selectedCategory === 'all' ? undefined : (selectedCategory as TradeCategory);

      const res = await tradeService.getTradeItems({
        trade_type: tradeType,
        category,
        page_size: PAGE_SIZE,
      });

      setItems(res.list || []);
      setCursor(res.next_cursor);
      setHasMore(res.has_more);
    } catch (e) {
      console.error('Failed to fetch trade items:', e);
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
    }
  }, [filterType, selectedCategory]);

  useEffect(() => {
    setIsLoading(true);
    setCursor(undefined);
    fetchItems(true);
  }, [filterType, selectedCategory]);

  const loadMore = useCallback(async () => {
    if (isLoadingMore || !hasMore || !cursor) return;
    setIsLoadingMore(true);
    try {
      const tradeType = filterType === 'all' ? undefined : (filterType as TradeType);
      const category = selectedCategory === 'all' ? undefined : (selectedCategory as TradeCategory);
      const res = await tradeService.getTradeItems({
        trade_type: tradeType,
        category,
        cursor,
        page_size: PAGE_SIZE,
      });
      setItems(prev => [...prev, ...(res.list || [])]);
      setCursor(res.next_cursor);
      setHasMore(res.has_more);
    } catch (e) {
      console.error('Failed to load more trade items:', e);
    } finally {
      setIsLoadingMore(false);
    }
  }, [isLoadingMore, hasMore, cursor, filterType, selectedCategory]);

  const handlePressItem = useCallback((id: string) => {
    router.push(`/trade/${id}` as any);
  }, [router]);

  const handleFavorite = useCallback(async (id: string) => {
    if (!isAuth) return;
    try {
      const item = items.find(i => i.id === id);
      if (!item) return;
      if (item.is_favorited) {
        await tradeService.unfavorite(id);
      } else {
        await tradeService.favorite(id);
      }
      setItems(prev =>
        prev.map(i =>
          i.id === id
            ? { ...i, is_favorited: !i.is_favorited, favorites_count: i.favorites_count + (i.is_favorited ? -1 : 1) }
            : i
        )
      );
    } catch (e) {
      console.error('Favorite failed:', e);
    }
  }, [items, isAuth]);

  const renderItem = useCallback<ListRenderItem<TradeItemDTO>>(({ item }) => (
    <View style={{ marginBottom: gap }}>
      <TradeCard
        item={item}
        variant="grid"
        onPress={handlePressItem}
        onFavorite={handleFavorite}
      />
    </View>
  ), [handlePressItem, handleFavorite, gap]);

  const keyExtractor = useCallback((item: TradeItemDTO) => item.id, []);

  if (isLoading) {
    return <Loading fullScreen />;
  }

  return (
    <View style={styles.container}>
      <FlashList
        ref={flashListRef as any}
        data={items}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
        numColumns={numColumns}
        key={`market_${numColumns}`}
        contentContainerStyle={styles.listContent}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={() => fetchItems(true)}
            colors={[colors.primary.main]}
            tintColor={colors.primary.main}
          />
        }
        onEndReached={loadMore}
        onEndReachedThreshold={0.3}
        ListEmptyComponent={
          <EmptyState
            title="暂无商品"
            description="还没有人发布商品，快来发布第一条吧"
          />
        }
        ListFooterComponent={isLoadingMore ? <Loading size="sm" /> : null}
        drawDistance={250}
        masonry
      />
    </View>
  );
}
