import React, { useContext, useState, useEffect } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Alert,
} from "react-native";
import axios from "axios";
import NetInfo from "@react-native-community/netinfo";
import UserContext from "../../contexts/UserContext";

const AddSong = ({ navigation, route }) => {
  const { user } = useContext(UserContext);
  const [title, setTitle] = useState("");
  const [verses, setVerses] = useState([{ content: "", addChorus: false }]);
  const [chorus, setChorus] = useState("");
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    // Initial check
    checkConnectivity();

    // Subscribe to network state updates
    const unsubscribe = NetInfo.addEventListener((state) => {
      setIsOnline(state.isConnected);
    });

    // Cleanup subscription on unmount
    return () => unsubscribe();
  }, []);

  const checkConnectivity = async () => {
    const state = await NetInfo.fetch();
    setIsOnline(state.isConnected);
  };

  const addVerse = () => {
    setVerses([...verses, { content: "", addChorus: false }]);
  };

  const updateVerse = (index, field, value) => {
    const newVerses = [...verses];
    newVerses[index][field] = value;
    setVerses(newVerses);
  };

  const handleAddSong = async () => {
    if (!isOnline) {
      Alert.alert(
        "Offline Mode",
        "You need an internet connection to add songs. Please try again when you're online."
      );
      return;
    }

    if (title && verses.length > 0) {
      const formattedVerses = verses
        .map((verse, index) => {
          let formattedVerse = `${index + 1}. ${verse.content}`;
          if (verse.addChorus) {
            formattedVerse += `\n\nChorus:\n${chorus}`;
          }
          return formattedVerse;
        })
        .join("\n\n");

      try {
        const songData = {
          title: title,
          content: formattedVerses,
          artist: user,
        };
        const response = await axios.post(
          "https://kiamabackend.mathenoid.com/api/songs",
          songData
        );

        if (response.data.success) {
          Alert.alert("Success", "Song added successfully");
          setTitle("");
          setVerses([{ content: "", addChorus: false }]);
          setChorus("");
        } else {
          Alert.alert("Error", "Failed to add song");
        }
      } catch (error) {
        console.error("Error adding song:", error);
        Alert.alert("Error", "An error occurred while adding the song");
      }
    }
  };

  const OfflineBanner = () => (
    <View style={styles.offlineBanner}>
      <Text style={styles.offlineBannerText}>
        You are offline. Connect to the internet to add songs.
      </Text>
    </View>
  );

  return (
    <ScrollView style={styles.container}>
      {!isOnline && <OfflineBanner />}

      <Text style={styles.header}>Add a New Song</Text>

      <TextInput
        style={[styles.input, !isOnline && styles.disabledInput]}
        placeholder="Song Title"
        value={title}
        onChangeText={setTitle}
        editable={isOnline}
      />

      {verses.map((verse, index) => (
        <View key={index} style={styles.verseContainer}>
          <Text style={styles.verseHeader}>Verse {index + 1}</Text>
          <TextInput
            style={[styles.verseInput, !isOnline && styles.disabledInput]}
            placeholder="Enter verse content"
            value={verse.content}
            onChangeText={(text) => updateVerse(index, "content", text)}
            multiline
            numberOfLines={4}
            editable={isOnline}
          />
          <TouchableOpacity
            style={[styles.repeatButton, !isOnline && styles.disabledButton]}
            onPress={() => updateVerse(index, "addChorus", !verse.addChorus)}
            disabled={!isOnline}
          >
            <Text style={styles.repeatButtonText}>
              {verse.addChorus ? "Remove Chorus" : "Add Chorus"}
            </Text>
          </TouchableOpacity>
          {verse.addChorus && (
            <TextInput
              style={[styles.chorusInput, !isOnline && styles.disabledInput]}
              placeholder="Enter chorus content"
              value={chorus}
              onChangeText={setChorus}
              multiline
              numberOfLines={4}
              editable={isOnline}
            />
          )}
        </View>
      ))}

      <TouchableOpacity
        style={[styles.addButton, !isOnline && styles.disabledButton]}
        onPress={addVerse}
        disabled={!isOnline}
      >
        <Text style={styles.addButtonText}>Add Verse</Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={[
          styles.button,
          (!title || verses.length === 0 || !isOnline) && styles.disabledButton,
        ]}
        onPress={handleAddSong}
        disabled={!title || verses.length === 0 || !isOnline}
      >
        <Text style={styles.buttonText}>Add Song</Text>
      </TouchableOpacity>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    backgroundColor: "#f0f8f0",
  },
  offlineBanner: {
    backgroundColor: "#f57c00",
    padding: 10,
    borderRadius: 5,
    marginBottom: 15,
  },
  offlineBannerText: {
    color: "#fff",
    textAlign: "center",
    fontWeight: "bold",
  },
  header: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 20,
    color: "#2e7d32",
  },
  input: {
    height: 40,
    borderColor: "#a5d6a7",
    borderWidth: 1,
    marginBottom: 15,
    paddingHorizontal: 10,
    borderRadius: 5,
    backgroundColor: "white",
  },
  disabledInput: {
    backgroundColor: "#e0e0e0",
    color: "#757575",
  },
  verseContainer: {
    marginBottom: 20,
    padding: 10,
    backgroundColor: "#e8f5e9",
    borderRadius: 5,
    borderColor: "#a5d6a7",
    borderWidth: 1,
  },
  verseHeader: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 10,
    color: "#2e7d32",
  },
  verseInput: {
    height: 100,
    borderColor: "#a5d6a7",
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    borderRadius: 5,
    textAlignVertical: "top",
    backgroundColor: "white",
  },
  chorusInput: {
    height: 80,
    borderColor: "#81c784",
    borderWidth: 1,
    marginTop: 10,
    marginBottom: 10,
    paddingHorizontal: 10,
    borderRadius: 5,
    textAlignVertical: "top",
    backgroundColor: "#f1f8e9",
  },
  button: {
    backgroundColor: "#4CAF50",
    padding: 10,
    borderRadius: 5,
    alignItems: "center",
    marginBottom: 10,
  },
  disabledButton: {
    backgroundColor: "#a5d6a7",
    opacity: 0.7,
  },
  buttonText: {
    color: "white",
    fontWeight: "bold",
  },
  addButton: {
    backgroundColor: "#66bb6a",
    padding: 10,
    borderRadius: 5,
    alignItems: "center",
    marginBottom: 20,
  },
  addButtonText: {
    color: "white",
    fontWeight: "bold",
  },
  repeatButton: {
    backgroundColor: "#81c784",
    padding: 5,
    borderRadius: 5,
    alignItems: "center",
    marginTop: 5,
  },
  repeatButtonText: {
    color: "white",
  },
});

export default AddSong;
