import React, { useEffect, useMemo, useState } from 'react';
import { FlatList, StyleSheet, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';

import SheetModal from '@/components/ui/SheetModal';
import { MOCK_CONTENT } from '@/src/constants/mockContent';
import { getFavorites, getRecoFeedCache, type FavoriteItem } from '@/src/storage/appStorage';

type Props = {
  visible: boolean;
  onClose: () => void;
};

export default function FavoritesModal({ visible, onClose }: Props) {
  const { t } = useTranslation();
  const [items, setItems] = useState<(FavoriteItem & { text: string })[]>([]);

  // 每次打开时刷新一次，确保展示最新“喜欢”
  useEffect(() => {
    if (!visible) return;
    let cancelled = false;
    (async () => {
      const [favList, cache] = await Promise.all([
        getFavorites(),
        getRecoFeedCache()
      ]);
      console.log('FavoritesModal: Loaded favList', favList.length, 'items');
      console.log('FavoritesModal: Loaded cache items', cache?.items?.length || 0);

      if (cancelled) return;

      // 建立文案查找表
      const textMap = new Map<string, string>();
      
      // 1. 放入 Mock 数据
      MOCK_CONTENT.forEach(c => textMap.set(String(c.id), t(c.textKey)));
      
      // 2. 放入缓存数据
      if (cache?.items) {
        cache.items.forEach(c => textMap.set(String(c.content_id), c.text));
      }

      // 3. 组装最终展示列表
      const enriched = favList.map(fav => {
        const favIdStr = String(fav.id);
        const text = fav.text || textMap.get(favIdStr);
        console.log(`FavoritesModal: Matching fav.id=${favIdStr}, found text=${!!text}, textValue=${text?.substring(0, 10)}...`);
        return {
          ...fav,
          text: text || t('favorites.unknownText')
        };
      });

      setItems(enriched);
    })();
    return () => {
      cancelled = true;
    };
  }, [visible, t]);

  return (
    <SheetModal visible={visible} title={t('profile.favorites')} onClose={onClose}>
      <View style={styles.container}>
        {items.length === 0 ? (
          <Text style={styles.empty}>{t('favorites.empty')}</Text>
        ) : (
          <FlatList
            data={items}
            keyExtractor={(it) => it.favId}
            contentContainerStyle={styles.list}
            renderItem={({ item }) => (
              <View style={styles.row}>
                <Text style={styles.text}>{item.text}</Text>
              </View>
            )}
          />
        )}
      </View>
    </SheetModal>
  );
}

const styles = StyleSheet.create({
  container: {
    borderRadius: 16,
    backgroundColor: 'rgba(255,255,255,0.75)',
    overflow: 'hidden',
    marginBottom: 8,
  },
  empty: {
    color: 'rgba(94,42,40,0.55)',
    fontSize: 15,
    textAlign: 'center',
    paddingVertical: 26,
    paddingHorizontal: 14,
  },
  list: {
    paddingBottom: 10,
  },
  row: {
    paddingHorizontal: 14,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: 'rgba(94,42,40,0.10)',
    backgroundColor: 'rgba(255,255,255,0.15)',
  },
  text: {
    color: '#5E2A28',
    fontSize: 15,
    lineHeight: 22,
    fontWeight: '600',
  },
});

