import { useRoute } from "@react-navigation/native";
import React, { useState } from "react";
import { View } from "react-native";
import { background } from "../../assets";
import MoreMenu from "../../components/MoreMenu";
import Page from "../../layouts/Page";
import { Routes } from "../../navigation";
import { navigate } from "../../navigation/NavigationService";
import { useUser } from "../../providers/UserDataProvider";
import { gutters } from "../../styles";
import MusicCard from "./components/MusicCard";

export default function AllMyList() {
  const route = useRoute();
  const {
    title = "Mes éléments",
    scope = "music",
    liked = false,
  } = route?.params || {};

  const { userProjects, userLikedProjects, userPlaybacks, userLikedPlaybacks } =
    useUser();

  const items = (() => {
    if (scope === "playback") {
      return Array.isArray(liked ? userLikedPlaybacks : userPlaybacks)
        ? liked
          ? userLikedPlaybacks
          : userPlaybacks
        : [];
    }
    // music (projects)
    return Array.isArray(liked ? userLikedProjects : userProjects)
      ? liked
        ? userLikedProjects
        : userProjects
      : [];
  })();

  const [top, setTop] = useState(0);
  const [showMenu, setShowMenu] = useState(false);
  const [selectedProjectId, setSelectedProjectId] = useState(null);

  const onPressItem = (item) => {
    if (scope === "playback") {
      navigate(Routes.Playbacks, { projectId: item.id });
    } else {
      navigate(Routes.MusicDetails, { projectId: item.id });
    }
  };

  return (
    <Page
      headerType="NAVIGATION"
      backgroundImg={background.libraryBG}
      title={title}
      contentContainerStyle={{ paddingBottom: gutters * 2 }}
    >
      <View style={{ flex: 1 }}>
        <View style={{ gap: 10 }}>
          {Array.isArray(items) &&
            items.map((item) => (
              <MusicCard
                key={item.id}
                title={item?.title || "Sans titre"}
                imageUri={item?.coverUrl || null}
                subtitle={"MusicLand"}
                projectId={item?.id}
                likedBy={item?.likedBy || []}
                onPress={() => onPressItem(item)}
                onPressMore={(posTop) => {
                  setSelectedProjectId(item.id);
                  setTop(posTop);
                  setShowMenu((prev) => !prev || posTop !== top);
                }}
              />
            ))}
          <MoreMenu
            visible={showMenu}
            top={top}
            onClose={() => setShowMenu(false)}
            inPlaylist={false}
            projectId={selectedProjectId}
          />
        </View>
      </View>
    </Page>
  );
}
