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 { colors } from '../../src/constants/colors';
import { api } from '../../src/services/api';
import { useAuth } from '../../src/context/AuthContext';
import { format } from 'date-fns';

export default function ProgressScreen() {
  const { user, refreshUser } = useAuth();
  const [vitals, setVitals] = useState<any[]>([]);
  const [goalPredictions, setGoalPredictions] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [showVitalModal, setShowVitalModal] = useState(false);
  const [isPredicting, setIsPredicting] = useState(false);
  const [newVital, setNewVital] = useState({
    weight_kg: '',
    body_fat_percent: '',
    chest_cm: '',
    waist_cm: '',
    hips_cm: '',
    arms_cm: '',
    thighs_cm: '',
    notes: '',
  });

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

  const loadData = async () => {
    try {
      const [vitalsData, predictions] = await Promise.all([
        api.getVitals(),
        api.getGoalPredictions(),
      ]);
      setVitals(vitalsData);
      setGoalPredictions(predictions);
    } catch (error) {
      console.error('Error loading progress data:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  const handleLogVital = async () => {
    if (!newVital.weight_kg) {
      Alert.alert('Error', 'Please enter your weight');
      return;
    }

    try {
      await api.logVitals({
        ...newVital,
        weight_kg: parseFloat(newVital.weight_kg),
        body_fat_percent: newVital.body_fat_percent ? parseFloat(newVital.body_fat_percent) : null,
        chest_cm: newVital.chest_cm ? parseFloat(newVital.chest_cm) : null,
        waist_cm: newVital.waist_cm ? parseFloat(newVital.waist_cm) : null,
        hips_cm: newVital.hips_cm ? parseFloat(newVital.hips_cm) : null,
        arms_cm: newVital.arms_cm ? parseFloat(newVital.arms_cm) : null,
        thighs_cm: newVital.thighs_cm ? parseFloat(newVital.thighs_cm) : null,
      });
      
      setShowVitalModal(false);
      setNewVital({
        weight_kg: '',
        body_fat_percent: '',
        chest_cm: '',
        waist_cm: '',
        hips_cm: '',
        arms_cm: '',
        thighs_cm: '',
        notes: '',
      });
      loadData();
      refreshUser();
    } catch (error) {
      Alert.alert('Error', 'Failed to log vitals');
    }
  };

  const handlePredictGoals = async () => {
    setIsPredicting(true);
    try {
      const prediction = await api.predictGoals();
      await loadData();
      Alert.alert('AI Prediction', prediction.prediction || 'Goal prediction generated!');
    } catch (error) {
      Alert.alert('Error', 'Failed to generate prediction. Please try again.');
    } finally {
      setIsPredicting(false);
    }
  };

  const getWeightTrend = () => {
    if (vitals.length < 2) return null;
    const recent = vitals[0].weight_kg;
    const previous = vitals[1].weight_kg;
    const diff = recent - previous;
    return {
      value: Math.abs(diff).toFixed(1),
      direction: diff > 0 ? 'up' : diff < 0 ? 'down' : 'same',
    };
  };

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

  const weightTrend = getWeightTrend();

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

      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        {/* Current Stats */}
        <View style={styles.statsGrid}>
          <View style={styles.statCard}>
            <Text style={styles.statLabel}>Current Weight</Text>
            <Text style={styles.statValue}>
              {user?.weight_kg || vitals[0]?.weight_kg || '--'}
              <Text style={styles.statUnit}> kg</Text>
            </Text>
            {weightTrend && (
              <View style={styles.trendBadge}>
                <Ionicons
                  name={weightTrend.direction === 'up' ? 'arrow-up' : weightTrend.direction === 'down' ? 'arrow-down' : 'remove'}
                  size={12}
                  color={weightTrend.direction === 'down' ? colors.success : colors.error}
                />
                <Text
                  style={[
                    styles.trendText,
                    { color: weightTrend.direction === 'down' ? colors.success : colors.error },
                  ]}
                >
                  {weightTrend.value}kg
                </Text>
              </View>
            )}
          </View>
          <View style={styles.statCard}>
            <Text style={styles.statLabel}>BMI</Text>
            <Text style={styles.statValue}>
              {user?.bmi || '--'}
            </Text>
            <Text style={styles.bmiCategory}>
              {user?.bmi ? getBMICategory(user.bmi) : ''}
            </Text>
          </View>
        </View>

        {/* AI Goal Prediction */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>AI Goal Prediction</Text>
            <TouchableOpacity
              style={[styles.aiButton, isPredicting && styles.aiButtonDisabled]}
              onPress={handlePredictGoals}
              disabled={isPredicting}
            >
              {isPredicting ? (
                <ActivityIndicator size="small" color={colors.text} />
              ) : (
                <>
                  <Ionicons name="sparkles" size={16} color={colors.text} />
                  <Text style={styles.aiButtonText}>Generate</Text>
                </>
              )}
            </TouchableOpacity>
          </View>

          {goalPredictions.length > 0 ? (
            <View style={styles.predictionCard}>
              <View style={styles.predictionHeader}>
                <Ionicons name="flag" size={20} color={colors.primary} />
                <Text style={styles.predictionType}>
                  {goalPredictions[0].goal_type?.replace('_', ' ').toUpperCase() || 'GOAL'}
                </Text>
              </View>
              <Text style={styles.predictionText}>{goalPredictions[0].prediction}</Text>
              {goalPredictions[0].timeline_weeks && (
                <Text style={styles.predictionTimeline}>
                  Timeline: {goalPredictions[0].timeline_weeks} weeks
                </Text>
              )}
              {goalPredictions[0].recommendations && goalPredictions[0].recommendations.length > 0 && (
                <View style={styles.recommendations}>
                  <Text style={styles.recommendationsTitle}>Recommendations:</Text>
                  {goalPredictions[0].recommendations.slice(0, 3).map((rec: string, i: number) => (
                    <Text key={i} style={styles.recommendationItem}>• {rec}</Text>
                  ))}
                </View>
              )}
            </View>
          ) : (
            <View style={styles.emptyPrediction}>
              <Ionicons name="sparkles-outline" size={32} color={colors.textMuted} />
              <Text style={styles.emptyPredictionText}>
                Tap "Generate" to get AI-powered goal predictions based on your data
              </Text>
            </View>
          )}
        </View>

        {/* Weight History */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Weight History</Text>
          {vitals.length === 0 ? (
            <View style={styles.emptyHistory}>
              <Ionicons name="analytics-outline" size={48} color={colors.textMuted} />
              <Text style={styles.emptyHistoryText}>No vitals logged yet</Text>
            </View>
          ) : (
            vitals.slice(0, 10).map((vital, index) => (
              <View key={vital.id} style={styles.vitalRow}>
                <View style={styles.vitalDate}>
                  <Text style={styles.vitalDateText}>
                    {format(new Date(vital.created_at), 'MMM d')}
                  </Text>
                </View>
                <View style={styles.vitalBar}>
                  <View style={styles.vitalDot} />
                  {index < vitals.length - 1 && <View style={styles.vitalLine} />}
                </View>
                <View style={styles.vitalData}>
                  <Text style={styles.vitalWeight}>{vital.weight_kg} kg</Text>
                  {vital.bmi && <Text style={styles.vitalBMI}>BMI: {vital.bmi}</Text>}
                  {vital.body_fat_percent && (
                    <Text style={styles.vitalBF}>BF: {vital.body_fat_percent}%</Text>
                  )}
                </View>
              </View>
            ))
          )}
        </View>
      </ScrollView>

      {/* Log Vital Modal */}
      <Modal visible={showVitalModal} 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 Vitals</Text>
              <TouchableOpacity onPress={() => setShowVitalModal(false)}>
                <Ionicons name="close" size={24} color={colors.text} />
              </TouchableOpacity>
            </View>

            <ScrollView style={styles.modalScroll}>
              {/* Weight */}
              <Text style={styles.inputLabel}>Weight (kg) *</Text>
              <TextInput
                style={styles.input}
                placeholder="Enter your weight"
                placeholderTextColor={colors.textMuted}
                keyboardType="decimal-pad"
                value={newVital.weight_kg}
                onChangeText={(text) => setNewVital({ ...newVital, weight_kg: text })}
              />

              {/* Body Fat */}
              <Text style={styles.inputLabel}>Body Fat %</Text>
              <TextInput
                style={styles.input}
                placeholder="Optional"
                placeholderTextColor={colors.textMuted}
                keyboardType="decimal-pad"
                value={newVital.body_fat_percent}
                onChangeText={(text) => setNewVital({ ...newVital, body_fat_percent: text })}
              />

              {/* Measurements */}
              <Text style={styles.inputLabel}>Body Measurements (cm)</Text>
              <View style={styles.measurementGrid}>
                <View style={styles.measurementInput}>
                  <Text style={styles.measurementLabel}>Chest</Text>
                  <TextInput
                    style={styles.measurementField}
                    placeholder="--"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="decimal-pad"
                    value={newVital.chest_cm}
                    onChangeText={(text) => setNewVital({ ...newVital, chest_cm: text })}
                  />
                </View>
                <View style={styles.measurementInput}>
                  <Text style={styles.measurementLabel}>Waist</Text>
                  <TextInput
                    style={styles.measurementField}
                    placeholder="--"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="decimal-pad"
                    value={newVital.waist_cm}
                    onChangeText={(text) => setNewVital({ ...newVital, waist_cm: text })}
                  />
                </View>
                <View style={styles.measurementInput}>
                  <Text style={styles.measurementLabel}>Hips</Text>
                  <TextInput
                    style={styles.measurementField}
                    placeholder="--"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="decimal-pad"
                    value={newVital.hips_cm}
                    onChangeText={(text) => setNewVital({ ...newVital, hips_cm: text })}
                  />
                </View>
                <View style={styles.measurementInput}>
                  <Text style={styles.measurementLabel}>Arms</Text>
                  <TextInput
                    style={styles.measurementField}
                    placeholder="--"
                    placeholderTextColor={colors.textMuted}
                    keyboardType="decimal-pad"
                    value={newVital.arms_cm}
                    onChangeText={(text) => setNewVital({ ...newVital, arms_cm: text })}
                  />
                </View>
              </View>

              {/* Notes */}
              <Text style={styles.inputLabel}>Notes</Text>
              <TextInput
                style={[styles.input, styles.textArea]}
                placeholder="Any notes about your progress"
                placeholderTextColor={colors.textMuted}
                multiline
                numberOfLines={2}
                value={newVital.notes}
                onChangeText={(text) => setNewVital({ ...newVital, notes: text })}
              />
            </ScrollView>

            <TouchableOpacity style={styles.submitButton} onPress={handleLogVital}>
              <Text style={styles.submitButtonText}>Save Vitals</Text>
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
      </Modal>
    </SafeAreaView>
  );
}

const getBMICategory = (bmi: number) => {
  if (bmi < 18.5) return 'Underweight';
  if (bmi < 25) return 'Normal';
  if (bmi < 30) return 'Overweight';
  return 'Obese';
};

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',
  },
  content: {
    flex: 1,
    padding: 20,
    paddingTop: 0,
  },
  statsGrid: {
    flexDirection: 'row',
    gap: 12,
    marginBottom: 24,
  },
  statCard: {
    flex: 1,
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 16,
    alignItems: 'center',
  },
  statLabel: {
    fontSize: 12,
    color: colors.textSecondary,
    marginBottom: 4,
  },
  statValue: {
    fontSize: 32,
    fontWeight: '700',
    color: colors.text,
  },
  statUnit: {
    fontSize: 16,
    fontWeight: '400',
    color: colors.textSecondary,
  },
  trendBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 4,
    gap: 2,
  },
  trendText: {
    fontSize: 12,
    fontWeight: '600',
  },
  bmiCategory: {
    fontSize: 12,
    color: colors.textSecondary,
    marginTop: 4,
  },
  section: {
    marginBottom: 24,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 12,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
  },
  aiButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.primary,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 8,
    gap: 4,
  },
  aiButtonDisabled: {
    opacity: 0.7,
  },
  aiButtonText: {
    fontSize: 12,
    fontWeight: '600',
    color: colors.text,
  },
  predictionCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
  },
  predictionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 12,
  },
  predictionType: {
    fontSize: 12,
    fontWeight: '700',
    color: colors.primary,
    letterSpacing: 1,
  },
  predictionText: {
    fontSize: 15,
    color: colors.text,
    lineHeight: 22,
  },
  predictionTimeline: {
    fontSize: 13,
    color: colors.secondary,
    marginTop: 8,
  },
  recommendations: {
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: colors.border,
  },
  recommendationsTitle: {
    fontSize: 13,
    fontWeight: '600',
    color: colors.textSecondary,
    marginBottom: 8,
  },
  recommendationItem: {
    fontSize: 13,
    color: colors.text,
    marginBottom: 4,
  },
  emptyPrediction: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 24,
    alignItems: 'center',
  },
  emptyPredictionText: {
    fontSize: 13,
    color: colors.textSecondary,
    textAlign: 'center',
    marginTop: 12,
  },
  emptyHistory: {
    alignItems: 'center',
    paddingVertical: 32,
  },
  emptyHistoryText: {
    fontSize: 14,
    color: colors.textSecondary,
    marginTop: 8,
  },
  vitalRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: 0,
  },
  vitalDate: {
    width: 50,
    paddingTop: 2,
  },
  vitalDateText: {
    fontSize: 12,
    color: colors.textMuted,
  },
  vitalBar: {
    width: 24,
    alignItems: 'center',
  },
  vitalDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
    backgroundColor: colors.primary,
  },
  vitalLine: {
    width: 2,
    height: 40,
    backgroundColor: colors.border,
  },
  vitalData: {
    flex: 1,
    paddingLeft: 12,
    paddingBottom: 24,
  },
  vitalWeight: {
    fontSize: 16,
    fontWeight: '600',
    color: colors.text,
  },
  vitalBMI: {
    fontSize: 12,
    color: colors.textSecondary,
    marginTop: 2,
  },
  vitalBF: {
    fontSize: 12,
    color: colors.textSecondary,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.7)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: colors.backgroundLight,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    padding: 20,
    maxHeight: '85%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
  },
  modalScroll: {
    maxHeight: 400,
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.textSecondary,
    marginBottom: 8,
  },
  input: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: colors.text,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: colors.border,
  },
  textArea: {
    height: 60,
    textAlignVertical: 'top',
  },
  measurementGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
    marginBottom: 16,
  },
  measurementInput: {
    width: '48%',
  },
  measurementLabel: {
    fontSize: 11,
    color: colors.textMuted,
    marginBottom: 4,
  },
  measurementField: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: colors.text,
    borderWidth: 1,
    borderColor: colors.border,
    textAlign: 'center',
  },
  submitButton: {
    backgroundColor: colors.primary,
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 12,
  },
  submitButtonText: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '700',
  },
});
