import React, { useState, useCallback } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  TouchableOpacity,
  Alert,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useUser } from "@clerk/clerk-expo";
import { useFocusEffect } from "expo-router";
import * as SecureStore from "expo-secure-store";
import { useTheme } from "../../contexts/ThemeContext";
import { MinimalCard } from "../../components/MinimalCard";
import { SectionHeader } from "../../components/SectionHeader";
import { MinimalButton } from "../../components/MinimalButton";
import { Badge } from "../../components/Badge";
import { ProgressBar } from "../../components/ProgressBar";
import { GoalProgressCard } from "../../components/GoalProgressCard";
import { GoalCreationModal } from "../../components/GoalCreationModal";
import { WeeklyProgressChart } from "../../components/WeeklyProgressChart";
import { GoalTypeBreakdownChart } from "../../components/GoalTypeBreakdownChart";
import type { FitnessGoal, CreateGoalData } from "../../services/fitnessGoals";
import { useStatistics } from "../../contexts/StatisticsContext";
import { useFitnessGoals } from "../../contexts/FitnessGoalsContext";
import { useRecommendations } from "../../contexts/RecommendationsContext";
import log from "../../utils/logger";

export default function GoalsScreen() {
  const { user } = useUser();
  const { colors, typography } = useTheme();
  const {
    statistics,
    refetchStatistics,
    clearCache: clearStatsCache,
  } = useStatistics();
  const {
    goals,
    loading,
    refetchGoals,
    createGoal,
    completeGoal,
    deleteGoal,
    clearCache: clearGoalsCache,
  } = useFitnessGoals();
  const { clearCache: clearRecommendationsCache } = useRecommendations();
  const [refreshing, setRefreshing] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [showAnalytics, setShowAnalytics] = useState(false);

  const loadData = useCallback(async () => {
    await refetchGoals();
    await refetchStatistics();
  }, [refetchGoals, refetchStatistics]);

  const clearClerkCache = async () => {
    Alert.alert(
      "Clear Clerk Cache",
      "This will clear all cached Clerk tokens. You will need to sign out and sign back in.",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Clear Cache",
          style: "destructive",
          onPress: async () => {
            try {
              const keysToDelete = [
                "__clerk_client_jwt",
                "__clerk_db_jwt",
                "__clerk_client_uat",
                "__clerk_session_id",
                "__clerk_refresh_token",
                "__clerk_session_jwt",
              ];

              for (const key of keysToDelete) {
                try {
                  await SecureStore.deleteItemAsync(key);
                } catch (e) {
                  // Key might not exist
                }
              }

              clearStatsCache();
              clearGoalsCache();
              clearRecommendationsCache();

              Alert.alert(
                "Success",
                "Cache cleared! Please sign out and sign back in.",
              );
            } catch (error) {
              log.error("Failed to clear cache", error);
              Alert.alert("Error", "Failed to clear cache");
            }
          },
        },
      ],
    );
  };

  useFocusEffect(
    useCallback(() => {
      loadData();
    }, [loadData]),
  );

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

  const handleCreateGoal = async (newGoal: CreateGoalData) => {
    await createGoal(newGoal);
    setIsModalVisible(false);
  };

  const handleCompleteGoal = async (goal: FitnessGoal) => {
    await completeGoal(goal.id);
  };

  const handleDeleteGoal = async (goalId: string) => {
    await deleteGoal(goalId);
  };

  const activeGoals = goals?.filter((g) => g.status === "active") || [];
  const completedGoals = goals?.filter((g) => g.status === "completed") || [];
  const avgProgress =
    activeGoals.length > 0
      ? Math.round(
          activeGoals.reduce((sum, g) => sum + (g.progress || 0), 0) /
            activeGoals.length,
        )
      : 0;

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={colors.primary}
          />
        }
      >
        {/* Header */}
        <View style={styles.header}>
          <View>
            <Text style={[typography.h1, { color: colors.textPrimary }]}>
              Fitness Goals
            </Text>
            <Text
              style={[
                typography.body,
                { color: colors.textSecondary, marginTop: 4 },
              ]}
            >
              Track your fitness journey progress
            </Text>
          </View>
          <TouchableOpacity
            onPress={clearClerkCache}
            style={styles.debugButton}
          >
            <Ionicons
              name="refresh-circle-outline"
              size={24}
              color={colors.textTertiary}
            />
          </TouchableOpacity>
        </View>

        {/* Stats Summary */}
        {goals && goals.length > 0 && (
          <View style={styles.section}>
            <View style={styles.statsRow}>
              <MinimalCard variant="elevated" style={styles.statCard}>
                <Text style={[typography.stat, { color: colors.primary }]}>
                  {activeGoals.length}
                </Text>
                <Text
                  style={[
                    typography.caption,
                    { color: colors.textTertiary, marginTop: 4 },
                  ]}
                >
                  Active
                </Text>
              </MinimalCard>

              <MinimalCard variant="elevated" style={styles.statCard}>
                <Text style={[typography.stat, { color: colors.success }]}>
                  {completedGoals.length}
                </Text>
                <Text
                  style={[
                    typography.caption,
                    { color: colors.textTertiary, marginTop: 4 },
                  ]}
                >
                  Completed
                </Text>
              </MinimalCard>

              <MinimalCard variant="elevated" style={styles.statCard}>
                <Text style={[typography.stat, { color: colors.textPrimary }]}>
                  {avgProgress}%
                </Text>
                <Text
                  style={[
                    typography.caption,
                    { color: colors.textTertiary, marginTop: 4 },
                  ]}
                >
                  Avg Progress
                </Text>
              </MinimalCard>
            </View>
          </View>
        )}

        {/* Analytics Section */}
        {statistics && (
          <View style={styles.section}>
            <MinimalCard variant="default">
              <TouchableOpacity
                style={styles.analyticsHeader}
                onPress={() => setShowAnalytics(!showAnalytics)}
                activeOpacity={0.7}
              >
                <View style={styles.analyticsHeaderLeft}>
                  <Ionicons
                    name="bar-chart-outline"
                    size={20}
                    color={colors.primary}
                  />
                  <Text
                    style={[
                      typography.h3,
                      { color: colors.textPrimary, marginLeft: 8 },
                    ]}
                  >
                    Progress Analytics
                  </Text>
                </View>
                <Ionicons
                  name={showAnalytics ? "chevron-up" : "chevron-down"}
                  size={20}
                  color={colors.textTertiary}
                />
              </TouchableOpacity>

              {showAnalytics && (
                <View style={styles.analyticsContent}>
                  {statistics.weeklyTrend.length > 0 && (
                    <WeeklyProgressChart
                      weeklyData={statistics.weeklyTrend}
                      title="8-Week Trend"
                    />
                  )}
                  {statistics.goals.goalsByType.length > 0 && (
                    <GoalTypeBreakdownChart
                      data={statistics.goals.goalsByType}
                      title="Goals by Type"
                    />
                  )}
                </View>
              )}
            </MinimalCard>
          </View>
        )}

        {/* Active Goals */}
        <View style={styles.section}>
          <SectionHeader
            title={`Active Goals (${activeGoals.length})`}
            actionLabel="Add New"
            onActionPress={() => setIsModalVisible(true)}
          />
          {activeGoals.length === 0 ? (
            <MinimalCard variant="default">
              <View style={styles.emptyState}>
                <Ionicons
                  name="flag-outline"
                  size={48}
                  color={colors.borderLight}
                />
                <Text
                  style={[
                    typography.bodyEmphasis,
                    { color: colors.textSecondary, marginTop: 12 },
                  ]}
                >
                  No active goals yet
                </Text>
                <Text
                  style={[
                    typography.caption,
                    { color: colors.textTertiary, marginTop: 4 },
                  ]}
                >
                  Tap "Add New" to create your first goal
                </Text>
              </View>
            </MinimalCard>
          ) : (
            <View style={styles.goalsList}>
              {activeGoals.map((goal) => (
                <GoalProgressCard
                  key={goal.id}
                  goal={goal}
                  onComplete={() => handleCompleteGoal(goal)}
                  onDelete={() => handleDeleteGoal(goal.id)}
                />
              ))}
            </View>
          )}
        </View>

        {/* Completed Goals */}
        {completedGoals.length > 0 && (
          <View style={styles.section}>
            <SectionHeader
              title={`Completed Goals (${completedGoals.length})`}
            />
            <View style={styles.goalsList}>
              {completedGoals.map((goal) => (
                <GoalProgressCard
                  key={goal.id}
                  goal={goal}
                  onDelete={() => handleDeleteGoal(goal.id)}
                />
              ))}
            </View>
          </View>
        )}

        <View style={styles.footer} />
      </ScrollView>

      {/* Floating Action Button - Minimal Style */}
      <View style={styles.fabContainer}>
        <TouchableOpacity
          onPress={() => setIsModalVisible(true)}
          activeOpacity={0.8}
          style={[
            styles.fab,
            {
              backgroundColor: colors.primary,
              shadowColor: colors.primary,
            },
          ]}
        >
          <Ionicons name="add" size={28} color={colors.white} />
        </TouchableOpacity>
      </View>

      {/* Create Goal Modal */}
      <GoalCreationModal
        visible={isModalVisible}
        onClose={() => setIsModalVisible(false)}
        onSubmit={handleCreateGoal}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    paddingBottom: 20,
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    paddingHorizontal: 24,
    paddingTop: 60,
    paddingBottom: 24,
  },
  debugButton: {
    padding: 8,
  },
  section: {
    paddingHorizontal: 24,
    marginBottom: 24,
  },
  statsRow: {
    flexDirection: "row",
    gap: 12,
  },
  statCard: {
    flex: 1,
    alignItems: "center",
    paddingVertical: 20,
  },
  analyticsHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  analyticsHeaderLeft: {
    flexDirection: "row",
    alignItems: "center",
  },
  analyticsContent: {
    paddingTop: 16,
    marginTop: 16,
    borderTopWidth: 1,
    borderTopColor: "rgba(0, 0, 0, 0.05)",
  },
  goalsList: {
    gap: 12,
  },
  emptyState: {
    alignItems: "center",
    paddingVertical: 40,
  },
  footer: {
    height: 100,
  },
  fabContainer: {
    position: "absolute",
    right: 24,
    bottom: 90,
  },
  fab: {
    width: 56,
    height: 56,
    borderRadius: 28,
    justifyContent: "center",
    alignItems: "center",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 8,
    elevation: 4,
  },
});
