import { Image as ExpoImage } from "expo-image";
import React, { useState } from "react";
import {
  FlatList,
  Pressable,
  Image as RNImage,
  useWindowDimensions,
} from "react-native";
import { img } from "../../../assets";
import { Routes } from "../../../navigation";
import { navigate } from "../../../navigation/NavigationService";
import { useUser } from "../../../providers/UserDataProvider";
import CardContainer from "./CardContainer";

const LikedMusic = () => {
  const { userLikedProjects = [] } = useUser();
  const items = Array.isArray(userLikedProjects)
    ? userLikedProjects.slice(0, 3)
    : [];
  const { width: screenWidth } = useWindowDimensions();
  const [containerWidth, setContainerWidth] = useState(screenWidth);
  const numColumns = 3;
  const gap = 8;
  const itemWidth = Math.max(
    0,
    Math.floor((containerWidth - gap * (numColumns - 1)) / numColumns)
  );
  return (
    <CardContainer
      label="Musiques likées"
      onPress={() =>
        navigate(Routes.AllMyList, {
          title: "Musiques likées",
          scope: "music",
          liked: true,
        })
      }
    >
      <FlatList
        onLayout={(e) => setContainerWidth(e.nativeEvent.layout.width)}
        scrollEnabled={false}
        data={items}
        numColumns={numColumns}
        key={numColumns}
        contentContainerStyle={{}}
        columnWrapperStyle={numColumns > 1 ? { gap } : null}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <Pressable
            style={{ width: itemWidth }}
            onPress={() =>
              navigate(Routes.MusicDetails, { projectId: item.id })
            }
          >
            {item?.coverUrl ? (
              <ExpoImage
                source={{ uri: item.coverUrl }}
                cachePolicy="memory-disk"
                priority="high"
                contentFit="cover"
                transition={100}
                style={{
                  width: "100%",
                  height: itemWidth,
                  borderRadius: 10,
                }}
              />
            ) : (
              <RNImage
                source={img.placeholder3}
                style={{
                  width: "100%",
                  height: itemWidth,
                  borderRadius: 10,
                }}
              />
            )}
          </Pressable>
        )}
      />
    </CardContainer>
  );
};

export default LikedMusic;
