import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
  Alert,
  ScrollView,
  ActivityIndicator,
} from "react-native";
import { useUser, useClerk, useAuth } from "@clerk/clerk-expo";
import { useRouter } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { theme } from "../../styles/theme";
import { AnimatedButton } from "../../components/AnimatedButton";
import { GradientBackground } from "../../components/GradientBackground";
import { useState, useEffect } from "react";
import { API_BASE_URL, API_ENDPOINTS } from "../../config/api";
import log from "../../utils/logger";

export default function ProfileScreen() {
  const { user } = useUser();
  const { signOut } = useClerk();
  const router = useRouter();

  const handleSignOut = async () => {
    try {
      await signOut();
    } catch (err) {
      log.error("Failed to sign out", err);
    }
  };

  const confirmSignOut = () => {
    Alert.alert("Sign Out", "Are you sure you want to sign out?", [
      { text: "Cancel", style: "cancel" },
      { text: "Sign Out", style: "destructive", onPress: handleSignOut },
    ]);
  };

  // Gym selection state and handlers
  const { getToken } = useAuth();
  const [gyms, setGyms] = useState<
    Array<{ id: string; name: string; location?: string }>
  >([]);
  const [gymsLoading, setGymsLoading] = useState(false);
  const [selectedGymId, setSelectedGymId] = useState<string | null>(null);
  const [currentGymId, setCurrentGymId] = useState<string | null>(null);
  const [currentGymName, setCurrentGymName] = useState<string | null>(null);

  useEffect(() => {
    const gid =
      ((user?.publicMetadata as any)?.gymId as string | undefined) ?? null;
    setCurrentGymId(gid ?? null);
    if (gid && gyms.length > 0) {
      const g = gyms.find((x) => x.id === gid);
      setCurrentGymName(g?.name ?? null);
      if (selectedGymId === null) setSelectedGymId(gid);
    }
  }, [user?.publicMetadata, gyms]);

  // Auto-load gyms on mount
  useEffect(() => {
    loadGyms();
  }, []);

  const loadGyms = async () => {
    try {
      setGymsLoading(true);
      const token = await getToken();
      const url = `${API_BASE_URL}${API_ENDPOINTS.GYMS}`;
      log.debug("Loading gyms", { url });
      const res = await fetch(url, {
        headers: token ? { Authorization: `Bearer ${token}` } : undefined,
      });
      const contentType = res.headers.get("content-type") || "";
      if (!res.ok) {
        const text = await res.text().catch(() => "");
        log.error(
          "Failed to fetch gyms - non-OK response",
          new Error(text.slice(0, 200)),
          {
            status: res.status,
          },
        );
        setGyms([]);
        return;
      }
      if (!contentType.includes("application/json")) {
        const text = await res.text().catch(() => "");
        log.error(
          "Failed to fetch gyms - expected JSON",
          new Error(text.slice(0, 200)),
          {
            contentType,
          },
        );
        setGyms([]);
        return;
      }
      let data: any = null;
      try {
        data = await res.json();
      } catch (e) {
        const text = await res.text().catch(() => "");
        log.error("Failed to parse gyms JSON", e, {
          bodyPreview: text?.slice(0, 200),
        });
        setGyms([]);
        return;
      }
      const list = Array.isArray(data) ? data : [];
      setGyms(list);
      const gid =
        currentGymId ??
        ((user?.publicMetadata as any)?.gymId as string | undefined) ??
        null;
      if (gid) {
        const g = list.find((x: any) => x.id === gid);
        setCurrentGymId(gid);
        setCurrentGymName(g?.name ?? null);
        if (selectedGymId === null) setSelectedGymId(gid);
      }
    } catch (err) {
      log.error("Failed to fetch gyms", err);
      setGyms([]);
    } finally {
      setGymsLoading(false);
    }
  };

  const handleApplyGym = async () => {
    try {
      const token = await getToken();
      const url = `${API_BASE_URL}${API_ENDPOINTS.USERS}/gym`;
      log.debug("Updating gym selection", { url, gymId: selectedGymId });
      const res = await fetch(url, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({ gymId: selectedGymId }),
      });
      const contentType = res.headers.get("content-type") || "";
      if (!res.ok) {
        const text = await res.text().catch(() => "");
        log.error(
          "Failed to update gym selection - non-OK response",
          new Error(text.slice(0, 200)),
          {
            status: res.status,
          },
        );
        Alert.alert("Error", "Failed to update gym selection");
        return;
      }
      if (contentType.includes("application/json")) {
        try {
          const data = await res.json();
          log.debug("Gym selection updated", { data });
        } catch (e) {
          const text = await res.text().catch(() => "");
          log.error("Failed to parse update response JSON", e, {
            bodyPreview: text?.slice(0, 200),
          });
        }
      }
      // Update current gym state for immediate UI reflection
      setCurrentGymId(selectedGymId);
      setCurrentGymName(
        selectedGymId
          ? (gyms.find((g) => g.id === selectedGymId)?.name ?? null)
          : null,
      );
      // Attempt to reload Clerk user metadata so current gym reflects server state
      try {
        await (user as any)?.reload?.();
      } catch (e) {
        log.debug("Failed to reload user after gym update", { error: e });
      }
      Alert.alert(
        "Success",
        selectedGymId ? "Gym selected successfully" : "Proceeding without gym",
      );
    } catch (err) {
      log.error("Failed to update gym selection", err);
      Alert.alert("Error", "Failed to update gym selection");
    }
  };

  return (
    <View style={styles.container}>
      <GradientBackground variant="primary" style={styles.header}>
        <View style={styles.profileCard}>
          <View style={styles.avatarContainer}>
            {user?.imageUrl ? (
              <Image source={{ uri: user.imageUrl }} style={styles.avatar} />
            ) : (
              <View style={styles.placeholderAvatar}>
                <Ionicons name="person" size={40} color="#fff" />
              </View>
            )}
            <View style={styles.editBadge}>
              <Ionicons name="pencil" size={12} color={theme.colors.primary} />
            </View>
          </View>
          <Text style={styles.name}>{user?.fullName || "User"}</Text>
          <Text style={styles.email}>
            {user?.primaryEmailAddress?.emailAddress}
          </Text>
          <View style={styles.memberBadge}>
            <Text style={styles.memberText}>Premium Member</Text>
          </View>
        </View>
      </GradientBackground>

      <View style={styles.content}>
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Account</Text>
          <View style={[styles.infoCard, theme.shadows.subtle]}>
            <TouchableOpacity
              style={styles.infoRow}
              onPress={() => router.push("/personal-details")}
            >
              <LinearGradient
                colors={["rgba(59, 130, 246, 0.1)", "rgba(59, 130, 246, 0.05)"]}
                style={styles.iconContainer}
              >
                <Ionicons
                  name="person-outline"
                  size={20}
                  color={theme.colors.primary}
                />
              </LinearGradient>
              <Text style={styles.infoLabel}>Personal Details</Text>
              <Ionicons
                name="chevron-forward"
                size={20}
                color={theme.colors.gray400}
              />
            </TouchableOpacity>
            <View style={styles.divider} />
            <TouchableOpacity
              style={styles.infoRow}
              onPress={() => router.push("/fitness-profile")}
            >
              <LinearGradient
                colors={["rgba(16, 185, 129, 0.1)", "rgba(16, 185, 129, 0.05)"]}
                style={styles.iconContainer}
              >
                <Ionicons
                  name="fitness-outline"
                  size={20}
                  color={theme.colors.success}
                />
              </LinearGradient>
              <Text style={styles.infoLabel}>Fitness Profile</Text>
              <Ionicons
                name="chevron-forward"
                size={20}
                color={theme.colors.gray400}
              />
            </TouchableOpacity>
            <View style={styles.divider} />
            <TouchableOpacity style={styles.infoRow}>
              <LinearGradient
                colors={["rgba(245, 158, 11, 0.1)", "rgba(245, 158, 11, 0.05)"]}
                style={styles.iconContainer}
              >
                <Ionicons
                  name="notifications-outline"
                  size={20}
                  color={theme.colors.warning}
                />
              </LinearGradient>
              <Text style={styles.infoLabel}>Notifications</Text>
              <Ionicons
                name="chevron-forward"
                size={20}
                color={theme.colors.gray400}
              />
            </TouchableOpacity>
          </View>

          {/* Gym Selection */}
          <View
            style={[styles.infoCard, theme.shadows.subtle, { marginTop: 12 }]}
          >
            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
                justifyContent: "space-between",
                padding: 12,
              }}
            >
              <Text style={styles.infoLabel}>
                Gym{" "}
                {currentGymName
                  ? `(Current: ${currentGymName})`
                  : currentGymId
                    ? `(Current: ${currentGymId})`
                    : "(Current: None)"}
              </Text>
              <TouchableOpacity onPress={loadGyms}>
                <Text style={{ color: theme.colors.primary }}>
                  Refresh Gyms
                </Text>
              </TouchableOpacity>
            </View>

            {gymsLoading ? (
              <ActivityIndicator style={{ padding: 12 }} />
            ) : (
              <ScrollView
                horizontal
                showsHorizontalScrollIndicator={false}
                style={{ paddingHorizontal: 12, paddingBottom: 12 }}
              >
                <View style={{ flexDirection: "row" }}>
                  <TouchableOpacity
                    style={[
                      styles.infoRow,
                      selectedGymId === null && {
                        backgroundColor: "rgba(59, 130, 246, 0.1)",
                      },
                    ]}
                    onPress={() => setSelectedGymId(null)}
                  >
                    <Text style={styles.infoLabel}>Proceed without gym</Text>
                  </TouchableOpacity>
                  {gyms.map((gym) => (
                    <TouchableOpacity
                      key={gym.id}
                      style={[
                        styles.infoRow,
                        selectedGymId === gym.id && {
                          backgroundColor: "rgba(59, 130, 246, 0.1)",
                        },
                      ]}
                      onPress={() => setSelectedGymId(gym.id)}
                    >
                      <Text style={styles.infoLabel}>{gym.name}</Text>
                    </TouchableOpacity>
                  ))}
                </View>
              </ScrollView>
            )}

            <View style={{ padding: 12 }}>
              <AnimatedButton
                title="Apply Gym Selection"
                onPress={handleApplyGym}
                variant="primary"
                style={{ marginTop: 4 }}
                icon={
                  <Ionicons
                    name="checkmark-outline"
                    size={20}
                    color={theme.colors.white}
                  />
                }
              />
            </View>
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Support</Text>
          <View style={[styles.infoCard, theme.shadows.subtle]}>
            <TouchableOpacity style={styles.infoRow}>
              <LinearGradient
                colors={["rgba(139, 92, 246, 0.1)", "rgba(139, 92, 246, 0.05)"]}
                style={styles.iconContainer}
              >
                <Ionicons
                  name="help-circle-outline"
                  size={20}
                  color={theme.colors.secondary}
                />
              </LinearGradient>
              <Text style={styles.infoLabel}>Help Center</Text>
              <Ionicons
                name="chevron-forward"
                size={20}
                color={theme.colors.gray400}
              />
            </TouchableOpacity>
            <View style={styles.divider} />
            <TouchableOpacity style={styles.infoRow}>
              <LinearGradient
                colors={[
                  "rgba(107, 114, 128, 0.1)",
                  "rgba(107, 114, 128, 0.05)",
                ]}
                style={styles.iconContainer}
              >
                <Ionicons
                  name="shield-checkmark-outline"
                  size={20}
                  color={theme.colors.gray600}
                />
              </LinearGradient>
              <Text style={styles.infoLabel}>Privacy & Security</Text>
              <Ionicons
                name="chevron-forward"
                size={20}
                color={theme.colors.gray400}
              />
            </TouchableOpacity>
          </View>
        </View>

        <AnimatedButton
          title="Sign Out"
          onPress={confirmSignOut}
          variant="danger"
          style={styles.signOutButton}
          icon={<Ionicons name="log-out-outline" size={20} color="#fff" />}
        />

        <Text style={styles.version}>Version 1.0.0</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
  },
  header: {
    paddingTop: 60,
    paddingBottom: 30,
    borderBottomLeftRadius: theme.borderRadius.xl,
    borderBottomRightRadius: theme.borderRadius.xl,
    alignItems: "center",
  },
  profileCard: {
    alignItems: "center",
  },
  avatarContainer: {
    position: "relative",
    marginBottom: 16,
  },
  avatar: {
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: "rgba(255, 255, 255, 0.3)",
  },
  placeholderAvatar: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 4,
    borderColor: "rgba(255, 255, 255, 0.3)",
  },
  editBadge: {
    position: "absolute",
    bottom: 0,
    right: 0,
    backgroundColor: theme.colors.white,
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: "center",
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  name: {
    fontSize: theme.typography.fontSize["2xl"],
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.white,
    marginBottom: 4,
  },
  email: {
    fontSize: theme.typography.fontSize.sm,
    color: "rgba(255, 255, 255, 0.8)",
    marginBottom: 12,
  },
  memberBadge: {
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: theme.borderRadius.full,
    borderWidth: 1,
    borderColor: "rgba(255, 255, 255, 0.3)",
  },
  memberText: {
    color: theme.colors.white,
    fontSize: theme.typography.fontSize.xs,
    fontWeight: theme.typography.fontWeight.bold,
    letterSpacing: 0.5,
  },
  content: {
    padding: 20,
    marginTop: -20,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: theme.typography.fontSize.lg,
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.gray900,
    marginBottom: 12,
    marginLeft: 4,
  },
  infoCard: {
    backgroundColor: theme.colors.white,
    borderRadius: theme.borderRadius.xl,
    padding: 8,
    borderWidth: 1,
    borderColor: theme.colors.gray100,
  },
  infoRow: {
    flexDirection: "row",
    alignItems: "center",
    padding: 12,
  },
  iconContainer: {
    width: 36,
    height: 36,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 12,
  },
  infoLabel: {
    flex: 1,
    fontSize: theme.typography.fontSize.base,
    color: theme.colors.gray900,
    fontWeight: theme.typography.fontWeight.medium,
  },
  divider: {
    height: 1,
    backgroundColor: theme.colors.gray100,
    marginLeft: 60,
  },
  signOutButton: {
    marginTop: 8,
  },
  version: {
    textAlign: "center",
    marginTop: 24,
    color: theme.colors.gray400,
    fontSize: theme.typography.fontSize.xs,
  },
});
