import React, { useState, useEffect, useCallback } from "react";
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  RefreshControl,
  TextInput,
} from "react-native";
import axios from "axios";
import { useRouter } from "expo-router";
import { Card, IconButton } from "react-native-paper";
import { Ionicons } from "@expo/vector-icons";
import NetInfo from "@react-native-community/netinfo";
import { useSQLiteContext } from "expo-sqlite";

const Songs = () => {
  const [songs, setSongs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [isOffline, setIsOffline] = useState(false);
  const router = useRouter();
  const db = useSQLiteContext();

  const fetchOnlineSongs = useCallback(async (query = "") => {
    try {
      setError(null);
      const url = query
        ? `https://kiamabackend.mathenoid.com/api/songs/search?query=${encodeURIComponent(
            query
          )}`
        : "https://kiamabackend.mathenoid.com/api/songs";
      const response = await axios.get(url);
      if (response.data.success) {
        const sortedSongs = response.data.songs.sort((a, b) =>
          a.title.localeCompare(b.title)
        );
        setSongs(sortedSongs);
      } else {
        setError("Failed to fetch songs");
      }
    } catch (error) {
      console.error("Error fetching online songs:", error);
      setError("An error occurred while fetching songs");
    }
  }, []);

  const fetchOfflineSongs = useCallback(
    async (query = "") => {
      try {
        setError(null);
        let sql = "SELECT * FROM songs";
        const params = [];
        if (query) {
          sql += " WHERE title LIKE ? OR artist LIKE ?";
          params.push(`%${query}%`, `%${query}%`);
        }
        sql += " ORDER BY title COLLATE NOCASE ASC";

        const result = await db.getAllAsync(sql, params);
        setSongs(result);
      } catch (error) {
        console.error("Error fetching offline songs:", error);
        setError("An error occurred while fetching songs from local database");
      }
    },
    [db]
  );

  const fetchSongs = useCallback(
    async (query = "") => {
      const netInfo = await NetInfo.fetch();
      setIsOffline(!netInfo.isConnected);
      if (netInfo.isConnected) {
        await fetchOnlineSongs(query);
      } else {
        await fetchOfflineSongs(query);
      }
    },
    [fetchOnlineSongs, fetchOfflineSongs]
  );

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

    fetchSongs().finally(() => setLoading(false));

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

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

  const handleSearch = useCallback(
    (text) => {
      setSearchQuery(text);
      fetchSongs(text);
    },
    [fetchSongs]
  );

  const renderSongCard = ({ item }) => (
    <Card style={styles.card}>
      <Card.Content>
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.artist}>By {item.artist}</Text>
        <Text style={styles.date}>
          Added on {new Date(item.addedOn).toLocaleDateString()}
        </Text>
        {item.editedOn && (
          <Text style={styles.editInfo}>
            Edited by {item.editedBy} on{" "}
            {new Date(item.editedOn).toLocaleDateString()}
          </Text>
        )}
      </Card.Content>
      <Card.Actions>
        <TouchableOpacity
          onPress={() => router.push(`/(songDetails)/${item.id}`)}
        >
          <Text style={styles.viewButton}>View Song</Text>
        </TouchableOpacity>
      </Card.Actions>
    </Card>
  );

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

  return (
    <View style={styles.container}>
      {isOffline && (
        <View style={styles.offlineBar}>
          <Ionicons name="cloud-offline" size={20} color="#fff" />
          <Text style={styles.offlineText}>Offline Mode</Text>
        </View>
      )}
      <View style={styles.searchContainer}>
        <TextInput
          style={styles.searchInput}
          placeholder="Search by title or artist"
          value={searchQuery}
          onChangeText={handleSearch}
        />
        <IconButton
          icon={() => <Ionicons name="search" size={24} color="#4caf50" />}
          onPress={() => fetchSongs(searchQuery)}
        />
      </View>
      <FlatList
        data={songs}
        renderItem={renderSongCard}
        showsVerticalScrollIndicator={false}
        keyExtractor={(item) => item.id.toString()}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        ListEmptyComponent={() => (
          <View style={styles.centerContainer}>
            <Text style={styles.errorText}>
              {error || "No songs available"}
            </Text>
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f0f8f0",
    padding: 10,
  },
  centerContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f0f8f0",
  },
  searchContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#ffffff",
    borderRadius: 25,
    marginBottom: 15,
    paddingHorizontal: 15,
    elevation: 3,
  },
  searchInput: {
    flex: 1,
    height: 50,
    fontSize: 16,
    color: "#333",
  },
  card: {
    marginBottom: 15,
    elevation: 3,
    backgroundColor: "#ffffff",
  },
  title: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#2e7d32",
  },
  artist: {
    fontSize: 14,
    color: "#4caf50",
    marginTop: 5,
  },
  date: {
    fontSize: 12,
    color: "#757575",
    marginTop: 5,
  },
  editInfo: {
    fontSize: 12,
    color: "#4caf50",
    fontStyle: "italic",
    marginTop: 5,
  },
  viewButton: {
    color: "#4caf50",
    fontWeight: "bold",
  },
  errorText: {
    color: "red",
    fontSize: 16,
  },
  offlineBar: {
    backgroundColor: "#f57c00",

    padding: 10,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 10,
    borderRadius: 5,
  },
  offlineText: {
    color: "#fff",
    marginLeft: 10,
    fontWeight: "bold",
  },
});

export default Songs;
