import { View, Image } from "react-native";
import React, { useState } from "react";
import * as ImagePicker from "expo-image-picker";
import { ai, background } from "../../assets";
import Page from "../../layouts/Page";
import { goBack, navigate } from "../../navigation/NavigationService";
import MusicLandHeader from "../../components/MusicLandHeader";
import { Routes } from "../../navigation";
import GradientButton from "../../components/GradientButton";
import { gutters } from "../../styles";
import FullscreenIntroVideo from "../../components/FullscreenIntroVideo";
import BorderGradientButton from "../../components/BorderGradientButton";
import { useUserData } from "../../providers/UserDataProvider";
import { uploadFileToFirebase } from "../../helpers/uploadToFirebase";
import useMinuit from "react-native-minuit/src/hooks/useMinuit";

export const ChooseCoverType = () => {
  const [showIntro, setShowIntro] = useState(true);
  const { selectedProject, selectedProjectId, updateProjectData } =
    useUserData();
  const { setIsLoading } = useMinuit();

  const onPickUserImage = async () => {
    try {
      await setIsLoading(true);
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ["images"],
        allowsEditing: true,
        aspect: [1, 1],
        quality: 1,
      });

      const uri = result?.assets?.[0]?.uri || null;
      if (!uri) return;

      const projectId = selectedProject?.id || selectedProjectId;
      const path = `musics/${projectId}/userSelectedCover.png`;

      const { resultURI } = await uploadFileToFirebase({
        uri,
        path,
        shouldCompress: true,
        fileType: "IMAGE",
      });

      if (!resultURI) {
        throw new Error("Erreur lors de l'upload");
      }
      await updateProjectData({
        cover: {
          result: resultURI,
        },
      });
      navigate(Routes.ValidateCover);
    } catch (e) {
      console.log("onPickUserImage error", e?.message);
    } finally {
      await setIsLoading(false);
    }
  };

  return (
    <Page backgroundImg={background.productionBG2} headerType="NONE">
      <Image
        source={ai.bena}
        style={{
          width: "100%",
          height: "70%",
          position: "absolute",
          bottom: -40,
          right: -30,
        }}
        resizeMode="contain"
      />
      <MusicLandHeader onPressBack={goBack} progress={9} />
      <View
        style={{ flex: 1, position: "relative", justifyContent: "flex-end" }}
      >
        <View
          style={{
            paddingBottom: gutters * 2,
            paddingHorizontal: gutters,
            gap: 12,
          }}
        >
          <BorderGradientButton
            title="Choisir une image"
            onPress={onPickUserImage}
          />
          <GradientButton
            title="Générer une pochette"
            onPress={() => navigate(Routes.PouchReady)}
          />
        </View>
      </View>
      <FullscreenIntroVideo
        visible={showIntro}
        onClose={() => setShowIntro(false)}
      />
    </Page>
  );
};
