import { useRoute } from "@react-navigation/native";
import React, { useState } from "react";
import { Image, Pressable, View } from "react-native";
import { SheetManager } from "react-native-actions-sheet";
import { useDataFromRef } from "react-native-minuit/src/hooks";
import useDataFromArrayId from "react-native-minuit/src/hooks/useDataFromArrayId";
import { useGlobal } from "reactn";
import { background, icons } from "../../assets";
import MoreMenu from "../../components/MoreMenu";
import { playlistsRef, projectsRef } from "../../config/firebase";
import Page from "../../layouts/Page";
import { Routes } from "../../navigation";
import { goBack, navigate } from "../../navigation/NavigationService";
import { gutters } from "../../styles";
import MusicCard from "./components/MusicCard";

const PlaylistDetails = () => {
  const [, setTooltip] = useGlobal("_tooltip");
  const route = useRoute();
  const playlistId = route?.params?.playlistId;

  // Fetch the playlist document
  const { data: playlist } = useDataFromRef({
    ref: playlistId ? playlistsRef.doc(playlistId) : null,
    simpleRef: true,
    listener: true,
    condition: !!playlistId,
    refreshArray: [playlistId],
  });

  // Fetch projects by ids from playlist.musics
  const { data: musics } = useDataFromArrayId({
    ref: projectsRef,
    arrayId: Array.isArray(playlist?.musics) ? playlist.musics : [],
    condition: Array.isArray(playlist?.musics) && playlist.musics.length > 0,
    refreshArray: [playlistId, playlist?.musics?.length || 0],
  });

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

  const confirmDelete = () => {
    SheetManager.show("Delete", {
      payload: {
        title: "Supprimer la playlist",
        message: "Es-tu sûr de vouloir supprimer cette playlist ?",
        onConfirm: async () => {
          try {
            if (playlistId) {
              await playlistsRef.doc(playlistId).delete();
              setTooltip({ type: "success", text: "Playlist supprimée" });
            }
          } catch (e) {
            console.log("Delete playlist error", e?.message);
            setTooltip({
              type: "error",
              text: e?.message || "Suppression impossible",
            });
          } finally {
            goBack();
          }
        },
      },
    });
  };

  return (
    <Page
      headerType="NAVIGATION"
      backgroundImg={background.libraryBG}
      title={playlist?.name || "Playlist"}
      rightComponent={() => (
        <Pressable onPress={confirmDelete}>
          <Image source={icons.trash} style={{ width: 24, height: 24 }} />
        </Pressable>
      )}
      contentContainerStyle={{ paddingBottom: gutters * 2 }}
    >
      <View style={{ flex: 1, gap: 10 }}>
        {Array.isArray(musics) &&
          musics.map((p) => (
            <MusicCard
              key={p.id}
              title={p?.title}
              subtitle={"MusicLand"}
              imageUri={p?.coverUrl || null}
              projectId={p?.id}
              likedBy={p?.likedBy || []}
              onPress={() => navigate(Routes.MusicDetails, { projectId: p.id })}
              onPressMore={(posTop) => {
                setSelectedProjectId(p.id);
                setMenuTop(posTop);
                setShowMenu((prev) => !prev || posTop !== menuTop);
              }}
            />
          ))}

        <MoreMenu
          visible={showMenu}
          top={menuTop}
          onClose={() => setShowMenu(false)}
          inPlaylist
          playlistId={playlistId}
          projectId={selectedProjectId}
        />
      </View>
    </Page>
  );
};

export default PlaylistDetails;
