import React, { useState, useEffect } from "react";
import { Text, View, FlatList, TouchableOpacity, Image, Alert, useWindowDimensions } from "react-native";
import { collection, deleteDoc, doc, onSnapshot  } from "firebase/firestore";
import { firebaseDb } from "../../firebaseConfig";
import { AntDesign, Feather } from "@expo/vector-icons";
import { Audio } from "expo-av";
import HTML from 'react-native-render-html';
import { colors } from "../util/color";

const NoteList = ({ navigation }) => {
  const [noteList, setNoteList] = useState([]);
  const [expandedNoteId, setExpandedNoteId] = useState(null);

  useEffect(() => {
    const getNoteList = onSnapshot(collection(firebaseDb, "notes"), (snapshot) => {
      setNoteList(
        snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data(), isPlaying: false }))
      );
    });
    return () => getNoteList();
  }, []);
  
  const truncateText = (text, length) => {
    return text.length > length ? text.substring(0, length) + "..." : text;
  };

  const deleteNote = async (id) => {
    try {
      await deleteDoc(doc(firebaseDb, "notes", id));
      setNoteList((prevNotes) => prevNotes.filter((note) => note.id !== id));
    } catch (error) {
      console.error("Error deleting note:", error);
    }
  };

  const handleDeletePress = (id) => {
    Alert.alert(
      "Delete Note",
      "Are you sure you want to delete this note?",
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Delete",
          style: "destructive",
          onPress: () => deleteNote(id),
        },
      ],
      { cancelable: false }
    );
  };

  const handleNoteItemPress = (id) => {
    if (expandedNoteId === id) {
      navigation.navigate('AddNote', { noteData: noteList.find(note => note.id === id) });
    } else {
      setExpandedNoteId(id);
    }
  };

  const handlePlayAudio = async (audioUrl, index) => { 
    try {
      const soundObject = new Audio.Sound();
      await soundObject.loadAsync({ uri: audioUrl });
      await soundObject.playAsync();
      setNoteList((prevNotes) =>
        prevNotes.map((note, i) =>
          i === index ? { ...note, isPlaying: true } : note
        )
      );
      soundObject.setOnPlaybackStatusUpdate((status) => {
        if (status.didJustFinish) {
          setNoteList((prevNotes) =>
            prevNotes.map((note, i) =>
              i === index ? { ...note, isPlaying: false } : note
            )
          );
        }
      });
    } catch (error) {
      console.error("Error playing audio:", error);
      Alert.alert("Error", "Could not play audio.");
    }
  };

  const windowWidth = useWindowDimensions().width;

  return (
    <View style={styles.container}>
      <FlatList
        data={noteList}
        renderItem={({ item, index }) => (
          <TouchableOpacity  onPress={() => handleNoteItemPress(item.id)}>
            <View style={[styles.noteItem, {height: expandedNoteId === item.id ? null : 110}]}>
              <View style={styles.noteInfo}>
                <HTML
                  source={{
                    html: `<h3 style="font-weight: bold;">${item.title}</h3>`,
                  }}
                  contentWidth={windowWidth}
                  ignoredDomTags={['input']}
                />
                {expandedNoteId === item.id ? (
                  <HTML
                    source={{ html: item.note }}
                    contentWidth={windowWidth}
                    ignoredDomTags={['input']}
                  />
                ) : (
                  <HTML
                    source={{ html: truncateText(item.note, 25) }}
                    contentWidth={windowWidth}
                    ignoredDomTags={['input']}
                  />
                )}
                {expandedNoteId === item.id && item.image && (
                  <Image
                    source={{ uri: item.image }}
                    style={{ width: "80%", height: 150, borderRadius: 10, marginVertical: 10 }}
                  />
                )}
                {expandedNoteId === item.id && item.audios && (
                  <TouchableOpacity onPress={() => handlePlayAudio(item.audios, index)} style={styles.playAudioButton}>
                    <AntDesign name={item.isPlaying ? "pausecircle" : "play"} size={20} color="black" />
                  </TouchableOpacity>

                  {recordedAudios.map((audioUrl, index) => (
                    <View key={index} style={styles.audioPlay}>

                      <TouchableOpacity onPress={() => handleAudioPlay(index)}>
                        <AntDesign name={(isPlaying && currentlyPlayingIndex === index) ? "pausecircle" : "play"} size={20} color="black" />
                      </TouchableOpacity>
                    </View>
                  ))}
                )}

                <Text style={styles.createdAt}>
                  {item.created_at && new Date(item.created_at?.toDate()).toLocaleString([], { hour: 'numeric', minute: 'numeric', hour12: true })}
                </Text>
          
              </View>

              {expandedNoteId === item.id && (
                <TouchableOpacity onPress={() => setExpandedNoteId(null)} style={styles.minimizeButton}>
                  <Feather name="minimize-2" size={20} color="black" />
                </TouchableOpacity>
              )}
        
              <TouchableOpacity
                onPress={() => handleDeletePress(item.id)}
                style={styles.deleteButton}
              >
                <AntDesign name="delete" size={20} color="black" />
              </TouchableOpacity>

            </View>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
      />
    </View>
  );
};

const styles = {
  container: {
    flex: 1,
    backgroundColor: colors.primary,
  },
  listContainer: {
    paddingHorizontal: 10,
  },
  noteItem: {
    marginBottom: 10,
    paddingHorizontal: 20,
    borderRadius: 20,
    backgroundColor: "#FEFEFA",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 10,
  },
  noteInfo: {
    flex: 1,
  },
  title: {
    fontWeight: 'bold',
    marginBottom: 8,
  },
  noteContent: {
    marginBottom: 8,
  },
  image: {
    width: 100,
    height: 100,
    marginVertical: 10,
  },
  createdAt: {
    fontSize: 12, 
    color: 'gray', 
    marginTop: 4,
  },
  minimizeButton: {
    position: 'absolute',
    top: 10,
    right: 10,
  },
  deleteButton: {
    padding: 10,
  },
  playAudioButton: {
    padding: 10,
  },
};

export default NoteList;