import {
  View,
  Text,
  Image,
  ActivityIndicator,
  Alert,
  setTimeout,
} from "react-native";
import { Image as ExpoImage } from "expo-image";
import React, { useEffect } from "react";
import { useIsFocused } from "@react-navigation/native";
import Page from "../../layouts/Page";
import { background, icons, img } from "../../assets";
import MusicLandHeader from "../../components/MusicLandHeader";
import { goBack, navigate } from "../../navigation/NavigationService";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
import { gutters, Palette, Style } from "../../styles";
import BorderGradientButton from "../../components/BorderGradientButton";
import GradientButton from "../../components/GradientButton";
import { Routes } from "../../navigation";
import firebase, { tasksRef } from "../../config/firebase";
import { useUser } from "../../providers/UserDataProvider";
import useMinuit from "react-native-minuit/src/hooks/useMinuit.js";

const PouchReady = () => {
  const { selectedProjectId, selectedProject, updateProjectData } = useUser();
  const { setIsLoading } = useMinuit();
  const isGenerating = selectedProject?.coverStatus === "GENERATING";
  const isFocused = useIsFocused();

  const generateCover = async () => {
    if (!selectedProjectId) return;
    try {
      await setIsLoading(true);
      await tasksRef.add({
        type: "cover",
        projectId: selectedProjectId,
        status: "PENDING",
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) {
      console.log("Cover task error", e?.message);
    } finally {
      setIsLoading(false);
    }
  };

  async function validateCover() {
    try {
      await setIsLoading(true);
      await updateProjectData({
        cover: {
          ...selectedProject.cover,
          result: selectedProject.cover.generatedBackground,
        },
      });
      navigate(Routes.PhotoCover);
    } catch (e) {
      console.log(e);
    } finally {
      await setIsLoading(false);
    }
  }

  useEffect(() => {
    if (
      isFocused &&
      !selectedProject?.cover?.generatedBackground &&
      selectedProject?.coverStatus !== "GENERATING"
    ) {
      Alert.alert("Attention", "Générer une pochette ?", [
        {
          text: "Oui",
          onPress: generateCover,
        },
        {
          text: "Non",
        },
      ]);
    }
  }, [selectedProject, isFocused]);

  return (
    <Page backgroundImg={background.studioBG2} headerType="NONE">
      <MusicLandHeader onPressBack={goBack} progress={72} />
      <View style={{ flex: 1, marginTop: 16 }}>
        <CreateLyricsHeader
          title={
            selectedProject?.cover?.backgroundGenerated
              ? "Ta pochette est prête!"
              : "Génération de la pochette"
          }
          // subTitle="Qu’en penses-tu ?"
        />
        <View style={{ flex: 1, ...Style.containerCenter }}>
          <View style={{ width: "80%", position: "relative" }}>
            {selectedProject?.cover?.generatedBackground && !isGenerating ? (
              <ExpoImage
                source={{ uri: selectedProject?.cover?.generatedBackground }}
                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*/}
            {/*  style={{*/}
            {/*    position: "absolute",*/}
            {/*    alignSelf: "center",*/}
            {/*    alignItems: "center",*/}
            {/*    top: 10,*/}
            {/*  }}*/}
            {/*>*/}
            {/*  <Text*/}
            {/*    style={{*/}
            {/*      fontSize: 22,*/}
            {/*      color: Palette.white,*/}
            {/*      fontFamily: FONT_FAMILY.InterSemiBold,*/}
            {/*    }}*/}
            {/*  >*/}
            {/*    {title || "Titre"}*/}
            {/*  </Text>*/}
            {/*  <Text*/}
            {/*    style={{*/}
            {/*      fontSize: 14,*/}
            {/*      color: Palette.gray,*/}
            {/*      fontFamily: FONT_FAMILY.InterRegular,*/}
            {/*    }}*/}
            {/*  >*/}
            {/*    MusicLand*/}
            {/*  </Text>*/}
            {/*</View>*/}
            {/*<View*/}
            {/*  style={{*/}
            {/*    position: "absolute",*/}
            {/*    alignItems: "center",*/}
            {/*    bottom: 10,*/}
            {/*    width: "100%",*/}
            {/*  }}*/}
            {/*>*/}
            {/*  <Image*/}
            {/*    source={icons.musicLandLogo}*/}
            {/*    style={{ width: "100%", height: 30 }}*/}
            {/*    resizeMode="contain"*/}
            {/*  />*/}
            {/*</View>*/}
          </View>
        </View>
      </View>
      <View
        style={{
          paddingBottom: gutters * 2,
          width: "80%",
          alignSelf: "center",
          gap: 12,
        }}
      >
        <BorderGradientButton
          title={isGenerating ? "Génération en cours..." : "Regénérer"}
          icon={icons.stars}
          onPress={generateCover}
          disabled={isGenerating}
        />
        <GradientButton
          title={isGenerating ? "Veuillez patienter..." : "Valider"}
          disabled={isGenerating}
          onPress={() => validateCover()}
        />
      </View>
    </Page>
  );
};

export default PouchReady;
