import React, { useMemo } from "react";
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  Pressable,
  Image,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/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 HomeScreen() {
  const navigation = useNavigation();
  const { albums, likedTracks, toggleLike, loading } = useLibrary();

  const homeLikedTracks = useMemo(() => likedTracks.slice(0, 5), [likedTracks]);

  return (
    <SafeAreaView style={styles.container}>
      <Header title="Home" showIcons={true} />

      {loading ? (
        <Text style={styles.emptyText}>Loading...</Text>
      ) : (
        <>
          <Pressable onPress={() => navigation.navigate("LikedTracks")}>
            <Text style={styles.sectionTitle}>Liked tracks ➚</Text>
          </Pressable>

          {homeLikedTracks.length === 0 ? (
            <Text style={styles.emptyText}>No liked tracks yet.</Text>
          ) : (
            homeLikedTracks.map((track) => {
              const album = albums.find((a) => a.id === track.albumId);
              return (
                <TrackRow
                  key={track.id}
                  title={track.title}
                  artist={track.artist ?? "Unknown artist"}
                  duration={track.duration}
                  cover={track.cover}
                  showHeart={true}
                  liked={true}
                  onToggleLike={() => toggleLike(track.albumId, track.id)}
                  onPress={() => album && navigation.navigate("Album", { album })}
                />
              );
            })
          )}

          <Text style={[styles.sectionTitle, { marginTop: 24 }]}>Albums</Text>

          {albums.length === 0 ? (
            <Text style={styles.emptyText}>No albums found.</Text>
          ) : (
            <FlatList
              data={albums}
              keyExtractor={(item) => item.id}
              numColumns={2}
              columnWrapperStyle={styles.albumRow}
              contentContainerStyle={styles.albumList}
              renderItem={({ item }) => (
                <Pressable
                  style={styles.albumItem}
                  onPress={() => navigation.navigate("Album", { album: item })}
                >
                  {item.cover ? (
                    <Image source={item.cover} style={styles.cover} resizeMode="cover" />
                  ) : (
                    <View style={[styles.cover, styles.coverPlaceholder]}>
                      <Ionicons name="musical-notes" size={32} color="#555" />
                    </View>
                  )}
                </Pressable>
              )}
              showsVerticalScrollIndicator={false}
            />
          )}
        </>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#000",
    paddingTop: 24,
    paddingHorizontal: 16,
  },
  sectionTitle: {
    color: "#ffffff",
    fontSize: 24,
    fontWeight: "700",
    marginBottom: 12,
  },
  emptyText: {
    color: "#9ca3af",
    fontSize: 15,
    marginTop: 8,
  },
  albumList: {
    paddingBottom: 120,
  },
  albumRow: {
    justifyContent: "space-between",
    marginBottom: 12,
  },
  albumItem: {
    width: "48%",
    aspectRatio: 1,
    borderRadius: 8,
    overflow: "hidden",
    backgroundColor: "#222",
  },
  cover: {
    width: "100%",
    height: "100%",
  },
  coverPlaceholder: {
    justifyContent: "center",
    alignItems: "center",
  },
});
