import React, { useState, useEffect, useContext, useCallback } from "react";
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  Alert,
  RefreshControl,
  ActivityIndicator,
} from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import { Ionicons } from "@expo/vector-icons";
import axios from "axios";
import UserContext from "../../contexts/UserContext";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import { router } from "expo-router";
import NetInfo from "@react-native-community/netinfo";
import { useSQLiteContext } from "expo-sqlite";

const Tab = createMaterialTopTabNavigator();

const MemberCard = ({
  member,
  onDelete,
  onToggleAdmin,
  currentUser,
  index,
  isOffline,
}) => {
  const isCurrentUser = member.name === currentUser;
  const isAdmin = member.role === "admin";

  return (
    <LinearGradient
      colors={["#ffffff", "#69c37b"]}
      style={styles.card}
      start={{ x: 0, y: 0 }}
      end={{ x: 1, y: 1 }}
    >
      <View style={styles.cardContent}>
        <View style={styles.nameContainer}>
          <Text style={styles.index}>{index}.</Text>
          <Text style={styles.name}>{member.name}</Text>
        </View>
        <View style={styles.infoContainer}>
          <View style={styles.infoItem}>
            <Ionicons name="home-outline" size={18} color="#4CAF50" />
            <Text style={styles.info}>{member.homechurch}</Text>
          </View>
          <View style={styles.infoItem}>
            <Ionicons name="musical-notes-outline" size={18} color="#4CAF50" />
            <Text style={styles.info}>{member.songCount || 0} songs</Text>
          </View>
          <View style={styles.infoItem}>
            <Ionicons name="person-outline" size={18} color="#4CAF50" />
            <Text style={styles.info}>{member.role}</Text>
          </View>
        </View>
      </View>
      {!isCurrentUser && !isOffline && (
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[
              styles.button,
              isAdmin ? styles.removeAdminButton : styles.makeAdminButton,
            ]}
            onPress={() => onToggleAdmin(member.name, isAdmin)}
          >
            <Text style={styles.buttonText}>
              {isAdmin ? "Remove Admin" : "Make Admin"}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.deleteButton}
            onPress={() => onDelete(member.name)}
          >
            <Ionicons name="trash-outline" size={24} color="#ff4d4d" />
          </TouchableOpacity>
        </View>
      )}
    </LinearGradient>
  );
};

const AppliedMemberCard = ({
  member,
  onAccept,
  onDismiss,
  index,
  isOffline,
}) => {
  return (
    <LinearGradient
      colors={["#ffffff", "#69c37b"]}
      style={styles.card}
      start={{ x: 0, y: 0 }}
      end={{ x: 1, y: 1 }}
    >
      <View style={styles.cardContent}>
        <View style={styles.nameContainer}>
          <Text style={styles.index}>{index}.</Text>
          <Text style={styles.name}>{member.name}</Text>
        </View>
        <View style={styles.infoContainer}>
          <View style={styles.infoItem}>
            <Ionicons name="home-outline" size={18} color="#4CAF50" />
            <Text style={styles.info}>{member.homechurch}</Text>
          </View>
          <View style={styles.infoItem}>
            <Ionicons name="call-outline" size={18} color="#4CAF50" />
            <Text style={styles.info}>{member.phone}</Text>
          </View>
          <View style={styles.infoItem}>
            <Ionicons name="mail-outline" size={18} color="#4CAF50" />
            <Text style={styles.info}>{member.email}</Text>
          </View>
        </View>
      </View>
      {!isOffline && (
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[styles.button, styles.acceptButton]}
            onPress={() => onAccept(member.name)}
          >
            <Text style={styles.buttonText}>Accept</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.button, styles.dismissButton]}
            onPress={() => onDismiss(member.name)}
          >
            <Text style={styles.buttonText}>Dismiss</Text>
          </TouchableOpacity>
        </View>
      )}
    </LinearGradient>
  );
};

const OfflineNotice = () => (
  <View style={styles.offlineNoticeContainer}>
    <LinearGradient
      colors={["#ff9800", "#f57c00"]}
      start={{ x: 0, y: 0 }}
      end={{ x: 1, y: 0 }}
      style={styles.offlineNotice}
    >
      <Ionicons name="cloud-offline-outline" size={20} color="#fff" />
      <Text style={styles.offlineText}>
        Offline Mode - Connect to manage members
      </Text>
    </LinearGradient>
  </View>
);

const Members = () => {
  const [members, setMembers] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [isOffline, setIsOffline] = useState(false);
  const { user } = useContext(UserContext);
  const db = useSQLiteContext();

  const fetchMembers = async () => {
    try {
      const netInfo = await NetInfo.fetch();
      if (!netInfo.isConnected) {
        const result = await db.getAllAsync(
          `SELECT * FROM colleagues ORDER BY name`
        );
        setMembers(result);
      } else {
        const response = await axios.get(
          "https://kiamabackend.mathenoid.com/api/members"
        );
        const sortedMembers = response.data.members.sort((a, b) =>
          a.name.localeCompare(b.name)
        );
        setMembers(sortedMembers);
      }
    } catch (error) {
      console.error(
        "Error fetching members:",
        error.response ? error.response.data : error.message
      );
      Alert.alert(
        "Error",
        "Failed to fetch members. Please check your connection and try again."
      );
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsOffline(!state.isConnected);
    });

    fetchMembers();

    return () => {
      unsubscribe();
    };
  }, [isOffline]);

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

  const handleDelete = (memberName) => {
    if (isOffline) return;

    Alert.alert(
      "Confirm Delete",
      `Are you sure you want to delete ${memberName}?`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Delete",
          style: "destructive",
          onPress: async () => {
            try {
              const encodedName = encodeURIComponent(memberName);
              await axios.delete(
                `https://kiamabackend.mathenoid.com/api/members/${encodedName}`,
                {
                  data: { currentUser: user },
                }
              );
              await fetchMembers();
              Alert.alert("Success", "Member deleted successfully");
            } catch (error) {
              console.error(
                "Error deleting member:",
                error.response ? error.response.data : error.message
              );
              Alert.alert(
                "Error",
                "Failed to delete member. Please try again."
              );
            }
          },
        },
      ]
    );
  };

  const handleToggleAdmin = async (memberName, isCurrentlyAdmin) => {
    if (isOffline) return;

    const action = isCurrentlyAdmin ? "remove admin status from" : "make admin";
    Alert.alert(
      "Confirm Action",
      `Are you sure you want to ${action} ${memberName}?`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Confirm",
          onPress: async () => {
            try {
              const response = await axios.put(
                `https://kiamabackend.mathenoid.com/api/members/${memberName}/toggleAdmin`,
                { currentUser: user }
              );
              if (response.data.success) {
                await fetchMembers();
                Alert.alert(
                  "Success",
                  `Admin status updated for ${memberName}`
                );
              } else {
                Alert.alert("Error", response.data.message);
              }
            } catch (error) {
              console.error(
                "Error updating admin status:",
                error.response ? error.response.data : error.message
              );
              Alert.alert(
                "Error",
                "Failed to update admin status. Please try again."
              );
            }
          },
        },
      ]
    );
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4CAF50" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {isOffline && <OfflineNotice />}
      <FlatList
        showsVerticalScrollIndicator={false}
        data={members}
        renderItem={({ item, index }) => (
          <MemberCard
            member={item}
            onDelete={handleDelete}
            onToggleAdmin={handleToggleAdmin}
            currentUser={user}
            index={index + 1}
            isOffline={isOffline}
          />
        )}
        keyExtractor={(item) => item.name}
        contentContainerStyle={styles.listContainer}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={
          <Text style={styles.emptyListText}>No members found</Text>
        }
      />
    </View>
  );
};

const AppliedMembers = () => {
  const [appliedMembers, setAppliedMembers] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [isOffline, setIsOffline] = useState(false);
  const db = useSQLiteContext();

  const fetchAppliedMembers = async () => {
    try {
      const netInfo = await NetInfo.fetch();
      if (!netInfo.isConnected) {
        const result = await db.getAllAsync(
          `SELECT * FROM colleaguesApplied ORDER BY name`
        );
        setAppliedMembers(result);
      } else {
        const response = await axios.get(
          "https://kiamabackend.mathenoid.com/api/applied-members"
        );
        setAppliedMembers(response.data.appliedMembers);
      }
    } catch (error) {
      if (error.response) {
        console.error("Server responded with error:", error.response.data);
        Alert.alert(
          "Server Error",
          "There was a problem with the server. Please try again later."
        );
      } else if (error.request) {
        console.error("No response received:", error.request);
        Alert.alert(
          "Network Error",
          "Unable to connect to the server. Please check your internet connection."
        );
      } else {
        console.error("Error setting up request:", error.message);
        Alert.alert("Error", "An unexpected error occurred. Please try again.");
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsOffline(!state.isConnected);
    });

    fetchAppliedMembers();

    return () => {
      unsubscribe();
    };
  }, [isOffline]);

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

  const handleAccept = async (memberName) => {
    if (isOffline) return;

    Alert.alert(
      "Confirm Accept",
      `Are you sure you want to accept ${memberName}?`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Accept",
          onPress: async () => {
            try {
              await axios.post(
                "https://kiamabackend.mathenoid.com/api/accept-member",
                { name: memberName }
              );
              await fetchAppliedMembers();
              Alert.alert("Success", "Member accepted successfully");
              router.push("/(drawer)");
            } catch (error) {
              console.error(
                "Error accepting member:",
                error.response ? error.response.data : error.message
              );
              Alert.alert(
                "Error",
                "Failed to accept member. Please try again."
              );
            }
          },
        },
      ]
    );
  };

  const handleDismiss = async (memberName) => {
    if (isOffline) return;

    Alert.alert(
      "Confirm Dismiss",
      `Are you sure you want to dismiss ${memberName}?`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Dismiss",
          style: "destructive",
          onPress: async () => {
            try {
              const encodedName = encodeURIComponent(memberName);
              await axios.delete(
                `https://kiamabackend.mathenoid.com/api/dismiss-member/${encodedName}`
              );
              await fetchAppliedMembers();
              Alert.alert("Success", "Member dismissed successfully");
              router.push("/(drawer)");
            } catch (error) {
              console.error(
                "Error dismissing member:",
                error.response ? error.response.data : error.message
              );
              Alert.alert(
                "Error",
                "Failed to dismiss member. Please try again."
              );
            }
          },
        },
      ]
    );
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4CAF50" />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {isOffline && <OfflineNotice />}
      <FlatList
        showsVerticalScrollIndicator={false}
        data={appliedMembers}
        renderItem={({ item, index }) => (
          <AppliedMemberCard
            member={item}
            onAccept={handleAccept}
            onDismiss={handleDismiss}
            index={index + 1}
            isOffline={isOffline}
          />
        )}
        keyExtractor={(item) => item.name}
        contentContainerStyle={styles.listContainer}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={
          <Text style={styles.emptyListText}>No applied members found</Text>
        }
      />
    </View>
  );
};

const ManageMembers = () => {
  return (
    <Tab.Navigator
      screenOptions={{
        tabBarLabelStyle: { fontSize: 14, fontWeight: "bold" },
        tabBarStyle: { backgroundColor: "#f0f0f0" },
        tabBarIndicatorStyle: { backgroundColor: "#4CAF50" },
      }}
    >
      <Tab.Screen name="Members" component={Members} />
      <Tab.Screen name="Applied Members" component={AppliedMembers} />
    </Tab.Navigator>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f5f5f5",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f5f5f5",
  },
  listContainer: {
    padding: 16,
  },
  card: {
    borderRadius: 12,
    marginBottom: 16,
    overflow: "hidden",
    elevation: 4,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  cardContent: {
    padding: 16,
  },
  nameContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 12,
  },
  index: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#333",
    marginRight: 4,
  },
  name: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#333",
  },
  infoContainer: {
    marginTop: 8,
  },
  infoItem: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 6,
  },
  info: {
    fontSize: 15,
    color: "#555",
    marginLeft: 8,
  },
  buttonContainer: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    padding: 16,
    borderTopWidth: 0.6,
    borderTopColor: "#e0e0e0",
  },
  button: {
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 6,
  },
  makeAdminButton: {
    backgroundColor: "#4CAF50",
  },
  removeAdminButton: {
    backgroundColor: "#FFA500",
  },
  acceptButton: {
    backgroundColor: "#4CAF50",
  },
  dismissButton: {
    backgroundColor: "#ff4d4d",
  },
  buttonText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 14,
  },
  deleteButton: {
    padding: 8,
  },
  emptyListText: {
    textAlign: "center",
    fontSize: 16,
    color: "#666",
    marginTop: 24,
  },
  offlineNoticeContainer: {
    width: "100%",
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    zIndex: 1000,
  },
  offlineNotice: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 10,
    paddingHorizontal: 16,
    backgroundColor: "#ff9800",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 5,
  },
  offlineText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 14,
    marginLeft: 8,
  },
});

export default ManageMembers;
