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 SwiperFlatList from "react-native-swiper-flatlist";
import { icons } from "../../assets";
import { arrayUnion, playlistsRef } from "../../config/firebase";
import useMinuit from "react-native-minuit/src/hooks/useMinuit";
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 isDuplicateName = useMemo(() => {
    const lower = (playlist || "").trim().toLowerCase();
    if (!lower) return false;
    const list = Array.isArray(userPlaylists) ? userPlaylists : [];
    return list.some((p) => (p?.name || "").trim().toLowerCase() === lower);
  }, [playlist, JSON.stringify(userPlaylists)]);

  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={Array.isArray(userPlaylists) ? userPlaylists : []}
              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 = (
                      Array.isArray(userPlaylists) ? userPlaylists : []
                    ).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 {
                  SheetManager.hide("Playlist");
                }
              }}
            />
          </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,
                }}
              >
                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();
                  // Unicité du nom pour l'utilisateur courant (insensible à la casse)
                  const exists = (
                    Array.isArray(userPlaylists) ? userPlaylists : []
                  ).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("");
                  SheetManager.hide("Playlist");
                  scrollRef.current.scrollToIndex({ index: 0, animated: true });
                } catch (e) {
                  console.log(e);
                  setTooltip({
                    type: "error",
                    text: e?.message || "Création impossible",
                  });
                } finally {
                  setIsCreating(false);
                }
              }}
            />
          </View>
        </View>
      </SwiperFlatList>
    </AppActionSheet>
  );
};

export default PlaylistModal;
