import React, { useState, useEffect, useCallback } from "react";
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  SafeAreaView,
  Dimensions,
  RefreshControl,
} from "react-native";
import { Card, Title, Paragraph, Avatar } from "react-native-paper";
import axios from "axios";
import { LinearGradient } from "expo-linear-gradient";
import { Ionicons } from "@expo/vector-icons";
import NetInfo from "@react-native-community/netinfo";
import { useSQLiteContext } from "expo-sqlite";

const { width } = Dimensions.get("window");

const Dashboard = () => {
  const [members, setMembers] = useState([]);
  const [totalSongs, setTotalSongs] = useState(0);
  const [refreshing, setRefreshing] = useState(false);
  const [isOnline, setIsOnline] = useState(true);
  const db = useSQLiteContext();

  const fetchOnlineData = async () => {
    try {
      const response = await axios.get(
        "https://kiamabackend.mathenoid.com/api/members"
      );
      return response.data.members;
    } catch (error) {
      console.error("Error fetching online data:", error);
      return null;
    }
  };

  const fetchOfflineData = async () => {
    try {
      // Fetch colleagues and their song counts
      const colleagues = await db.getAllAsync(`
        SELECT c.name, c.homechurch , COUNT(s.id) as songCount
        FROM colleagues c
        LEFT JOIN songs s ON s.artist = c.name
        GROUP BY c.name
      `);

      return colleagues.map((colleague) => ({
        name: colleague.name,
        homechurch: colleague.homechurch,
        songCount: colleague.songCount || 0,
      }));
    } catch (error) {
      console.error("Error fetching offline data:", error);
      return [];
    }
  };

  const fetchMembers = async () => {
    const networkState = await NetInfo.fetch();
    setIsOnline(networkState.isConnected);

    let fetchedMembers;
    if (networkState.isConnected) {
      fetchedMembers = await fetchOnlineData();
    }

    if (!networkState.isConnected || !fetchedMembers) {
      fetchedMembers = await fetchOfflineData();
    }

    if (fetchedMembers) {
      setMembers(fetchedMembers);
      setTotalSongs(
        fetchedMembers.reduce((total, member) => total + member.songCount, 0)
      );
    }
  };

  useEffect(() => {
    fetchMembers();

    // Set up network status listener
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsOnline(state.isConnected);
    });

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

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

  const renderMemberCard = ({ item }) => (
    <Card style={styles.memberCard}>
      <LinearGradient
        colors={["#4c669f", "#3b5998", "#192f6a"]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.cardGradient}
      >
        <Card.Content style={styles.cardContent}>
          <Avatar.Text
            size={50}
            label={item.name.charAt(0)}
            style={styles.avatar}
          />
          <View style={styles.memberInfo}>
            <Title style={styles.memberName}>{item.name}</Title>
            <Paragraph style={styles.memberDetails}>
              <Ionicons name="home-outline" size={14} color="#ddd" />{" "}
              {item.homechurch || "Unknown"}
            </Paragraph>
            <View style={styles.songCountContainer}>
              <Ionicons name="musical-notes-outline" size={14} color="#ddd" />
              <Text style={styles.songCount}>{item.songCount} songs</Text>
            </View>
          </View>
        </Card.Content>
      </LinearGradient>
    </Card>
  );

  const SummaryCard = () => (
    <Card style={styles.summaryCard}>
      <LinearGradient
        colors={["#FF512F", "#DD2476"]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={styles.summaryGradient}
      >
        <Card.Content>
          <Title style={styles.summaryTitle}>Summary</Title>
          <View style={styles.summaryDetails}>
            <View style={styles.summaryItem}>
              <Ionicons name="musical-notes" size={24} color="#fff" />
              <Text style={styles.summaryText}>{totalSongs} Songs</Text>
            </View>
            <View style={styles.summaryItem}>
              <Ionicons name="people" size={24} color="#fff" />
              <Text style={styles.summaryText}>{members.length} Members</Text>
            </View>
          </View>
          <View style={styles.connectionStatus}>
            <Ionicons
              name={isOnline ? "cloud-done-outline" : "cloud-offline-outline"}
              size={18}
              color={isOnline ? "#4CAF50" : "#FFA000"}
            />

            <Text style={styles.connectionStatusText}>
              {isOnline ? "Online" : "Offline"}
            </Text>
          </View>
          <Paragraph style={styles.currentDate}>
            {new Date().toLocaleDateString("en-US", {
              weekday: "long",
              year: "numeric",
              month: "long",
              day: "numeric",
            })}
          </Paragraph>
        </Card.Content>
      </LinearGradient>
    </Card>
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        showsVerticalScrollIndicator={false}
        ListHeaderComponent={SummaryCard}
        data={members}
        renderItem={renderMemberCard}
        keyExtractor={(item) => item.name}
        contentContainerStyle={styles.listContainer}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f0f0f0",
  },
  listContainer: {
    padding: 16,
    paddingBottom: 32,
  },
  summaryCard: {
    marginBottom: 16,
    borderRadius: 15,
    overflow: "hidden",
    elevation: 5,
  },
  summaryGradient: {
    borderRadius: 15,
    padding: 16,
  },
  summaryTitle: {
    fontSize: 28,
    fontWeight: "bold",
    color: "#fff",
    textAlign: "center",
    marginBottom: 16,
    marginTop: 16,
    paddingTop: 10,
  },
  summaryDetails: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginBottom: 16,
  },
  summaryItem: {
    alignItems: "center",
  },
  summaryText: {
    color: "#fff",
    fontSize: 18,
    marginTop: 8,
  },
  connectionStatus: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    marginBottom: 8,
  },
  connectionStatusText: {
    color: "#fff",
    marginLeft: 8,
    fontSize: 14,
  },
  currentDate: {
    textAlign: "center",
    color: "#fff",
    fontSize: 16,
    fontStyle: "italic",
  },
  memberCard: {
    marginBottom: 16,
    borderRadius: 15,
    overflow: "hidden",
    elevation: 3,
  },
  cardGradient: {
    borderRadius: 15,
  },
  cardContent: {
    flexDirection: "row",
    alignItems: "center",
    padding: 16,
  },
  avatar: {
    marginRight: 16,
    backgroundColor: "rgba(255,255,255,0.2)",
  },
  memberInfo: {
    flex: 1,
  },
  memberName: {
    color: "#fff",
    fontSize: 20,
    fontWeight: "bold",
  },
  memberDetails: {
    color: "#ddd",
    marginTop: 4,
    fontSize: 14,
  },
  songCountContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginTop: 8,
  },
  songCount: {
    color: "#ddd",
    marginLeft: 4,
    fontSize: 14,
  },
});

export default Dashboard;
