import { View, Text, Image, ActivityIndicator } from "react-native";
import { Image as ExpoImage } from "expo-image";
import React, { useEffect, useState } from "react";
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 { FONT_FAMILY } from "../../styles/Fonts";
import { useRoute } from "@react-navigation/native";
import firebase from "../../config/firebase";

const PouchReady = () => {
  const route = useRoute();
  const projectId = route?.params?.projectId;
  const [coverUrl, setCoverUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [title, setTitle] = useState("");
  const [coverStatus, setCoverStatus] = useState(null);
  const isGenerating = coverStatus === "GENERATING";

  useEffect(() => {
    if (!projectId) return;
    const unsub = firebase
      .firestore()
      .collection("projects")
      .doc(projectId)
      .onSnapshot((doc) => {
        const d = doc.data() || {};
        setTitle(d?.title || "");
        setCoverUrl(d?.coverUrl || null);
        setCoverStatus(d?.coverStatus || null);
      });
    return () => unsub?.();
  }, [projectId]);

  const generateCover = async () => {
    if (!projectId) return;
    try {
      setLoading(true);
      // Marquer le projet en génération
      await firebase
        .firestore()
        .collection("projects")
        .doc(projectId)
        .set({ coverStatus: "GENERATING" }, { merge: true });

      // Créer une tâche pour déclencher la Cloud Function onCreate
      await firebase.firestore().collection("tasks").add({
        type: "cover",
        projectId,
        status: "PENDING",
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
    } catch (e) {
      console.log("Cover task error", e?.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!projectId) return;
    // Si pas de cover et pas déjà en génération, lancer une tâche
    if (!coverUrl && !isGenerating && !loading) {
      generateCover();
    }
  }, [projectId, coverUrl, isGenerating]);

  return (
    <Page backgroundImg={background.studioBG2} headerType="NONE">
      <MusicLandHeader onPressBack={goBack} progress={72} />
      <View style={{ flex: 1, marginTop: 16 }}>
        <CreateLyricsHeader
          title={
            coverUrl ? "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" }}>
            {coverUrl ? (
              <ExpoImage
                source={{ uri: coverUrl }}
                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 || loading ? (
                  <ActivityIndicator color={Palette.white} />
                ) : (
                  <Image
                    source={img.placeholder}
                    style={{ width: 120, height: 120, opacity: 0.5 }}
                  />
                )}
              </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 || !coverUrl}
          onPress={() => navigate(Routes.PhotoCover)}
        />
      </View>
    </Page>
  );
};

export default PouchReady;
