import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  Image,
} from "react-native";
import { useUser } from "@clerk/clerk-expo";
import { useState, useCallback, useEffect } from "react";
import { useFocusEffect } from "@react-navigation/native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "../../contexts/ThemeContext";
import { useStatistics } from "../../contexts/StatisticsContext";
import { MinimalCard } from "../../components/MinimalCard";
import { SectionHeader } from "../../components/SectionHeader";
import { IconContainer } from "../../components/IconContainer";
import { ProgressBar } from "../../components/ProgressBar";
import { TrackMealModal } from "../../components/TrackMealModal";
import { AddWaterModal } from "../../components/AddWaterModal";
import { ScanFoodModal } from "../../components/ScanFoodModal";

const CALORIE_GOAL = 2000; // kcal
const WATER_GOAL = 2000; // ml

export default function HomeScreen() {
  const { user } = useUser();
  const { colors, typography } = useTheme();
  const { refetchStatistics, forceRefresh, statistics, loading } =
    useStatistics();
  const [refreshing, setRefreshing] = useState(false);
  const [trackMealModalVisible, setTrackMealModalVisible] = useState(false);
  const [addWaterModalVisible, setAddWaterModalVisible] = useState(false);
  const [scanFoodModalVisible, setScanFoodModalVisible] = useState(false);
  const [calories, setCalories] = useState(0);
  const [waterIntake, setWaterIntake] = useState(0);

  // Refetch statistics when screen comes into focus
  useFocusEffect(
    useCallback(() => {
      refetchStatistics();
    }, [refetchStatistics]),
  );

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await forceRefresh();
    setRefreshing(false);
  }, [forceRefresh]);

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return "Good Morning";
    if (hour < 18) return "Good Afternoon";
    return "Good Evening";
  };

  const handleSaveMeal = (meal: {
    type: string;
    name: string;
    calories: number;
  }) => {
    setCalories((prev) => prev + meal.calories);
    setTrackMealModalVisible(false);
  };

  const handleAddWater = (amount: number) => {
    setWaterIntake((prev) => prev + amount);
    setAddWaterModalVisible(false);
  };

  const handleResetCalories = () => {
    setCalories(0);
  };

  const handleResetWater = () => {
    setWaterIntake(0);
  };

  const handleAddScannedFood = (scannedCalories: number) => {
    setCalories((prev) => prev + scannedCalories);
    setScanFoodModalVisible(false);
  };

  const resetAllCounters = async () => {
    setCalories(0);
    setWaterIntake(0);
    const today = new Date().toDateString();
    await AsyncStorage.setItem("lastResetDate", today);
    await AsyncStorage.removeItem(`calories_${today}`);
    await AsyncStorage.removeItem(`water_${today}`);
  };

  // Load persisted data on mount
  useEffect(() => {
    const loadPersistedData = async () => {
      const today = new Date().toDateString();
      const storedCalories = await AsyncStorage.getItem(`calories_${today}`);
      const storedWater = await AsyncStorage.getItem(`water_${today}`);

      if (storedCalories) {
        setCalories(parseInt(storedCalories, 10));
      }
      if (storedWater) {
        setWaterIntake(parseInt(storedWater, 10));
      }
    };

    loadPersistedData();
  }, []);

  // Persist calories to AsyncStorage whenever it changes
  useEffect(() => {
    const persistCalories = async () => {
      const today = new Date().toDateString();
      await AsyncStorage.setItem(`calories_${today}`, calories.toString());
    };

    persistCalories();
  }, [calories]);

  // Persist water intake to AsyncStorage whenever it changes
  useEffect(() => {
    const persistWater = async () => {
      const today = new Date().toDateString();
      await AsyncStorage.setItem(`water_${today}`, waterIntake.toString());
    };

    persistWater();
  }, [waterIntake]);

  // Check for midnight reset
  useEffect(() => {
    const checkAndResetIfNeeded = async () => {
      const lastResetDate = await AsyncStorage.getItem("lastResetDate");
      const today = new Date().toDateString();

      if (lastResetDate !== today) {
        await resetAllCounters();
      }
    };

    checkAndResetIfNeeded();

    // Calculate time until midnight
    const now = new Date();
    const midnight = new Date();
    midnight.setHours(24, 0, 0, 0);
    const timeUntilMidnight = midnight.getTime() - now.getTime();

    // Set timer for midnight reset
    const midnightTimer = setTimeout(async () => {
      await resetAllCounters();

      // Set up daily interval after first midnight
      const dailyInterval = setInterval(
        async () => {
          await resetAllCounters();
        },
        24 * 60 * 60 * 1000,
      ); // 24 hours

      return () => clearInterval(dailyInterval);
    }, timeUntilMidnight);

    return () => clearTimeout(midnightTimer);
  }, []);

  const checkInsThisWeek = statistics?.attendance.checkInsThisWeek || 0;
  const currentStreak = statistics?.attendance.currentStreak || 0;

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        {/* Header Section */}
        <View style={styles.header}>
          <View>
            <Text style={[typography.body, { color: colors.textSecondary }]}>
              {getGreeting()},
            </Text>
            <Text
              style={[
                typography.h1,
                { color: colors.textPrimary, marginTop: 4 },
              ]}
            >
              {user?.firstName || "Athlete"}
            </Text>
          </View>
          <View>
            {user?.imageUrl ? (
              <Image source={{ uri: user.imageUrl }} style={styles.avatar} />
            ) : (
              <View
                style={[
                  styles.placeholderAvatar,
                  { backgroundColor: colors.primary },
                ]}
              >
                <Ionicons name="person" size={24} color={colors.white} />
              </View>
            )}
          </View>
        </View>

        {/* Daily Stats Card */}
        <View style={styles.section}>
          <MinimalCard variant="elevated">
            <View style={styles.statsRow}>
              <View style={styles.statItem}>
                <IconContainer
                  variant="colored"
                  backgroundColor={`${colors.info}20`}
                >
                  <Ionicons
                    name="checkmark-circle"
                    size={24}
                    color={colors.info}
                  />
                </IconContainer>
                <Text
                  style={[
                    typography.stat,
                    { color: colors.textPrimary, marginTop: 8 },
                  ]}
                >
                  {checkInsThisWeek}
                </Text>
                <Text
                  style={[typography.caption, { color: colors.textTertiary }]}
                >
                  This Week
                </Text>
              </View>

              <View
                style={[styles.divider, { backgroundColor: colors.border }]}
              />

              <View style={styles.statItem}>
                <IconContainer
                  variant="colored"
                  backgroundColor={`${colors.danger}20`}
                >
                  <Ionicons name="flame" size={24} color={colors.danger} />
                </IconContainer>
                <Text
                  style={[
                    typography.stat,
                    { color: colors.textPrimary, marginTop: 8 },
                  ]}
                >
                  {calories}
                </Text>
                <Text
                  style={[typography.caption, { color: colors.textTertiary }]}
                >
                  Kcal
                </Text>
              </View>

              <View
                style={[styles.divider, { backgroundColor: colors.border }]}
              />

              <View style={styles.statItem}>
                <IconContainer
                  variant="colored"
                  backgroundColor={`${colors.success}20`}
                >
                  <Ionicons name="trophy" size={24} color={colors.success} />
                </IconContainer>
                <Text
                  style={[
                    typography.stat,
                    { color: colors.textPrimary, marginTop: 8 },
                  ]}
                >
                  {currentStreak}
                </Text>
                <Text
                  style={[typography.caption, { color: colors.textTertiary }]}
                >
                  Day Streak
                </Text>
              </View>
            </View>
          </MinimalCard>
        </View>

        {/* Quick Actions */}
        <View style={styles.section}>
          <SectionHeader title="Quick Actions" />
          <View style={styles.actionGrid}>
            <MinimalCard
              variant="default"
              onPress={() => {
                console.log("Log workout tapped");
              }}
              style={styles.actionCard}
            >
              <IconContainer
                variant="colored"
                backgroundColor={`${colors.primary}20`}
              >
                <Ionicons name="barbell" size={24} color={colors.primary} />
              </IconContainer>
              <Text
                style={[
                  typography.h3,
                  { color: colors.textPrimary, marginTop: 8 },
                ]}
              >
                Log Workout
              </Text>
            </MinimalCard>

            <MinimalCard
              variant="default"
              onPress={() => setTrackMealModalVisible(true)}
              style={styles.actionCard}
            >
              <IconContainer
                variant="colored"
                backgroundColor={`${colors.success}20`}
              >
                <Ionicons name="restaurant" size={24} color={colors.success} />
              </IconContainer>
              <Text
                style={[
                  typography.h3,
                  { color: colors.textPrimary, marginTop: 8 },
                ]}
              >
                Track Meal
              </Text>
            </MinimalCard>

            <MinimalCard
              variant="default"
              onPress={() => setAddWaterModalVisible(true)}
              style={styles.actionCard}
            >
              <IconContainer
                variant="colored"
                backgroundColor={`${colors.info}20`}
              >
                <Ionicons name="water" size={24} color={colors.info} />
              </IconContainer>
              <Text
                style={[
                  typography.h3,
                  { color: colors.textPrimary, marginTop: 8 },
                ]}
              >
                Add Water
              </Text>
            </MinimalCard>

            <MinimalCard
              variant="default"
              onPress={() => setScanFoodModalVisible(true)}
              style={styles.actionCard}
            >
              <IconContainer
                variant="colored"
                backgroundColor={`${colors.accent}20`}
              >
                <Ionicons name="scan" size={24} color={colors.accent} />
              </IconContainer>
              <Text
                style={[
                  typography.h3,
                  { color: colors.textPrimary, marginTop: 8 },
                ]}
              >
                Scan Food
              </Text>
            </MinimalCard>
          </View>
        </View>

        {/* Nutrition Progress */}
        <View style={styles.section}>
          <SectionHeader title="Nutrition" />
          <MinimalCard variant="default">
            <View style={styles.progressHeader}>
              <View style={styles.progressLabelRow}>
                <Ionicons name="flame" size={20} color={colors.textSecondary} />
                <Text
                  style={[
                    typography.h3,
                    { color: colors.textPrimary, marginLeft: 8 },
                  ]}
                >
                  Calories
                </Text>
              </View>
              <Text
                style={[typography.bodyEmphasis, { color: colors.textPrimary }]}
              >
                {calories} / {CALORIE_GOAL}
              </Text>
            </View>
            <ProgressBar
              progress={calories / CALORIE_GOAL}
              color={colors.danger}
              style={{ marginTop: 12 }}
            />
          </MinimalCard>
        </View>

        {/* Hydration Progress */}
        <View style={styles.section}>
          <MinimalCard variant="default">
            <View style={styles.progressHeader}>
              <View style={styles.progressLabelRow}>
                <Ionicons name="water" size={20} color={colors.textSecondary} />
                <Text
                  style={[
                    typography.h3,
                    { color: colors.textPrimary, marginLeft: 8 },
                  ]}
                >
                  Hydration
                </Text>
              </View>
              <Text
                style={[typography.bodyEmphasis, { color: colors.textPrimary }]}
              >
                {waterIntake} / {WATER_GOAL} ml
              </Text>
            </View>
            <ProgressBar
              progress={waterIntake / WATER_GOAL}
              color={colors.info}
              style={{ marginTop: 12 }}
            />
          </MinimalCard>
        </View>

        {/* Recent Activity */}
        <View style={styles.section}>
          <SectionHeader
            title="Recent Activity"
            actionLabel="See All"
            onActionPress={() => console.log("See all tapped")}
          />

          <View style={styles.activityList}>
            <MinimalCard variant="default" style={styles.activityItem}>
              <IconContainer
                variant="colored"
                backgroundColor={`${colors.primary}20`}
              >
                <Ionicons name="barbell" size={20} color={colors.primary} />
              </IconContainer>
              <View style={styles.activityInfo}>
                <Text style={[typography.h3, { color: colors.textPrimary }]}>
                  Upper Body Power
                </Text>
                <Text
                  style={[
                    typography.caption,
                    { color: colors.textTertiary, marginTop: 2 },
                  ]}
                >
                  Today, 10:00 AM
                </Text>
              </View>
              <Text
                style={[
                  typography.bodyEmphasis,
                  { color: colors.textSecondary },
                ]}
              >
                45m
              </Text>
            </MinimalCard>

            <MinimalCard variant="default" style={styles.activityItem}>
              <IconContainer
                variant="colored"
                backgroundColor={`${colors.success}20`}
              >
                <Ionicons name="bicycle" size={20} color={colors.success} />
              </IconContainer>
              <View style={styles.activityInfo}>
                <Text style={[typography.h3, { color: colors.textPrimary }]}>
                  Morning Cardio
                </Text>
                <Text
                  style={[
                    typography.caption,
                    { color: colors.textTertiary, marginTop: 2 },
                  ]}
                >
                  Yesterday, 7:30 AM
                </Text>
              </View>
              <Text
                style={[
                  typography.bodyEmphasis,
                  { color: colors.textSecondary },
                ]}
              >
                30m
              </Text>
            </MinimalCard>
          </View>
        </View>

        <TrackMealModal
          visible={trackMealModalVisible}
          onClose={() => setTrackMealModalVisible(false)}
          onSave={handleSaveMeal}
          onResetData={handleResetCalories}
        />

        <AddWaterModal
          visible={addWaterModalVisible}
          onClose={() => setAddWaterModalVisible(false)}
          onAdd={handleAddWater}
          onResetData={handleResetWater}
        />

        <ScanFoodModal
          visible={scanFoodModalVisible}
          onClose={() => setScanFoodModalVisible(false)}
          onAddFood={handleAddScannedFood}
        />

        {/* Bottom Spacer for Tab Bar */}
        <View style={{ height: 100 }} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    paddingTop: 60,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 24,
    marginBottom: 24,
  },
  avatar: {
    width: 56,
    height: 56,
    borderRadius: 28,
  },
  placeholderAvatar: {
    width: 56,
    height: 56,
    borderRadius: 28,
    justifyContent: "center",
    alignItems: "center",
  },
  section: {
    paddingHorizontal: 24,
    marginBottom: 24,
  },
  statsRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  statItem: {
    alignItems: "center",
    flex: 1,
  },
  divider: {
    width: 1,
    height: 60,
  },
  actionGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 12,
  },
  actionCard: {
    width: "48%",
    alignItems: "center",
    paddingVertical: 20,
  },
  progressHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  progressLabelRow: {
    flexDirection: "row",
    alignItems: "center",
  },
  activityList: {
    gap: 12,
  },
  activityItem: {
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
  },
  activityInfo: {
    flex: 1,
  },
});
