import { useMemo, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Pressable,
  TextInput,
} from "react-native";
import TrackRow from "../components/TrackRow";
import { useLibrary } from "../contexts/LibraryContext";
import { SafeAreaView } from "react-native-safe-area-context";
import Header from "../components/Header";

export default function LikedTracksScreen({ navigation }) {
  const [query, setQuery] = useState("");
  const [sortDir, setSortDir] = useState("desc");
  const { albums, likedTracks, toggleLike } = useLibrary();

  const [sortBy, setSortBy] = useState("dateAdded");
  const [showSortMenu, setShowSortMenu] = useState(false);

  const filteredAndSortedTracks = useMemo(() => {
    const q = query.trim().toLowerCase();

    let result = !q
      ? [...likedTracks]
      : likedTracks.filter(
        (item) =>
          item.title.toLowerCase().includes(q) ||
          item.artist.toLowerCase().includes(q)
      );

    if (sortBy === "name") {
      result.sort((a, b) => a.title.localeCompare(b.title));
    } else if (sortBy === "length") {
      result.sort((a, b) => a.duration - b.duration);
    } else {
      result.sort((a, b) => {
        if (a.dateAdded && b.dateAdded) {
          return new Date(b.dateAdded) - new Date(a.dateAdded);
        }
        return 0;
      });
    }

    if (sortDir === "desc") result.reverse();

    return result;
  }, [likedTracks, query, sortBy, sortDir]);

  return (
    <SafeAreaView style={styles.container}>
      <Pressable onPress={() => navigation.goBack()} style={styles.backBtn}>
        <Text style={styles.backText}>← Back</Text>
      </Pressable>

      <Header title="Your liked tracks" showIcons={true}/>

      <TextInput
        value={query}
        onChangeText={setQuery}
        placeholder="Search liked tracks"
        placeholderTextColor="#9ca3af"
        style={styles.searchInput}
        autoCapitalize="none"
        autoCorrect={false}
      />

      <View style={styles.sortRow}>
        <Text style={styles.sortByText}>Sort by:</Text>
        <Pressable
          style={styles.sortButton}
          onPress={() => setShowSortMenu((v) => !v)}
        >
          <Text style={styles.sortButtonText}>
            {sortBy === "dateAdded" ? "Date added" : sortBy === "name" ? "Name" : "Length"} ▾
          </Text>
        </Pressable>
        <Pressable
          style={styles.sortDirButton}
          onPress={() => setSortDir((d) => (d === "asc" ? "desc" : "asc"))}
        >
          <Text style={styles.sortDirButtonText}>
            {sortDir === "asc" ? "ASC ↑" : "DESC ↓"}
          </Text>
        </Pressable>
      </View>

      {showSortMenu && (
        <View style={styles.sortMenu}>
          <Pressable style={styles.sortOption} onPress={() => { setSortBy("dateAdded"); setShowSortMenu(false); }}>
            <Text style={styles.sortOptionText}>Date added</Text>
          </Pressable>
          <Pressable style={styles.sortOption} onPress={() => { setSortBy("name"); setShowSortMenu(false); }}>
            <Text style={styles.sortOptionText}>Name</Text>
          </Pressable>
          <Pressable style={styles.sortOption} onPress={() => { setSortBy("length"); setShowSortMenu(false); }}>
            <Text style={styles.sortOptionText}>Length</Text>
          </Pressable>
        </View>
      )}

      <FlatList
        data={filteredAndSortedTracks}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <TrackRow
            title={item.title}
            artist={item.artist}
            duration={item.duration}
            cover={item.cover}
            showHeart={true}
            liked={item.liked}
            onToggleLike={() => toggleLike(item.albumId, item.id)}
            onPress={() => {
              const album = albums.find((a) => a.id === item.albumId);
              if (album) navigation.navigate("Album", { album });
            }}
          />
        )}
        ListEmptyComponent={
          <Text style={styles.emptyText}>No liked tracks found.</Text>
        }
        keyboardShouldPersistTaps="handled"
        contentContainerStyle={{ paddingBottom: 180 }}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#000",
    paddingTop: 24,
    paddingHorizontal: 16,
  },
  backBtn: {
    marginBottom: 10,
    alignSelf: "flex-start",
  },
  backText: {
    color: "#fff",
    fontSize: 16,
    fontWeight: "600",
  },
  title: {
    color: "#fff",
    fontSize: 30,
    fontWeight: "700",
    marginBottom: 12,
  },
  searchInput: {
    backgroundColor: "#1f2937",
    color: "#fff",
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 16,
    marginBottom: 12,
  },
  emptyText: {
    color: "#9ca3af",
    fontSize: 15,
    marginTop: 16,
  },
  sortRow: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 8,
  },
  sortByText: {
    color: "#9ca3af",
    marginRight: 8,
    fontSize: 14,
  },
  sortButton: {
    backgroundColor: "#111827",
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 6,
  },
  sortButtonText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "600",
  },
  sortMenu: {
    backgroundColor: "#111827",
    borderRadius: 10,
    marginBottom: 10,
    overflow: "hidden",
    borderWidth: 1,
    borderColor: "#1f2937",
  },
  sortOption: {
    paddingHorizontal: 12,
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBottomColor: "#1f2937",
  },
  sortOptionText: {
    color: "#fff",
    fontSize: 15,
  },
  sortDirButton: {
    backgroundColor: "#111827",
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 6,
    marginLeft: 8,
  },
  sortDirButtonText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "600",
  },
});