import { ActivityIndicator, Text, View } from "react-native";
import React from "react";
import MusicLandHeader from "../../components/MusicLandHeader";
import { background } from "../../assets";
import Page from "../../layouts/Page";
import { goBack, navigate } from "../../navigation/NavigationService";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
import { gutters, Palette, Style } from "../../styles";
import BorderGradientButton from "../../components/BorderGradientButton";
import { Routes } from "../../navigation";
import GradientButton from "../../components/GradientButton";
import * as ImagePicker from "expo-image-picker";
import { uploadFileToFirebase } from "../../helpers/uploadToFirebase";
import { useUserData } from "../../providers/UserDataProvider";
import useMinuit from "react-native-minuit/src/hooks/useMinuit";
import firebase, { tasksRef } from "../../config/firebase";
import { Image as ExpoImage } from "expo-image";

const PhotoCover = () => {
  const { selectedProject, selectedProjectId, updateProjectData } =
    useUserData();
  const { setIsLoading } = useMinuit();
  const isGenerating = selectedProject?.coverStatus === "GENERATING";

  const onChooseForegroundImage = 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}/userForeground.png`;

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

      if (!resultURI) {
        throw new Error("Erreur lors de l'upload");
      }
      await updateProjectData({
        cover: {
          ...selectedProject.cover,
          userForeground: resultURI,
        },
      });
      await tasksRef.add({
        type: "combine",
        projectId: selectedProjectId,
        status: "PENDING",
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) {
      console.log("onPickUserImage error", e?.message);
    } finally {
      await setIsLoading(false);
    }
  };

  return (
    <Page backgroundImg={background.studioBG2} headerType="NONE">
      <MusicLandHeader onPressBack={goBack} progress={81} />
      <View style={{ flex: 1, marginTop: 16 }}>
        <CreateLyricsHeader title="Souhaites-tu rajouter une photo de toi sur la pochette?" />
        <View style={{ flex: 1, ...Style.containerCenter }}>
          <View style={{ width: "80%", position: "relative" }}>
            {selectedProject?.cover?.result && !isGenerating ? (
              <ExpoImage
                source={{ uri: selectedProject?.cover?.result }}
                cachePolicy="memory-disk"
                priority="high"
                contentFit="cover"
                transition={120}
                style={{ width: "100%", height: 300, borderRadius: 20 }}
              />
            ) : (
              <View
                style={{
                  width: "100%",
                  height: 300,
                  borderRadius: 20,
                  backgroundColor: "#00000040",
                  ...Style.containerCenter,
                }}
              >
                {isGenerating && (
                  <View style={{ alignItems: "center", gap: 8 }}>
                    <ActivityIndicator color={Palette.white} />
                    <Text style={{ color: Palette.white, marginTop: 6 }}>
                      Génération en cours.
                    </Text>
                  </View>
                )}
              </View>
            )}
          </View>
        </View>
      </View>
      <View
        style={{
          paddingBottom: gutters * 2,
          width: "80%",
          alignSelf: "center",
          gap: 12,
        }}
      >
        <BorderGradientButton
          onPress={() => navigate(Routes.ValidateCover)}
          title={
            isGenerating ? "Génération en cours..." : "Valider la pochette"
          }
          disabled={isGenerating}
        />
        <GradientButton
          title={
            isGenerating ? "Génération en cours..." : "Oui choisir une image"
          }
          onPress={() => onChooseForegroundImage()}
          disabled={isGenerating}
        />
      </View>
    </Page>
  );
};

export default PhotoCover;
