import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  TouchableOpacity,
  ActivityIndicator,
  Dimensions,
} 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';

const { width } = Dimensions.get('window');

export default function UserDashboard() {
  const { user, refreshUser } = useAuth();
  const [stats, setStats] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

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

  const loadData = async () => {
    try {
      const data = await api.getDashboardStats();
      setStats(data);
      await refreshUser();
    } catch (error) {
      console.error('Error loading dashboard:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  const getProgressPercent = (current: number, target: number) => {
    if (!target) return 0;
    return Math.min((current / target) * 100, 100);
  };

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

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <ScrollView
        style={styles.content}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        {/* Header */}
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>Good {getGreeting()},</Text>
            <Text style={styles.name}>{user?.name || 'User'}</Text>
          </View>
          <View style={styles.logoContainer}>
            <Text style={styles.logoText}>ABBAS</Text>
            <Text style={styles.logoSubtext}>FIT</Text>
          </View>
        </View>

        {/* BMI Card */}
        {user?.bmi && (
          <View style={styles.bmiCard}>
            <View style={styles.bmiHeader}>
              <Text style={styles.bmiTitle}>Your BMI</Text>
              <Text style={styles.bmiValue}>{user.bmi}</Text>
            </View>
            <Text style={styles.bmiCategory}>{getBMICategory(user.bmi)}</Text>
            <View style={styles.bmiBar}>
              <View
                style={[
                  styles.bmiIndicator,
                  { left: `${getBMIPosition(user.bmi)}%` },
                ]}
              />
            </View>
            <View style={styles.bmiLabels}>
              <Text style={styles.bmiLabel}>Underweight</Text>
              <Text style={styles.bmiLabel}>Normal</Text>
              <Text style={styles.bmiLabel}>Overweight</Text>
              <Text style={styles.bmiLabel}>Obese</Text>
            </View>
          </View>
        )}

        {/* Today's Progress */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Today's Progress</Text>
          <View style={styles.progressGrid}>
            <View style={styles.progressCard}>
              <View style={styles.progressHeader}>
                <Ionicons name="flame" size={20} color={colors.primary} />
                <Text style={styles.progressLabel}>Calories</Text>
              </View>
              <Text style={styles.progressValue}>
                {stats?.today?.calories_consumed || 0}
                <Text style={styles.progressTarget}>
                  /{stats?.targets?.calories || 2000}
                </Text>
              </Text>
              <View style={styles.progressBar}>
                <View
                  style={[
                    styles.progressFill,
                    {
                      width: `${getProgressPercent(
                        stats?.today?.calories_consumed || 0,
                        stats?.targets?.calories || 2000
                      )}%`,
                      backgroundColor: colors.primary,
                    },
                  ]}
                />
              </View>
            </View>

            <View style={styles.progressCard}>
              <View style={styles.progressHeader}>
                <Ionicons name="fish" size={20} color={colors.secondary} />
                <Text style={styles.progressLabel}>Protein</Text>
              </View>
              <Text style={styles.progressValue}>
                {stats?.today?.protein_consumed || 0}g
                <Text style={styles.progressTarget}>
                  /{stats?.targets?.protein || 150}g
                </Text>
              </Text>
              <View style={styles.progressBar}>
                <View
                  style={[
                    styles.progressFill,
                    {
                      width: `${getProgressPercent(
                        stats?.today?.protein_consumed || 0,
                        stats?.targets?.protein || 150
                      )}%`,
                      backgroundColor: colors.secondary,
                    },
                  ]}
                />
              </View>
            </View>

            <View style={styles.progressCard}>
              <View style={styles.progressHeader}>
                <Ionicons name="water" size={20} color={colors.info} />
                <Text style={styles.progressLabel}>Fat</Text>
              </View>
              <Text style={styles.progressValue}>
                {stats?.today?.fat_consumed || 0}g
                <Text style={styles.progressTarget}>
                  /{stats?.targets?.fat || 65}g
                </Text>
              </Text>
              <View style={styles.progressBar}>
                <View
                  style={[
                    styles.progressFill,
                    {
                      width: `${getProgressPercent(
                        stats?.today?.fat_consumed || 0,
                        stats?.targets?.fat || 65
                      )}%`,
                      backgroundColor: colors.info,
                    },
                  ]}
                />
              </View>
            </View>

            <View style={styles.progressCard}>
              <View style={styles.progressHeader}>
                <Ionicons name="leaf" size={20} color={colors.warning} />
                <Text style={styles.progressLabel}>Fiber</Text>
              </View>
              <Text style={styles.progressValue}>
                {stats?.today?.fiber_consumed || 0}g
                <Text style={styles.progressTarget}>
                  /{stats?.targets?.fiber || 30}g
                </Text>
              </Text>
              <View style={styles.progressBar}>
                <View
                  style={[
                    styles.progressFill,
                    {
                      width: `${getProgressPercent(
                        stats?.today?.fiber_consumed || 0,
                        stats?.targets?.fiber || 30
                      )}%`,
                      backgroundColor: colors.warning,
                    },
                  ]}
                />
              </View>
            </View>
          </View>
        </View>

        {/* Today's Activity */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Today's Summary</Text>
          <View style={styles.summaryRow}>
            <View style={styles.summaryCard}>
              <Ionicons name="restaurant" size={24} color={colors.primary} />
              <Text style={styles.summaryNumber}>{stats?.today?.meals_count || 0}</Text>
              <Text style={styles.summaryLabel}>Meals Logged</Text>
            </View>
            <View style={styles.summaryCard}>
              <Ionicons name="fitness" size={24} color={colors.secondary} />
              <Text style={styles.summaryNumber}>{stats?.today?.activities_count || 0}</Text>
              <Text style={styles.summaryLabel}>Activities</Text>
            </View>
            <View style={styles.summaryCard}>
              <Ionicons name="flame-outline" size={24} color={colors.error} />
              <Text style={styles.summaryNumber}>{stats?.today?.calories_burned || 0}</Text>
              <Text style={styles.summaryLabel}>Cal Burned</Text>
            </View>
          </View>
        </View>

        {/* Quick Actions */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Quick Actions</Text>
          <View style={styles.actionsRow}>
            <TouchableOpacity style={styles.actionButton}>
              <Ionicons name="add-circle" size={24} color={colors.text} />
              <Text style={styles.actionText}>Log Meal</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionButton}>
              <Ionicons name="barbell" size={24} color={colors.text} />
              <Text style={styles.actionText}>Log Activity</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.actionButton}>
              <Ionicons name="scale" size={24} color={colors.text} />
              <Text style={styles.actionText}>Log Weight</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* BMR Info */}
        {user?.bmr && (
          <View style={styles.infoCard}>
            <Ionicons name="information-circle" size={20} color={colors.info} />
            <View style={styles.infoContent}>
              <Text style={styles.infoTitle}>Your BMR: {user.bmr} kcal/day</Text>
              <Text style={styles.infoText}>
                This is the number of calories your body burns at rest. To maintain weight, you need approximately this many calories daily.
              </Text>
            </View>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 12) return 'morning';
  if (hour < 17) return 'afternoon';
  return 'evening';
};

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

const getBMIPosition = (bmi: number) => {
  if (bmi < 18.5) return (bmi / 18.5) * 25;
  if (bmi < 25) return 25 + ((bmi - 18.5) / 6.5) * 25;
  if (bmi < 30) return 50 + ((bmi - 25) / 5) * 25;
  return Math.min(75 + ((bmi - 30) / 10) * 25, 95);
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 24,
  },
  greeting: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  name: {
    fontSize: 24,
    fontWeight: '700',
    color: colors.text,
  },
  logoContainer: {
    flexDirection: 'row',
    alignItems: 'baseline',
  },
  logoText: {
    fontSize: 18,
    fontWeight: '900',
    color: colors.text,
    letterSpacing: 2,
  },
  logoSubtext: {
    fontSize: 18,
    fontWeight: '900',
    color: colors.primary,
    letterSpacing: 2,
  },
  bmiCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 20,
    marginBottom: 24,
  },
  bmiHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  bmiTitle: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  bmiValue: {
    fontSize: 32,
    fontWeight: '700',
    color: colors.primary,
  },
  bmiCategory: {
    fontSize: 16,
    color: colors.text,
    marginTop: 4,
  },
  bmiBar: {
    height: 8,
    borderRadius: 4,
    backgroundColor: colors.border,
    marginTop: 16,
    position: 'relative',
    overflow: 'visible',
  },
  bmiIndicator: {
    position: 'absolute',
    top: -4,
    width: 16,
    height: 16,
    borderRadius: 8,
    backgroundColor: colors.primary,
    borderWidth: 2,
    borderColor: colors.text,
  },
  bmiLabels: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  bmiLabel: {
    fontSize: 10,
    color: colors.textMuted,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: colors.text,
    marginBottom: 12,
  },
  progressGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  progressCard: {
    width: (width - 52) / 2,
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 14,
  },
  progressHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 8,
  },
  progressLabel: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  progressValue: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
    marginBottom: 8,
  },
  progressTarget: {
    fontSize: 14,
    fontWeight: '400',
    color: colors.textMuted,
  },
  progressBar: {
    height: 6,
    borderRadius: 3,
    backgroundColor: colors.border,
  },
  progressFill: {
    height: '100%',
    borderRadius: 3,
  },
  summaryRow: {
    flexDirection: 'row',
    gap: 12,
  },
  summaryCard: {
    flex: 1,
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 14,
    alignItems: 'center',
  },
  summaryNumber: {
    fontSize: 24,
    fontWeight: '700',
    color: colors.text,
    marginTop: 8,
  },
  summaryLabel: {
    fontSize: 11,
    color: colors.textSecondary,
    marginTop: 4,
    textAlign: 'center',
  },
  actionsRow: {
    flexDirection: 'row',
    gap: 12,
  },
  actionButton: {
    flex: 1,
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    alignItems: 'center',
    gap: 8,
  },
  actionText: {
    fontSize: 12,
    color: colors.text,
    fontWeight: '500',
  },
  infoCard: {
    flexDirection: 'row',
    backgroundColor: 'rgba(59, 130, 246, 0.1)',
    borderRadius: 12,
    padding: 16,
    gap: 12,
    marginBottom: 24,
  },
  infoContent: {
    flex: 1,
  },
  infoTitle: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.info,
    marginBottom: 4,
  },
  infoText: {
    fontSize: 12,
    color: colors.textSecondary,
    lineHeight: 18,
  },
});
