import { HeaderBar } from '@/components/ui/HeaderBar';
import { Colors } from '@/constants/Colors';
import { useSafeAreaTop } from '@/hooks/useSafeAreaWithPadding';
import {
  getNutritionAnalysisRecords,
  type GetNutritionRecordsParams,
  type NutritionAnalysisRecord,
  type NutritionItem
} from '@/services/nutritionLabelAnalysis';
import { triggerLightHaptic } from '@/utils/haptics';
import { Ionicons } from '@expo/vector-icons';
import dayjs from 'dayjs';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { useRouter } from 'expo-router';
import React, { useCallback, useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  RefreshControl,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';

export default function NutritionAnalysisHistoryScreen() {
  const safeAreaTop = useSafeAreaTop();
  const router = useRouter();

  const [records, setRecords] = useState<NutritionAnalysisRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [total, setTotal] = useState(0);
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [error, setError] = useState<string | null>(null);

  // 获取历史记录
  const fetchRecords = useCallback(async (page: number = 1, isRefresh: boolean = false, currentStatusFilter?: string) => {
    try {
      // 清除之前的错误
      setError(null);

      const params: GetNutritionRecordsParams = {
        page,
        limit: 20,
      };

      // 使用传入的筛选条件或当前状态
      const filterToUse = currentStatusFilter !== undefined ? currentStatusFilter : statusFilter;
      if (filterToUse) {
        params.status = filterToUse;
      }

      const response = await getNutritionAnalysisRecords(params);

      console.log('response', JSON.stringify(response));

      if (response.code === 0) {
        const newRecords = response.data.records;

        if (isRefresh || page === 1) {
          setRecords(newRecords);
        } else {
          setRecords(prev => [...prev, ...newRecords]);
        }

        setTotal(response.data.total);
        setHasMore(page < response.data.totalPages);
        setCurrentPage(page);
      } else {
        const errorMessage = response.message || '获取历史记录失败';
        setError(errorMessage);
        Alert.alert('错误', errorMessage);
      }
    } catch (error) {
      console.error('[HISTORY] 获取历史记录失败:', error);
      const errorMessage = '获取历史记录失败，请稍后重试';
      setError(errorMessage);
      Alert.alert('错误', errorMessage);
    } finally {
      setLoading(false);
      setRefreshing(false);
      setLoadingMore(false);
    }
  }, [statusFilter]);

  // 初始加载 - 只在组件挂载时执行一次
  useEffect(() => {
    setLoading(true);
    fetchRecords(1, true);
  }, []); // 移除 fetchRecords 依赖，避免循环

  // 筛选条件变化时的处理
  useEffect(() => {
    // 只有在非初始加载时才执行
    if (!loading) {
      setLoading(true);
      setCurrentPage(1);
      fetchRecords(1, true, statusFilter);
    }
  }, [statusFilter]); // 只依赖 statusFilter

  // 下拉刷新
  const handleRefresh = useCallback(() => {
    setRefreshing(true);
    fetchRecords(1, true);
  }, []); // 移除 fetchRecords 依赖

  // 加载更多
  const handleLoadMore = useCallback(() => {
    if (!hasMore || loadingMore || loading || error) return; // 添加错误状态检查

    setLoadingMore(true);
    fetchRecords(currentPage + 1, false);
  }, [hasMore, loadingMore, loading, currentPage, error]); // 移除 fetchRecords 依赖，添加 error 依赖

  // 切换展开状态
  const toggleExpanded = useCallback((id: number) => {
    triggerLightHaptic();
    setExpandedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  }, []);

  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success':
        return '#4CAF50';
      case 'failed':
        return '#F44336';
      case 'processing':
        return '#FF9800';
      default:
        return '#9E9E9E';
    }
  };

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'success':
        return '成功';
      case 'failed':
        return '失败';
      case 'processing':
        return '处理中';
      default:
        return '未知';
    }
  };

  // 从营养数据中提取主要营养素的辅助函数
  const getMainNutrients = (data: NutritionItem[]) => {
    const energy = data.find(item => item.key === 'energy_kcal');
    const protein = data.find(item => item.key === 'protein');
    const carbs = data.find(item => item.key === 'carbohydrate');
    const fat = data.find(item => item.key === 'fat');

    return {
      energy: energy?.value || '',
      protein: protein?.value || '',
      carbs: carbs?.value || '',
      fat: fat?.value || ''
    };
  };

  // 渲染历史记录项
  const renderRecordItem = useCallback(({ item }: { item: NutritionAnalysisRecord }) => {
    const isExpanded = expandedItems.has(item.id);
    const isSuccess = item.status === 'success';

    return (
      <View style={styles.recordItem}>
        {/* 头部信息 */}
        <View style={styles.recordHeader}>
          <View style={styles.recordInfo}>
            <Text style={styles.recordDate}>
              {dayjs(item.createdAt).format('YYYY年M月D日 HH:mm')}
            </Text>
            <View style={[styles.statusBadge, { backgroundColor: getStatusColor(item.status) }]}>
              <Text style={styles.statusText}>{getStatusText(item.status)}</Text>
            </View>
          </View>

          {isSuccess && (
            <Text style={styles.nutritionCount}>
              识别 {item.nutritionCount} 项营养素
            </Text>
          )}
        </View>

        {/* 图片预览 */}
        {item.imageUrl && (
          <View style={styles.imageContainer}>
            <Image
              source={{ uri: item.imageUrl }}
              style={styles.thumbnail}
              contentFit="cover"
            />
          </View>
        )}

        {/* 分析结果摘要 */}
        {isSuccess && item.analysisResult && item.analysisResult.data && item.analysisResult.data.length > 0 && (
          <View style={styles.summaryContainer}>
            <View style={styles.nutritionSummary}>
              {(() => {
                const mainNutrients = getMainNutrients(item.analysisResult.data);
                return (
                  <>
                    {mainNutrients.energy && (
                      <View style={styles.nutritionItem}>
                        <Text style={styles.nutritionLabel}>热量</Text>
                        <Text style={styles.nutritionValue}>{mainNutrients.energy}</Text>
                      </View>
                    )}
                    {mainNutrients.protein && (
                      <View style={styles.nutritionItem}>
                        <Text style={styles.nutritionLabel}>蛋白质</Text>
                        <Text style={styles.nutritionValue}>{mainNutrients.protein}</Text>
                      </View>
                    )}
                    {mainNutrients.carbs && (
                      <View style={styles.nutritionItem}>
                        <Text style={styles.nutritionLabel}>碳水</Text>
                        <Text style={styles.nutritionValue}>{mainNutrients.carbs}</Text>
                      </View>
                    )}
                    {mainNutrients.fat && (
                      <View style={styles.nutritionItem}>
                        <Text style={styles.nutritionLabel}>脂肪</Text>
                        <Text style={styles.nutritionValue}>{mainNutrients.fat}</Text>
                      </View>
                    )}
                  </>
                );
              })()}
            </View>
          </View>
        )}

        {/* 失败信息 */}
        {!isSuccess && (
          <View style={styles.errorContainer}>
            <Ionicons name="alert-circle-outline" size={20} color="#F44336" />
            <Text style={styles.errorMessage}>{item.message}</Text>
          </View>
        )}

        {/* 展开/收起按钮 */}
        <TouchableOpacity
          style={styles.expandButton}
          onPress={() => toggleExpanded(item.id)}
          activeOpacity={0.7}
        >
          <Text style={styles.expandButtonText}>
            {isExpanded ? '收起详情' : '展开详情'}
          </Text>
          <Ionicons
            name={isExpanded ? 'chevron-up-outline' : 'chevron-down-outline'}
            size={16}
            color={Colors.light.primary}
          />
        </TouchableOpacity>

        {/* 详细信息 */}
        {isExpanded && isSuccess && item.analysisResult && item.analysisResult.data && (
          <View style={styles.detailsContainer}>
            <Text style={styles.detailsTitle}>详细营养成分</Text>
            {item.analysisResult.data.map((nutritionItem: NutritionItem) => (
              <View key={nutritionItem.key} style={styles.detailItem}>
                <View style={styles.nutritionInfo}>
                  <Text style={styles.detailLabel}>{nutritionItem.name}</Text>
                  <Text style={styles.detailValue}>{nutritionItem.value}</Text>
                </View>
                {nutritionItem.analysis && (
                  <Text style={styles.analysisText}>{nutritionItem.analysis}</Text>
                )}
              </View>
            ))}

            <View style={styles.metaInfo}>
              <Text style={styles.metaText}>AI 模型: {item.aiModel}</Text>
              <Text style={styles.metaText}>服务提供商: {item.aiProvider}</Text>
            </View>
          </View>
        )}
      </View>
    );
  }, [expandedItems, toggleExpanded]);

  // 渲染空状态
  const renderEmptyState = () => (
    <View style={styles.emptyState}>
      <Ionicons name="document-text-outline" size={64} color="#CCC" />
      <Text style={styles.emptyStateText}>暂无历史记录</Text>
      <Text style={styles.emptyStateSubtext}>开始识别营养成分表吧</Text>
    </View>
  );

  // 渲染错误状态
  const renderErrorState = () => (
    <View style={styles.errorState}>
      <Ionicons name="alert-circle-outline" size={64} color="#F44336" />
      <Text style={styles.errorStateText}>加载失败</Text>
      <Text style={styles.errorStateSubtext}>{error || '未知错误'}</Text>
      <TouchableOpacity
        style={styles.retryButton}
        onPress={() => {
          setLoading(true);
          fetchRecords(1, true);
        }}
      >
        <Text style={styles.retryButtonText}>重试</Text>
      </TouchableOpacity>
    </View>
  );

  // 渲染底部加载指示器
  const renderFooter = () => {
    if (!loadingMore) return null;

    return (
      <View style={styles.loadingFooter}>
        <ActivityIndicator size="small" color={Colors.light.primary} />
        <Text style={styles.loadingFooterText}>加载更多...</Text>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      {/* 背景渐变 */}
      <LinearGradient
        colors={['#f5e5fbff', '#e5fcfeff', '#eefdffff', '#ffffffff']}
        style={styles.gradientBackground}
        start={{ x: 0, y: 0 }}
        end={{ x: 0, y: 1 }}
      />

      <HeaderBar
        title="历史记录"
        onBack={() => router.back()}
        transparent={true}
      />

      {/* 筛选按钮 */}
      <View style={[styles.filterContainer, { paddingTop: safeAreaTop }]}>
        <TouchableOpacity
          style={[styles.filterButton, !statusFilter && styles.filterButtonActive]}
          onPress={() => {
            if (statusFilter !== '') {
              setStatusFilter('');
              setCurrentPage(1);
              // 直接调用数据获取，不依赖 useEffect
              setLoading(true);
              fetchRecords(1, true, '');
            }
          }}
          activeOpacity={0.7}
        >
          <Text style={[styles.filterButtonText, !statusFilter && styles.filterButtonTextActive]}>
            全部
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.filterButton, statusFilter === 'success' && styles.filterButtonActive]}
          onPress={() => {
            if (statusFilter !== 'success') {
              setStatusFilter('success');
              setCurrentPage(1);
              // 直接调用数据获取，不依赖 useEffect
              setLoading(true);
              fetchRecords(1, true, 'success');
            }
          }}
          activeOpacity={0.7}
        >
          <Text style={[styles.filterButtonText, statusFilter === 'success' && styles.filterButtonTextActive]}>
            成功
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.filterButton, statusFilter === 'failed' && styles.filterButtonActive]}
          onPress={() => {
            if (statusFilter !== 'failed') {
              setStatusFilter('failed');
              setCurrentPage(1);
              // 直接调用数据获取，不依赖 useEffect
              setLoading(true);
              fetchRecords(1, true, 'failed');
            }
          }}
          activeOpacity={0.7}
        >
          <Text style={[styles.filterButtonText, statusFilter === 'failed' && styles.filterButtonTextActive]}>
            失败
          </Text>
        </TouchableOpacity>
      </View>

      {/* 记录列表 */}
      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={Colors.light.primary} />
          <Text style={styles.loadingText}>加载历史记录...</Text>
        </View>
      ) : (
        <FlatList
          data={records}
          renderItem={renderRecordItem}
          keyExtractor={item => item.id.toString()}
          contentContainerStyle={styles.listContainer}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={handleRefresh}
              colors={[Colors.light.primary]}
              tintColor={Colors.light.primary}
            />
          }
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.2} // 提高阈值，减少频繁触发
          ListEmptyComponent={error ? renderErrorState : renderEmptyState} // 错误时显示错误状态
          ListFooterComponent={renderFooter}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5e5fbff',
  },
  gradientBackground: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
  },
  filterContainer: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingBottom: 12,
    gap: 8,
  },
  filterButton: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.7)',
    borderWidth: 1,
    borderColor: '#E0E0E0',
  },
  filterButtonActive: {
    backgroundColor: Colors.light.primary,
    borderColor: Colors.light.primary,
  },
  filterButtonText: {
    fontSize: 14,
    fontWeight: '500',
    color: '#666',
  },
  filterButtonTextActive: {
    color: '#FFF',
  },
  listContainer: {
    paddingHorizontal: 16,
    paddingBottom: 20,
  },
  recordItem: {
    backgroundColor: Colors.light.background,
    borderRadius: 16,
    padding: 16,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  recordHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 12,
  },
  recordInfo: {
    flex: 1,
  },
  recordDate: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.light.text,
    marginBottom: 4,
  },
  statusBadge: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 8,
    alignSelf: 'flex-start',
  },
  statusText: {
    fontSize: 12,
    fontWeight: '500',
    color: '#FFF',
  },
  nutritionCount: {
    fontSize: 14,
    color: Colors.light.textSecondary,
    fontWeight: '500',
  },
  imageContainer: {
    marginBottom: 12,
  },
  thumbnail: {
    width: '100%',
    height: 120,
    borderRadius: 12,
  },
  summaryContainer: {
    marginBottom: 12,
  },
  nutritionSummary: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  nutritionItem: {
    flex: 1,
    minWidth: '45%',
    backgroundColor: 'rgba(74, 144, 226, 0.1)',
    padding: 8,
    borderRadius: 8,
  },
  nutritionLabel: {
    fontSize: 12,
    color: Colors.light.textSecondary,
    marginBottom: 2,
  },
  nutritionValue: {
    fontSize: 14,
    fontWeight: '600',
    color: Colors.light.primary,
  },
  errorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(244, 67, 54, 0.1)',
    padding: 12,
    borderRadius: 8,
    marginBottom: 12,
  },
  errorMessage: {
    fontSize: 14,
    color: '#F44336',
    marginLeft: 8,
    flex: 1,
  },
  expandButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 8,
  },
  expandButtonText: {
    fontSize: 14,
    color: Colors.light.primary,
    fontWeight: '500',
    marginRight: 4,
  },
  detailsContainer: {
    borderTopWidth: 1,
    borderTopColor: '#F0F0F0',
    paddingTop: 16,
    marginTop: 8,
  },
  detailsTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.light.text,
    marginBottom: 12,
  },
  detailItem: {
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#F8F8F8',
  },
  detailLabel: {
    fontSize: 14,
    color: Colors.light.text,
  },
  nutritionInfo: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 4,
  },
  detailValue: {
    fontSize: 14,
    fontWeight: '600',
    color: Colors.light.primary,
  },
  analysisText: {
    fontSize: 12,
    color: Colors.light.textSecondary,
    lineHeight: 16,
    marginTop: 4,
    paddingHorizontal: 8,
    paddingVertical: 4,
    backgroundColor: 'rgba(74, 144, 226, 0.05)',
    borderRadius: 6,
  },
  metaInfo: {
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: '#F0F0F0',
  },
  metaText: {
    fontSize: 12,
    color: Colors.light.textSecondary,
    marginBottom: 4,
  },
  emptyState: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyStateText: {
    fontSize: 18,
    fontWeight: '600',
    color: Colors.light.text,
    marginTop: 16,
  },
  emptyStateSubtext: {
    fontSize: 14,
    color: Colors.light.textSecondary,
    marginTop: 8,
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingText: {
    fontSize: 16,
    color: Colors.light.textSecondary,
    marginTop: 12,
  },
  loadingFooter: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 20,
  },
  loadingFooterText: {
    fontSize: 14,
    color: Colors.light.textSecondary,
    marginLeft: 8,
  },
  errorState: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  errorStateText: {
    fontSize: 18,
    fontWeight: '600',
    color: Colors.light.text,
    marginTop: 16,
  },
  errorStateSubtext: {
    fontSize: 14,
    color: Colors.light.textSecondary,
    marginTop: 8,
    textAlign: 'center',
    paddingHorizontal: 32,
  },
  retryButton: {
    marginTop: 20,
    paddingHorizontal: 24,
    paddingVertical: 12,
    backgroundColor: Colors.light.primary,
    borderRadius: 24,
  },
  retryButtonText: {
    color: '#FFF',
    fontSize: 16,
    fontWeight: '600',
  },
});