import React, { useEffect, useState, useContext } from "react";
import {
  View,
  Text,
  ScrollView,
  StyleSheet,
  TextInput,
  Alert,
  Animated,
} from "react-native";
import { Card, Button } from "react-native-paper";
import { useLocalSearchParams, useRouter } from "expo-router";
import axios from "axios";
import UserContext from "../../contexts/UserContext";
import { useSQLiteContext } from "expo-sqlite";
import NetInfo from "@react-native-community/netinfo";
import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";

const SongDetails = () => {
  const { id } = useLocalSearchParams();
  const [song, setSong] = useState(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editedTitle, setEditedTitle] = useState("");
  const [editedContent, setEditedContent] = useState("");
  const { userRole, user } = useContext(UserContext);
  const router = useRouter();
  const db = useSQLiteContext();
  const [isOnline, setIsOnline] = useState(true);
  const [offlineAnimation] = useState(new Animated.Value(0));

  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsOnline(state.isConnected);
      if (!state.isConnected) {
        Animated.loop(
          Animated.sequence([
            Animated.timing(offlineAnimation, {
              toValue: 1,
              duration: 1000,
              useNativeDriver: true,
            }),
            Animated.timing(offlineAnimation, {
              toValue: 0,
              duration: 1000,
              useNativeDriver: true,
            }),
          ])
        ).start();
      } else {
        offlineAnimation.setValue(0);
      }
    });

    fetchSongDetails();

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

  const fetchSongDetails = async () => {
    try {
      const networkState = await NetInfo.fetch();
      if (networkState.isConnected) {
        // Online: Fetch from API
        const response = await axios.get(
          `https://kiamabackend.mathenoid.com/api/songs/${id}`
        );
        setSong(response.data.song);
        setEditedTitle(response.data.song.title);
        setEditedContent(response.data.song.content);
      } else {
        // Offline: Fetch from local database
        const result = await db.getFirstAsync(
          "SELECT * FROM songs WHERE id = ?",
          [id]
        );
        if (result) {
          setSong(result);
          setEditedTitle(result.title);
          setEditedContent(result.content);
        } else {
          Alert.alert("Error", "Song not found in local database");
        }
      }
    } catch (error) {
      console.error("Error fetching song details:", error);
      Alert.alert("Error", "Failed to fetch song details");
    }
  };

  const handleEdit = () => {
    if (!isOnline) {
      Alert.alert("Offline", "Editing is not available while offline");
      return;
    }
    setIsEditing(true);
  };

  const handleSave = async () => {
    if (!isOnline) {
      Alert.alert("Offline", "Saving changes is not available while offline");
      return;
    }

    if (editedTitle === song.title && editedContent === song.content) {
      Alert.alert("No Changes", "No changes were made to the song.");
      setIsEditing(false);
      return;
    }

    try {
      const editedSongData = {
        title: editedTitle,
        content: editedContent,
        editedBy: user,
      };
      const response = await axios.put(
        `https://kiamabackend.mathenoid.com/api/songs/${id}`,
        editedSongData
      );
      if (response.data.success) {
        Alert.alert("Success", "Changes made successfully");
        setIsEditing(false);
        fetchSongDetails();
      } else {
        Alert.alert("Error", "Failed to save changes");
      }
    } catch (error) {
      console.error("Error saving changes:", error);
      Alert.alert("Error", "An error occurred while saving changes");
    }
  };

  const handleDelete = async () => {
    if (!isOnline) {
      Alert.alert("Offline", "Deleting is not available while offline");
      return;
    }

    Alert.alert(
      "Confirm Delete",
      "Are you sure you want to delete this song?",
      [
        {
          text: "Cancel",
          style: "cancel",
        },
        {
          text: "Delete",
          onPress: async () => {
            try {
              const response = await axios.delete(
                `https://kiamabackend.mathenoid.com/api/songs/${id}`
              );
              if (response.data.success) {
                Alert.alert("Success", "Song deleted successfully");
                router.replace("/(drawer)/Songs");
              } else {
                Alert.alert("Error", "Failed to delete song");
              }
            } catch (error) {
              console.error("Error deleting song:", error);
              Alert.alert("Error", "An error occurred while deleting the song");
            }
          },
          style: "destructive",
        },
      ]
    );
  };

  const renderSongContent = () => {
    if (!song) return null;
    const content = isEditing ? editedContent : song.content;
    return content.split("\n\n").map((verse, index) => (
      <View key={index}>
        {verse.toLowerCase().includes("chorus") ? (
          isEditing ? (
            <TextInput
              style={[styles.chorus, styles.editInput]}
              value={verse}
              onChangeText={(text) => {
                const newContent = editedContent.split("\n\n");
                newContent[index] = text;
                setEditedContent(newContent.join("\n\n"));
              }}
              multiline
            />
          ) : (
            <Text style={styles.chorus}>{verse}</Text>
          )
        ) : isEditing ? (
          <TextInput
            style={[styles.verse, styles.editInput]}
            value={verse}
            onChangeText={(text) => {
              const newContent = editedContent.split("\n\n");
              newContent[index] = text;
              setEditedContent(newContent.join("\n\n"));
            }}
            multiline
          />
        ) : (
          <Text style={styles.verse}>{verse}</Text>
        )}
        {index < content.split("\n\n").length - 1 && (
          <View style={styles.verseSeparator} />
        )}
      </View>
    ));
  };

  if (!song) {
    return (
      <View style={styles.container}>
        <Text>Loading...</Text>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
      {!isOnline && (
        <View style={[styles.offlineBanner]}>
          <Ionicons name="cloud-offline" size={24} color="#fff" />
          <Text style={styles.offlineText}>
            Offline Mode - Connect internet to edit or delete
          </Text>
        </View>
      )}

      <Card style={styles.songCard}>
        <Card.Content>
          {isEditing ? (
            <TextInput
              style={[styles.title, styles.editInput]}
              value={editedTitle}
              onChangeText={setEditedTitle}
            />
          ) : (
            <Text style={styles.title}>{song.title}</Text>
          )}
          <Text style={styles.artist}>By {song.artist}</Text>
          <Text style={styles.date}>
            Added on {new Date(song.addedOn).toLocaleDateString()}
          </Text>
          {song.editedOn && (
            <Text style={styles.editInfo}>
              Edited by {song.editedBy} on{" "}
              {new Date(song.editedOn).toLocaleDateString()}
            </Text>
          )}
          <View style={styles.contentSeparator} />
          <View style={styles.songContent}>{renderSongContent()}</View>
        </Card.Content>
        <Card.Actions>
          {isOnline && (
            <>
              {isEditing ? (
                <Button
                  mode="contained"
                  onPress={handleSave}
                  style={styles.editButton}
                >
                  Save Changes
                </Button>
              ) : (
                <Button
                  mode="contained"
                  onPress={handleEdit}
                  style={styles.editButton}
                >
                  Edit Song
                </Button>
              )}
              {userRole === "admin" && (
                <Button
                  mode="contained"
                  onPress={handleDelete}
                  style={styles.deleteButton}
                >
                  Delete Song
                </Button>
              )}
            </>
          )}
        </Card.Actions>
      </Card>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f0f8f0",
    paddingTop: 50,
    padding: 20,
    paddingBottom: 50,
  },
  songCard: {
    backgroundColor: "#dede",
    borderRadius: 2,
    paddingBottom: 50,
  },
  title: {
    fontSize: 24,
    fontFamily: "outfit-bold",
    color: "#2e7d32",
  },
  artist: {
    fontSize: 18,
    color: "#4caf50",
    fontFamily: "outfit-bold",
    marginBottom: 5,
  },
  date: {
    fontSize: 14,
    color: "#757575",
    fontFamily: "outfit",
    marginBottom: 5,
  },
  editInfo: {
    fontSize: 14,
    color: "#4caf50",
    fontFamily: "outfit",
    marginBottom: 5,
  },
  contentSeparator: {
    height: 1,
    backgroundColor: "#e0e0e0",
    marginVertical: 10,
  },
  songContent: {
    marginTop: 10,
  },
  verse: {
    fontSize: 20,
    color: "#333333",
    fontFamily: "outfit",
    lineHeight: 24,
    marginBottom: 10,
  },
  chorus: {
    fontSize: 16,
    color: "#1b5e20",
    fontStyle: "italic",
    lineHeight: 24,
    backgroundColor: "#c8e6c9",
    padding: 10,
    borderRadius: 5,
    marginBottom: 10,
  },
  verseSeparator: {
    backgroundColor: "#e0e0e0",
    marginVertical: 10,
  },
  editButton: {
    marginTop: 10,
    backgroundColor: "#4caf50",
  },
  deleteButton: {
    marginTop: 10,
    backgroundColor: "#FF0000",
    marginLeft: 10,
  },
  editInput: {
    borderWidth: 1,
    borderColor: "#4caf50",
    borderRadius: 5,
    padding: 5,
    marginBottom: 5,
  },
  offlineBanner: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: "#f57c00",
    padding: 10,
    borderRadius: 5,
    marginBottom: 10,
  },
  offlineText: {
    color: "#fff",
    marginLeft: 10,
    fontFamily: "outfit",
    fontSize: 14,
  },
});

export default SongDetails;
