import { ThemedText } from '@/components/ThemedText';
import { useThemeColor } from '@/hooks/useThemeColor';
import { DietRecord } from '@/services/dietRecords';
import { Ionicons } from '@expo/vector-icons';
import dayjs from 'dayjs';
import { Image } from 'expo-image';
import React, { useMemo, useRef, useState } from 'react';
import { Alert, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { RectButton, Swipeable } from 'react-native-gesture-handler';


export type NutritionRecordCardProps = {
  record: DietRecord;
  onPress?: () => void;
  onDelete?: () => void;
};

const MEAL_TYPE_LABELS = {
  breakfast: '早餐',
  lunch: '午餐',
  dinner: '晚餐',
  snack: '加餐',
  other: '其他',
} as const;

const MEAL_TYPE_ICONS = {
  breakfast: 'sunny-outline',
  lunch: 'partly-sunny-outline',
  dinner: 'moon-outline',
  snack: 'cafe-outline',
  other: 'restaurant-outline',
} as const;

const MEAL_TYPE_COLORS = {
  breakfast: '#FF6B35',
  lunch: '#4CAF50',
  dinner: '#2196F3',
  snack: '#FF7A85',
  other: '#9AA3AE',
} as const;

export function NutritionRecordCard({
  record,
  onPress,
  onDelete
}: NutritionRecordCardProps) {
  const surfaceColor = useThemeColor({}, 'surface');
  const textColor = useThemeColor({}, 'text');
  const textSecondaryColor = useThemeColor({}, 'textSecondary');

  // Popover 状态管理
  const [showPopover, setShowPopover] = useState(false);
  const popoverRef = useRef<any>(null);

  // 左滑删除相关
  const swipeableRef = useRef<Swipeable>(null);

  // 添加滑动状态管理，防止滑动时触发点击事件
  const [isSwiping, setIsSwiping] = useState(false);

  // 营养数据统计
  const nutritionStats = useMemo(() => {
    return [
      {
        label: '蛋白质',
        value: record.proteinGrams ? `${record.proteinGrams.toFixed(1)}g` : '-',
        icon: '🥩',
        color: '#FF6B6B'
      },
      {
        label: '脂肪',
        value: record.fatGrams ? `${record.fatGrams.toFixed(1)}g` : '-',
        icon: '🥑',
        color: '#FFB366'
      },
      {
        label: '碳水',
        value: record.carbohydrateGrams ? `${record.carbohydrateGrams.toFixed(1)}g` : '-',
        icon: '🍞',
        color: '#4ECDC4'
      },
    ];
  }, [record]);

  const mealTypeColor = MEAL_TYPE_COLORS[record.mealType];
  const mealTypeLabel = MEAL_TYPE_LABELS[record.mealType];

  // 处理点击事件，只有在非滑动状态下才触发
  const handlePress = () => {
    if (!isSwiping && onPress) {
      onPress();
    }
  };

  // 处理滑动开始
  const handleSwipeableWillOpen = () => {
    setIsSwiping(true);
  };

  // 处理滑动结束
  const handleSwipeableClose = () => {
    // 延迟重置滑动状态，防止滑动结束时立即触发点击
    setTimeout(() => {
      setIsSwiping(false);
    }, 100);
  };

  // 处理删除操作
  const handleDelete = () => {
    Alert.alert(
      '确认删除',
      `确定要删除这条营养记录吗？此操作无法撤销。`,
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '删除',
          style: 'destructive',
          onPress: () => {
            onDelete?.();
            swipeableRef.current?.close();
          },
        },
      ]
    );
  };

  // 渲染删除按钮
  const renderRightActions = () => {
    return (
      <TouchableOpacity
        style={styles.deleteButton}
        onPress={handleDelete}
        activeOpacity={0.8}
      >
        <Ionicons name="trash" size={20} color="#FFFFFF" />
        <Text style={styles.deleteButtonText}>删除</Text>
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.container}>
      <Swipeable
        ref={swipeableRef}
        renderRightActions={renderRightActions}
        rightThreshold={40}
        overshootRight={false}
        onSwipeableWillOpen={handleSwipeableWillOpen}
        onSwipeableClose={handleSwipeableClose}
      >
        <RectButton
          style={[
            styles.card,

          ]}
          onPress={handlePress}
        // activeOpacity={0.7}
        >
          {/* 主要内容区域 - 水平布局 */}
          <View style={styles.mainContent}>
            {/* 左侧：食物图片 */}
            <View style={[styles.foodImageContainer, !record.imageUrl && styles.foodImagePlaceholder]}>
              {record.imageUrl ? (
                <Image
                  source={{ uri: record.imageUrl }}
                  style={styles.foodImage}
                  cachePolicy={'memory-disk'}
                />
              ) : (
                <Ionicons name="restaurant" size={28} color={textSecondaryColor} />
              )}
            </View>

            {/* 中间：食物信息 */}
            <View style={styles.foodInfoContainer}>
              {/* 食物名称 */}
              <ThemedText style={[styles.foodName, { color: textColor }]}>
                {record.foodName}
              </ThemedText>

              {/* 时间 */}
              <ThemedText style={[styles.mealTime, { color: textSecondaryColor }]}>
                {record.mealTime ? dayjs(record.mealTime).format('HH:mm') : '--:--'}
              </ThemedText>

              {/* 营养信息 - 水平排列 */}
              <View style={styles.nutritionContainer}>
                {nutritionStats.map((stat, index) => (
                  <View key={stat.label} style={styles.nutritionItem}>
                    <ThemedText style={styles.nutritionIcon}>{stat.icon}</ThemedText>
                    <ThemedText style={[styles.nutritionValue, { color: textColor }]}>
                      {stat.value}
                    </ThemedText>
                  </View>
                ))}
              </View>
            </View>

            {/* 右侧：热量和餐次标签 */}
            <View style={styles.rightSection}>
              {/* 热量显示 */}
              <View style={styles.caloriesContainer}>
                <ThemedText style={[styles.caloriesText]}>
                  {record.estimatedCalories ? `${Math.round(record.estimatedCalories)} kcal` : '- kcal'}
                </ThemedText>
              </View>

              {/* 餐次标签 */}
              <View style={[styles.mealTypeBadge]}>
                <ThemedText style={[styles.mealTypeText, { color: mealTypeColor }]}>
                  {mealTypeLabel}
                </ThemedText>
              </View>

            </View>
          </View>
        </RectButton>
      </Swipeable>

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginBottom: 16,
    // iOS 阴影效果 - 更自然的阴影
    shadowColor: '#000000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    // Android 阴影效果
    elevation: 3,
  },
  card: {
    flex: 1,
    minHeight: 100,
    backgroundColor: '#FFFFFF',
    borderRadius: 16,
    paddingHorizontal: 16,
    paddingVertical: 14,
  },
  mainContent: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  foodImageContainer: {
    width: 48,
    height: 48,
    borderRadius: 12,
    marginRight: 16,
    overflow: 'hidden',
  },
  foodImage: {
    width: '100%',
    height: '100%',
    borderRadius: 8,
  },
  foodImagePlaceholder: {
    backgroundColor: '#F8F9FA',
    justifyContent: 'center',
    alignItems: 'center',
  },
  foodInfoContainer: {
    flex: 1,
    justifyContent: 'center',
    gap: 4,
  },
  foodName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333333',
    lineHeight: 20,
  },
  mealTime: {
    fontSize: 12,
    fontWeight: '400',
    color: '#999999',
    lineHeight: 16,
  },
  nutritionContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 16,
    marginTop: 2,
  },
  nutritionItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  nutritionIcon: {
    fontSize: 14,
  },
  nutritionValue: {
    fontSize: 13,
    fontWeight: '500',
    color: '#666666',
  },
  rightSection: {
    alignItems: 'flex-end',
    justifyContent: 'center',
    gap: 8,
    minHeight: 60,
  },
  caloriesContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  caloriesText: {
    fontSize: 14,
    color: '#333333',
    fontWeight: '600',
  },
  mealTypeBadge: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 12,
    backgroundColor: 'rgba(0,0,0,0.05)',
  },
  mealTypeText: {
    fontSize: 12,
    fontWeight: '600',
  },
  moreButton: {
    padding: 2,
  },
  notesSection: {
    marginTop: 8,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: 'rgba(0,0,0,0.06)',
  },
  notesText: {
    fontSize: 13,
    fontWeight: '500',
    lineHeight: 18,
    fontStyle: 'italic',
  },
  popoverContainer: {
    borderRadius: 12,
    backgroundColor: '#FFFFFF',
    // iOS 阴影效果
    shadowColor: '#000000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 12,
    // Android 阴影效果
    elevation: 8,
    // 添加边框
    borderWidth: 0.5,
    borderColor: 'rgba(0, 0, 0, 0.08)',
  },
  popoverBackground: {
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  popoverContent: {
    minWidth: 140,
    paddingVertical: 8,
  },
  popoverItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    gap: 12,
  },
  popoverText: {
    fontSize: 16,
    fontWeight: '500',
  },
  deleteButton: {
    backgroundColor: '#EF4444',
    justifyContent: 'center',
    alignItems: 'center',
    width: 80,
    borderRadius: 12,
    marginLeft: 8,
  },
  deleteButtonText: {
    color: '#FFFFFF',
    fontSize: 12,
    fontWeight: '600',
    marginTop: 4,
  },
});
