import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Modal,
  Alert,
  RefreshControl,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import { colors } from '../../src/constants/colors';
import { api } from '../../src/services/api';
import { format } from 'date-fns';

export default function MealsScreen() {
  const [meals, setMeals] = useState<any[]>([]);
  const [todaysMeals, setTodaysMeals] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [newMeal, setNewMeal] = useState({
    meal_type: 'lunch',
    description: '',
    photo_base64: '',
    calories: '',
    protein_g: '',
    carbs_g: '',
    fat_g: '',
    fiber_g: '',
  });
  const [aiAnalysis, setAiAnalysis] = useState<any>(null);

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

  const loadMeals = async () => {
    try {
      const [allMeals, todays] = await Promise.all([
        api.getMeals(),
        api.getTodaysMeals(),
      ]);
      setMeals(allMeals);
      setTodaysMeals(todays);
    } catch (error) {
      console.error('Error loading meals:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await loadMeals();
    setRefreshing(false);
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission needed', 'Please grant camera roll permissions');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 0.5,
      base64: true,
    });

    if (!result.canceled && result.assets[0].base64) {
      setNewMeal({ ...newMeal, photo_base64: result.assets[0].base64 });
    }
  };

  const analyzeWithAI = async () => {
    if (!newMeal.description) {
      Alert.alert('Error', 'Please enter a meal description first');
      return;
    }

    setIsAnalyzing(true);
    try {
      const analysis = await api.analyzeMeal(
        newMeal.description,
        newMeal.photo_base64 || undefined
      );
      setAiAnalysis(analysis);
      
      // Auto-fill nutrition data
      setNewMeal({
        ...newMeal,
        calories: analysis.calories?.toString() || '',
        protein_g: analysis.protein_g?.toString() || '',
        carbs_g: analysis.carbs_g?.toString() || '',
        fat_g: analysis.fat_g?.toString() || '',
        fiber_g: analysis.fiber_g?.toString() || '',
      });
    } catch (error) {
      Alert.alert('Error', 'Failed to analyze meal. Please try again.');
    } finally {
      setIsAnalyzing(false);
    }
  };

  const handleLogMeal = async () => {
    if (!newMeal.description) {
      Alert.alert('Error', 'Please enter a meal description');
      return;
    }

    try {
      await api.logMeal({
        ...newMeal,
        calories: newMeal.calories ? parseInt(newMeal.calories) : null,
        protein_g: newMeal.protein_g ? parseFloat(newMeal.protein_g) : null,
        carbs_g: newMeal.carbs_g ? parseFloat(newMeal.carbs_g) : null,
        fat_g: newMeal.fat_g ? parseFloat(newMeal.fat_g) : null,
        fiber_g: newMeal.fiber_g ? parseFloat(newMeal.fiber_g) : null,
        ai_analysis: aiAnalysis,
      });
      
      setShowModal(false);
      setNewMeal({
        meal_type: 'lunch',
        description: '',
        photo_base64: '',
        calories: '',
        protein_g: '',
        carbs_g: '',
        fat_g: '',
        fiber_g: '',
      });
      setAiAnalysis(null);
      loadMeals();
    } catch (error) {
      Alert.alert('Error', 'Failed to log meal');
    }
  };

  const getMealIcon = (type: string) => {
    switch (type) {
      case 'breakfast':
        return 'sunny-outline';
      case 'lunch':
        return 'restaurant-outline';
      case 'dinner':
        return 'moon-outline';
      default:
        return 'nutrition-outline';
    }
  };

  const getTodaysCalories = () => {
    return todaysMeals.reduce((sum, meal) => sum + (meal.calories || 0), 0);
  };

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <View style={styles.header}>
        <Text style={styles.title}>Meals</Text>
        <TouchableOpacity
          style={styles.addButton}
          onPress={() => setShowModal(true)}
        >
          <Ionicons name="add" size={24} color={colors.text} />
        </TouchableOpacity>
      </View>

      {/* Today's Summary */}
      <View style={styles.summaryCard}>
        <View style={styles.summaryItem}>
          <Text style={styles.summaryNumber}>{todaysMeals.length}</Text>
          <Text style={styles.summaryLabel}>Meals Today</Text>
        </View>
        <View style={styles.summaryDivider} />
        <View style={styles.summaryItem}>
          <Text style={styles.summaryNumber}>{getTodaysCalories()}</Text>
          <Text style={styles.summaryLabel}>Calories</Text>
        </View>
      </View>

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        {meals.length === 0 ? (
          <View style={styles.emptyState}>
            <Ionicons name="restaurant-outline" size={64} color={colors.textMuted} />
            <Text style={styles.emptyText}>No meals logged yet</Text>
            <Text style={styles.emptySubtext}>Tap + to log your first meal</Text>
          </View>
        ) : (
          meals.map((meal) => (
            <View key={meal.id} style={styles.mealCard}>
              <View style={styles.mealIcon}>
                <Ionicons
                  name={getMealIcon(meal.meal_type) as any}
                  size={24}
                  color={colors.primary}
                />
              </View>
              <View style={styles.mealInfo}>
                <Text style={styles.mealType}>
                  {meal.meal_type.charAt(0).toUpperCase() + meal.meal_type.slice(1)}
                </Text>
                <Text style={styles.mealDescription} numberOfLines={2}>
                  {meal.description}
                </Text>
                <Text style={styles.mealDate}>
                  {format(new Date(meal.created_at), 'MMM d, h:mm a')}
                </Text>
              </View>
              {meal.calories && (
                <View style={styles.mealCalories}>
                  <Text style={styles.caloriesNumber}>{meal.calories}</Text>
                  <Text style={styles.caloriesLabel}>kcal</Text>
                </View>
              )}
            </View>
          ))
        )}
      </ScrollView>

      {/* Add Meal Modal */}
      <Modal visible={showModal} animationType="slide" transparent>
        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
          style={styles.modalOverlay}
        >
          <View style={styles.modalContent}>
            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>Log Meal</Text>
              <TouchableOpacity onPress={() => setShowModal(false)}>
                <Ionicons name="close" size={24} color={colors.text} />
              </TouchableOpacity>
            </View>

            <ScrollView style={styles.modalScroll}>
              {/* Meal Type Selection */}
              <View style={styles.mealTypeRow}>
                {['breakfast', 'lunch', 'dinner', 'snack'].map((type) => (
                  <TouchableOpacity
                    key={type}
                    style={[
                      styles.mealTypeButton,
                      newMeal.meal_type === type && styles.mealTypeActive,
                    ]}
                    onPress={() => setNewMeal({ ...newMeal, meal_type: type })}
                  >
                    <Ionicons
                      name={getMealIcon(type) as any}
                      size={20}
                      color={newMeal.meal_type === type ? colors.primary : colors.textMuted}
                    />
                    <Text
                      style={[
                        styles.mealTypeText,
                        newMeal.meal_type === type && styles.mealTypeTextActive,
                      ]}
                    >
                      {type.charAt(0).toUpperCase() + type.slice(1)}
                    </Text>
                  </TouchableOpacity>
                ))}
              </View>

              {/* Description */}
              <TextInput
                style={[styles.input, styles.textArea]}
                placeholder="What did you eat? (e.g., 2 chapati with dal and sabzi)"
                placeholderTextColor={colors.textMuted}
                multiline
                numberOfLines={3}
                value={newMeal.description}
                onChangeText={(text) => setNewMeal({ ...newMeal, description: text })}
              />

              {/* Photo Upload */}
              <TouchableOpacity style={styles.photoButton} onPress={pickImage}>
                <Ionicons
                  name={newMeal.photo_base64 ? 'checkmark-circle' : 'camera-outline'}
                  size={24}
                  color={newMeal.photo_base64 ? colors.success : colors.textMuted}
                />
                <Text style={styles.photoButtonText}>
                  {newMeal.photo_base64 ? 'Photo Added' : 'Add Photo (Optional)'}
                </Text>
              </TouchableOpacity>

              {/* AI Analysis Button */}
              <TouchableOpacity
                style={[styles.aiButton, isAnalyzing && styles.aiButtonDisabled]}
                onPress={analyzeWithAI}
                disabled={isAnalyzing}
              >
                {isAnalyzing ? (
                  <ActivityIndicator color={colors.text} size="small" />
                ) : (
                  <Ionicons name="sparkles" size={20} color={colors.text} />
                )}
                <Text style={styles.aiButtonText}>
                  {isAnalyzing ? 'Analyzing...' : 'Analyze with AI'}
                </Text>
              </TouchableOpacity>

              {/* AI Analysis Result */}
              {aiAnalysis && (
                <View style={styles.analysisResult}>
                  <Text style={styles.analysisTitle}>AI Analysis</Text>
                  {aiAnalysis.food_items && (
                    <Text style={styles.analysisItems}>
                      Items: {aiAnalysis.food_items.join(', ')}
                    </Text>
                  )}
                  {aiAnalysis.health_rating && (
                    <Text style={styles.analysisRating}>
                      Health Rating: {aiAnalysis.health_rating}/10
                    </Text>
                  )}
                  {aiAnalysis.suggestions && aiAnalysis.suggestions.length > 0 && (
                    <View style={styles.suggestionsList}>
                      {aiAnalysis.suggestions.map((s: string, i: number) => (
                        <Text key={i} style={styles.suggestionItem}>
                          • {s}
                        </Text>
                      ))}
                    </View>
                  )}
                </View>
              )}

              {/* Nutrition Inputs */}
              <Text style={styles.sectionLabel}>Nutrition (auto-filled by AI)</Text>
              <View style={styles.nutritionGrid}>
                <View style={styles.nutritionInput}>
                  <Text style={styles.nutritionLabel}>Calories</Text>
                  <TextInput
                    style={styles.nutritionField}
                    placeholder="0"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="numeric"
                    value={newMeal.calories}
                    onChangeText={(text) => setNewMeal({ ...newMeal, calories: text })}
                  />
                </View>
                <View style={styles.nutritionInput}>
                  <Text style={styles.nutritionLabel}>Protein (g)</Text>
                  <TextInput
                    style={styles.nutritionField}
                    placeholder="0"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="numeric"
                    value={newMeal.protein_g}
                    onChangeText={(text) => setNewMeal({ ...newMeal, protein_g: text })}
                  />
                </View>
                <View style={styles.nutritionInput}>
                  <Text style={styles.nutritionLabel}>Carbs (g)</Text>
                  <TextInput
                    style={styles.nutritionField}
                    placeholder="0"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="numeric"
                    value={newMeal.carbs_g}
                    onChangeText={(text) => setNewMeal({ ...newMeal, carbs_g: text })}
                  />
                </View>
                <View style={styles.nutritionInput}>
                  <Text style={styles.nutritionLabel}>Fat (g)</Text>
                  <TextInput
                    style={styles.nutritionField}
                    placeholder="0"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="numeric"
                    value={newMeal.fat_g}
                    onChangeText={(text) => setNewMeal({ ...newMeal, fat_g: text })}
                  />
                </View>
              </View>
            </ScrollView>

            <TouchableOpacity style={styles.submitButton} onPress={handleLogMeal}>
              <Text style={styles.submitButtonText}>Log Meal</Text>
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 20,
    paddingBottom: 12,
  },
  title: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.text,
  },
  addButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  summaryCard: {
    flexDirection: 'row',
    backgroundColor: colors.backgroundCard,
    marginHorizontal: 20,
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  summaryItem: {
    flex: 1,
    alignItems: 'center',
  },
  summaryNumber: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.primary,
  },
  summaryLabel: {
    fontSize: 12,
    color: colors.textSecondary,
    marginTop: 4,
  },
  summaryDivider: {
    width: 1,
    backgroundColor: colors.border,
    marginHorizontal: 16,
  },
  content: {
    flex: 1,
    paddingHorizontal: 20,
  },
  emptyState: {
    alignItems: 'center',
    paddingTop: 60,
  },
  emptyText: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
    marginTop: 16,
  },
  emptySubtext: {
    fontSize: 14,
    color: colors.textSecondary,
    marginTop: 4,
  },
  mealCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    marginBottom: 12,
  },
  mealIcon: {
    width: 48,
    height: 48,
    borderRadius: 12,
    backgroundColor: 'rgba(255, 107, 53, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  mealInfo: {
    flex: 1,
  },
  mealType: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.primary,
  },
  mealDescription: {
    fontSize: 14,
    color: colors.text,
    marginTop: 2,
  },
  mealDate: {
    fontSize: 11,
    color: colors.textMuted,
    marginTop: 4,
  },
  mealCalories: {
    alignItems: 'center',
  },
  caloriesNumber: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
  },
  caloriesLabel: {
    fontSize: 10,
    color: colors.textMuted,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.7)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: colors.backgroundLight,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    padding: 20,
    maxHeight: '90%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
  },
  modalScroll: {
    maxHeight: 450,
  },
  mealTypeRow: {
    flexDirection: 'row',
    gap: 8,
    marginBottom: 16,
  },
  mealTypeButton: {
    flex: 1,
    alignItems: 'center',
    padding: 10,
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    gap: 4,
  },
  mealTypeActive: {
    backgroundColor: 'rgba(255, 107, 53, 0.1)',
    borderWidth: 1,
    borderColor: colors.primary,
  },
  mealTypeText: {
    fontSize: 10,
    color: colors.textMuted,
  },
  mealTypeTextActive: {
    color: colors.primary,
  },
  input: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: colors.text,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: colors.border,
  },
  textArea: {
    height: 80,
    textAlignVertical: 'top',
  },
  photoButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 14,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: colors.border,
    borderStyle: 'dashed',
    gap: 8,
  },
  photoButtonText: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  aiButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.primary,
    borderRadius: 8,
    padding: 14,
    marginBottom: 16,
    gap: 8,
  },
  aiButtonDisabled: {
    opacity: 0.7,
  },
  aiButtonText: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.text,
  },
  analysisResult: {
    backgroundColor: 'rgba(29, 185, 84, 0.1)',
    borderRadius: 8,
    padding: 12,
    marginBottom: 16,
  },
  analysisTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.secondary,
    marginBottom: 8,
  },
  analysisItems: {
    fontSize: 13,
    color: colors.text,
    marginBottom: 4,
  },
  analysisRating: {
    fontSize: 13,
    color: colors.text,
    marginBottom: 4,
  },
  suggestionsList: {
    marginTop: 8,
  },
  suggestionItem: {
    fontSize: 12,
    color: colors.textSecondary,
    marginBottom: 2,
  },
  sectionLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.textSecondary,
    marginBottom: 8,
  },
  nutritionGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  nutritionInput: {
    width: '48%',
  },
  nutritionLabel: {
    fontSize: 12,
    color: colors.textMuted,
    marginBottom: 4,
  },
  nutritionField: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: colors.text,
    borderWidth: 1,
    borderColor: colors.border,
  },
  submitButton: {
    backgroundColor: colors.primary,
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 12,
  },
  submitButtonText: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '700',
  },
});
