import { useEffect, useState } from "react";
import {
  View,
  Text,
  FlatList,
  ActivityIndicator,
  StyleSheet,
  RefreshControl,
} from "react-native";
import { useAuth } from "@clerk/clerk-expo";
import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { API_BASE_URL, API_ENDPOINTS } from "../../config/api";
import { theme } from "../../styles/theme";
import log from "../../utils/logger";

interface Recommendation {
  id: string;
  userId: string;
  recommendationText: string;
  activityPlan?: string;
  dietPlan?: string;
  status: string;
  createdAt: string;
}

export default function RecommendationsScreen() {
  const { getToken, userId } = useAuth();
  const [recommendations, setRecommendations] = useState<Recommendation[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const fetchRecommendations = async () => {
    try {
      if (!userId) {
        log.warn("No userId available");
        return;
      }

      const token = await getToken();
      const headers: Record<string, string> = {
        "Content-Type": "application/json",
      };

      if (token) {
        headers["Authorization"] = `Bearer ${token}`;
      }

      const url = `${API_BASE_URL}${API_ENDPOINTS.RECOMMENDATIONS}?userId=${userId}`;
      log.apiRequest("GET", url);

      const res = await fetch(url, { headers });

      if (!res.ok) {
        const errorText = await res.text();
        log.error("API error fetching recommendations", {
          status: res.status,
          errorText,
        });
        throw new Error(`Network response was not ok: ${res.status}`);
      }

      const data = await res.json();
      log.debug("Recommendations fetched", {
        count: data.recommendations?.length || data.length || 0,
      });
      setRecommendations(data.recommendations || data || []);
    } catch (e) {
      log.error("Failed to load recommendations", e);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  const onRefresh = () => {
    setRefreshing(true);
    fetchRecommendations();
  };

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

  return (
    <View style={styles.container}>
      <LinearGradient
        colors={theme.gradients.primary}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.header}
      >
        <Text style={styles.headerTitle}>AI Recommendations</Text>
      </LinearGradient>

      {/* AI Context Info Banner with Glassmorphism */}
      <LinearGradient
        colors={
          ["rgba(59, 130, 246, 0.15)", "rgba(139, 92, 246, 0.1)"] as const
        }
        style={styles.infoBanner}
      >
        <View style={styles.infoBannerIconContainer}>
          <LinearGradient
            colors={theme.gradients.primary}
            style={styles.infoBannerIcon}
          >
            <Ionicons name="sparkles" size={16} color="#fff" />
          </LinearGradient>
        </View>
        <Text style={styles.infoBannerText}>
          Personalized based on your active fitness goals and progress
        </Text>
      </LinearGradient>

      <FlatList
        data={recommendations}
        keyExtractor={(item) => item.id}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <View style={styles.emptyIconContainer}>
              <LinearGradient
                colors={
                  [
                    "rgba(209, 213, 219, 0.3)",
                    "rgba(209, 213, 219, 0.1)",
                  ] as const
                }
                style={styles.emptyIconGradient}
              >
                <Ionicons name="sparkles-outline" size={48} color="#9ca3af" />
              </LinearGradient>
            </View>
            <Text style={styles.empty}>No recommendations available yet.</Text>
            <Text style={styles.emptySub}>Pull down to refresh</Text>
          </View>
        }
        renderItem={({ item }) => (
          <LinearGradient
            colors={
              ["rgba(255, 255, 255, 1)", "rgba(249, 250, 251, 1)"] as const
            }
            style={[styles.card, theme.shadows.medium]}
          >
            <View style={styles.cardHeader}>
              <LinearGradient
                colors={theme.gradients.success}
                style={styles.statusBadge}
              >
                <Text style={styles.statusText}>
                  {item.status.toUpperCase()}
                </Text>
              </LinearGradient>
              <Text style={styles.date}>
                {new Date(item.createdAt).toLocaleDateString()}
              </Text>
            </View>

            <Text style={styles.sectionTitle}>Daily Advice</Text>
            <Text style={styles.content}>{item.recommendationText}</Text>

            {item.activityPlan && (
              <>
                <Text style={styles.sectionTitle}>Activity Plan</Text>
                <Text style={styles.content}>{item.activityPlan}</Text>
              </>
            )}

            {item.dietPlan && (
              <>
                <Text style={styles.sectionTitle}>Diet Plan</Text>
                <Text style={styles.content}>{item.dietPlan}</Text>
              </>
            )}
          </LinearGradient>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
  },
  header: {
    paddingTop: 60,
    paddingBottom: 24,
    paddingHorizontal: 24,
    borderBottomLeftRadius: theme.borderRadius.xl,
    borderBottomRightRadius: theme.borderRadius.xl,
  },
  headerTitle: {
    fontSize: theme.typography.fontSize["3xl"],
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.white,
  },
  infoBanner: {
    flexDirection: "row",
    alignItems: "center",
    marginHorizontal: 16,
    marginTop: 16,
    marginBottom: 12,
    padding: 14,
    borderRadius: theme.borderRadius.lg,
    borderWidth: 1,
    borderColor: "rgba(59, 130, 246, 0.2)",
    gap: 10,
  },
  infoBannerIconContainer: {
    marginRight: 4,
  },
  infoBannerIcon: {
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: "center",
    alignItems: "center",
  },
  infoBannerText: {
    flex: 1,
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.gray700,
    lineHeight: 18,
    fontWeight: theme.typography.fontWeight.medium,
  },
  centered: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: theme.colors.background,
  },
  listContent: {
    padding: 16,
  },
  card: {
    padding: 18,
    marginBottom: 14,
    borderRadius: theme.borderRadius.xl,
    borderWidth: 1,
    borderColor: "rgba(59, 130, 246, 0.1)",
  },
  cardHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 14,
    paddingBottom: 12,
    borderBottomWidth: 1,
    borderBottomColor: theme.colors.gray200,
  },
  statusBadge: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: theme.borderRadius.md,
  },
  statusText: {
    fontSize: theme.typography.fontSize.xs,
    fontWeight: theme.typography.fontWeight.semibold,
    color: theme.colors.white,
  },
  date: {
    fontSize: theme.typography.fontSize.xs,
    color: theme.colors.gray600,
    fontWeight: theme.typography.fontWeight.medium,
  },
  sectionTitle: {
    fontSize: theme.typography.fontSize.base,
    fontWeight: theme.typography.fontWeight.semibold,
    color: theme.colors.gray900,
    marginTop: 12,
    marginBottom: 6,
  },
  content: {
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.gray700,
    lineHeight: 20,
  },
  emptyContainer: {
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 60,
  },
  emptyIconContainer: {
    marginBottom: 16,
  },
  emptyIconGradient: {
    width: 96,
    height: 96,
    borderRadius: 48,
    justifyContent: "center",
    alignItems: "center",
  },
  empty: {
    textAlign: "center",
    fontSize: theme.typography.fontSize.base,
    color: theme.colors.gray700,
    fontWeight: theme.typography.fontWeight.semibold,
    marginBottom: 4,
  },
  emptySub: {
    textAlign: "center",
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.gray500,
  },
});
