import React, { useState } from "react";
import {
  FlatList,
  Image,
  Pressable,
  View,
  useWindowDimensions,
} from "react-native";
import { Routes } from "../../../navigation";
import { navigate } from "../../../navigation/NavigationService";
import { useUserData } from "../../../providers/UserDataProvider";
import CardContainer from "./CardContainer";
const BackTracks = () => {
  const { userPlaybacks } = useUserData();
  const items = Array.isArray(userPlaybacks) ? userPlaybacks.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="Mes Playbacks"
      onPress={() =>
        navigate(Routes.AllMyList, {
          title: "Mes playbacks",
          scope: "playback",
          liked: false,
        })
      }
    >
      <View>
        {items.length > 0 && (
          <FlatList
            onLayout={(e) => setContainerWidth(e.nativeEvent.layout.width)}
            data={items}
            numColumns={numColumns}
            key={numColumns}
            columnWrapperStyle={{ gap }}
            keyExtractor={(item) => item.id}
            renderItem={({ item }) => (
              <View style={{ width: itemWidth }} key={item.id}>
                <Pressable
                  onPress={() =>
                    navigate(Routes.Playbacks, { projectId: item.id })
                  }
                >
                  <Image
                    source={{ uri: item.coverUrl || "" }}
                    style={{
                      width: "100%",
                      height: Math.round((itemWidth * 16) / 9),
                      borderRadius: 10,
                    }}
                  />
                </Pressable>
              </View>
            )}
          />
        )}
      </View>
    </CardContainer>
  );
};

export default BackTracks;
