import { View, Text, Image, Platform } from "react-native";
import React, { useMemo, useState } from "react";
import Page from "../layouts/Page";
import { background, img } from "../assets";
import { responsiveHeight } from "react-native-responsive-dimensions";
import { Palette } from "../styles";
import { FONT_FAMILY } from "../styles/Fonts";
import { navigate } from "../navigation/NavigationService";
import { Routes } from "../navigation";
import { FlatList, Alert } from "react-native";
import { BlurView } from "expo-blur";
import { useUser } from "../providers/UserDataProvider";
import MusicCard from "./Library/components/MusicCard";
import GradientButton from "../components/GradientButton";
import MoreMenu from "../components/MoreMenu";
import { projectsRef } from "../config/firebase";
import { useGlobal } from "reactn";

const Home = () => {
  const { userProjects = [] } = useUser();
  const projects = useMemo(
    () => (Array.isArray(userProjects) ? userProjects : []),
    [userProjects],
  );
  const [, setTooltip] = useGlobal("_tooltip");
  const [menuTop, setMenuTop] = useState(0);
  const [showMenu, setShowMenu] = useState(false);
  const [selectedProjectId, setSelectedProjectId] = useState(null);

  return (
    <Page backgroundImg={background.homeBG} headerType="NONE">
      <View style={{ flex: 1 }}>
        <Image
          source={img.goodVibe}
          style={{ alignSelf: "center", position: "absolute" }}
        />
        {projects.length > 0 && (
          <View
            style={{
              height: responsiveHeight(70),
              paddingTop: responsiveHeight(6),
            }}
          >
            <BlurView
              intensity={20}
              style={{
                flex: 1,
                borderRadius: 20,
                overflow: "hidden",
                backgroundColor: Palette.glass,
                padding: 12,
                gap: 8,
              }}
              experimentalBlurMethod={
                Platform.OS !== "ios" ? "dimezisBlurView" : "none"
              }
            >
              <Text
                style={{
                  fontSize: 22,
                  color: Palette.white,
                  fontFamily: FONT_FAMILY.InterSemiBold,
                  marginBottom: 8,
                  textAlign: "center",
                }}
              >
                Musiques en cours
              </Text>
              <FlatList
                data={projects}
                keyExtractor={(item) => item.id}
                contentContainerStyle={{ gap: 10, paddingBottom: 10 }}
                renderItem={({ item }) => (
                  <MusicCard
                    title={item?.title || "Sans titre"}
                    subtitle={"MusicLand"}
                    imageUri={item?.coverUrl || null}
                    projectId={item?.id}
                    likedBy={item?.likedBy || []}
                    onPress={() =>
                      navigate(Routes.FlowSelection, { projectId: item.id })
                    }
                    onPressMore={(posTop) => {
                      setSelectedProjectId(item.id);
                      setMenuTop(posTop);
                      setShowMenu((prev) => !prev || posTop !== menuTop);
                    }}
                  />
                )}
              />
              <MoreMenu
                visible={showMenu}
                top={menuTop}
                onClose={() => setShowMenu(false)}
                inPlaylist={false}
                projectId={selectedProjectId}
                extraItems={[
                  {
                    label: "Supprimer",
                    onPress: () =>
                      Alert.alert(
                        "Confirmer la suppression",
                        "Cette action supprimera définitivement ce projet.",
                        [
                          { text: "Annuler", style: "cancel" },
                          {
                            text: "Supprimer",
                            style: "destructive",
                            onPress: async () => {
                              try {
                                if (!selectedProjectId) return;
                                await projectsRef
                                  .doc(selectedProjectId)
                                  .delete();
                                setTooltip({
                                  type: "success",
                                  text: "Projet supprimé",
                                });
                              } catch (e) {
                                setTooltip({
                                  type: "error",
                                  text: e?.message || "Suppression impossible",
                                });
                              }
                            },
                          },
                        ],
                        { cancelable: true },
                      ),
                  },
                ]}
              />
            </BlurView>
          </View>
        )}
        <View style={{ paddingTop: 12, marginBottom: responsiveHeight(10) }}>
          <GradientButton
            title="Créer une nouvelle musique"
            containerStyle={{ width: "80%", alignSelf: "center" }}
            onPress={() => navigate(Routes.FlowSelection)}
          />
        </View>
      </View>
    </Page>
  );
};

export default Home;
