Files
musicland/src/components/modal/PlaylistModal.js
T
2025-10-02 16:48:35 +02:00

284 lines
9.2 KiB
JavaScript

import React, { useMemo, useRef, useState } from "react";
import {
Dimensions,
FlatList,
Image,
Pressable,
Text,
TextInput,
View,
} from "react-native";
import { SheetManager } from "react-native-actions-sheet";
import useMinuit from "react-native-minuit/src/hooks/useMinuit";
import SwiperFlatList from "react-native-swiper-flatlist";
import { icons } from "../../assets";
import { arrayUnion, playlistsRef } from "../../config/firebase";
import { useUserData } from "../../providers/UserDataProvider";
import { createPlaylist } from "../../screens/Library/Playlists/playlist";
import { Palette } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts";
import Style, { size } from "../../styles/Style";
import AppActionSheet from "../AppActionSheet";
import AppCheckbox from "../AppCheckbox";
import GradientButton from "../GradientButton";
const { width } = Dimensions.get("window");
const PlaylistModal = (props) => {
const scrollRef = useRef(null);
const [selectedId, setSelectedId] = useState("");
const [playlist, setPlaylist] = useState("");
const [isCreating, setIsCreating] = useState(false);
const { currentUID, userPlaylists = [] } = useUserData();
const startAtCreate = props?.payload?.startAtCreate || false;
const { setTooltip } = useMinuit();
const sanitizedPlaylists = useMemo(
() => (Array.isArray(userPlaylists) ? userPlaylists : []),
[userPlaylists],
);
const isDuplicateName = useMemo(() => {
const lower = (playlist || "").trim().toLowerCase();
if (!lower) return false;
return sanitizedPlaylists.some(
(p) => (p?.name || "").trim().toLowerCase() === lower,
);
}, [playlist, sanitizedPlaylists]);
const hideSheet = () => {
SheetManager.hide("Playlist");
};
return (
<AppActionSheet id="Playlist">
<SwiperFlatList
style={{ width, left: -14 }}
ref={scrollRef}
disableGesture
index={startAtCreate ? 1 : 0}
>
<View style={{ width, paddingHorizontal: 14 }}>
<View style={{ gap: 20 }}>
<Text
style={{
fontSize: 22,
color: Palette.white,
fontFamily: FONT_FAMILY.InterSemiBold,
textAlign: "center",
}}
>
Ajouter ce titre à une playlist
</Text>
<FlatList
data={sanitizedPlaylists}
keyExtractor={(item, index) => item?.id || `playlist-${index}`}
contentContainerStyle={{ gap: 20 }}
ListHeaderComponent={
<Pressable
style={{
...Style.containerRow,
gap: 10,
}}
onPress={() =>
scrollRef.current?.scrollToIndex({
index: 1,
animated: true,
})
}
>
<Image source={icons.add} style={size({ size: 15 })} />
<Text
style={{
fontSize: 16,
color: Palette.white,
fontFamily: FONT_FAMILY.HelveticaNeueRegular,
}}
>
Créer une nouvelle playlist
</Text>
</Pressable>
}
renderItem={({ item }) => (
<AppCheckbox
label={item?.name || "Sans nom"}
onPress={() => setSelectedId(item?.id)}
selected={selectedId === item?.id}
/>
)}
/>
<GradientButton
title="Valider"
containerStyle={{
width: "80%",
alignSelf: "center",
opacity: selectedId ? 1 : 0.5,
}}
disabled={!selectedId}
onPress={async () => {
try {
const projectId = props?.payload?.projectId;
if (!selectedId) return;
if (projectId) {
await playlistsRef.doc(selectedId).update({
musics: arrayUnion(projectId),
updatedAt: new Date(),
});
const addedPlaylist = sanitizedPlaylists.find(
(p) => p?.id === selectedId,
);
const name = addedPlaylist?.name || "la playlist";
setTooltip({
type: "success",
text: `Ajouté à “${name}”`,
});
}
} catch (e) {
console.log("Add to playlist error", e?.message);
setTooltip({
type: "error",
text: e?.message || "Ajout impossible",
});
} finally {
hideSheet();
}
}}
/>
</View>
</View>
<View style={{ width, paddingHorizontal: 14 }}>
<View style={{ gap: 20 }}>
{!startAtCreate && (
<Pressable
onPress={() => {
scrollRef.current?.scrollToIndex({
index: 0,
animated: true,
});
setPlaylist("");
}}
>
<Text
style={{
fontSize: 12,
color: Palette.gray,
fontFamily: FONT_FAMILY.HelveticaNeueRegular,
}}
>
Annuler
</Text>
</Pressable>
)}
<View style={{ ...Style.containerCenter, gap: 14 }}>
<Text
style={{
fontSize: 20,
color: Palette.white,
fontFamily: FONT_FAMILY.HelveticaNeueMedium,
textAlign: "center",
}}
>
Nommer la playlist
</Text>
<TextInput
autoFocus={true}
style={{
paddingVertical: 6,
borderBottomWidth: 1,
borderColor: Palette.white,
fontSize: 20,
color: Palette.white,
fontFamily: FONT_FAMILY.HelveticaNeueRegular,
minWidth: "30%",
maxWidth: "80%",
}}
value={playlist}
onChangeText={setPlaylist}
textAlign="center"
/>
{isDuplicateName && (
<Text
style={{
fontSize: 12,
color: Palette.red,
fontFamily: FONT_FAMILY.InterRegular,
textAlign: "center",
}}
>
Ce nom de playlist existe déjà
</Text>
)}
</View>
<GradientButton
title={isCreating ? "Création..." : "Créer la playlist"}
containerStyle={{
width: "80%",
alignSelf: "center",
opacity: playlist?.trim()?.length ? 1 : 0.5,
}}
disabled={!playlist?.trim()?.length || isCreating}
onPress={async () => {
if (!playlist?.trim()?.length || !currentUID) return;
try {
setIsCreating(true);
const name = playlist.trim();
const lower = name.toLowerCase();
const exists = sanitizedPlaylists.some(
(p) => (p?.name || "").trim().toLowerCase() === lower,
);
if (exists) {
setTooltip({
type: "error",
text: "Ce nom de playlist existe déjà",
});
return;
}
await createPlaylist({
createdBy: currentUID,
name,
musics: props?.payload?.projectId
? [props.payload.projectId]
: [],
createdAt: new Date(),
updatedAt: new Date(),
});
setTooltip({
type: "success",
text: props?.payload?.projectId
? `Playlist “${name}” créée et musique ajoutée`
: `Playlist “${name}” créée`,
});
setPlaylist("");
scrollRef.current?.scrollToIndex({
index: 0,
animated: true,
});
hideSheet();
} catch (e) {
console.log(e);
setTooltip({
type: "error",
text: e?.message || "Création impossible",
});
} finally {
setIsCreating(false);
}
}}
/>
</View>
</View>
</SwiperFlatList>
</AppActionSheet>
);
};
export default PlaylistModal;