import React, { useEffect, useRef, useState } from "react";
import { Image, Platform, Text, View } from "react-native";
import Page from "../../layouts/Page";
import { ai, background } from "../../assets";
import MusicLandHeader from "../../components/MusicLandHeader";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
import { BlurView } from "expo-blur";
import { Palette } from "../../styles";
import ProgressBar from "../../components/ProgressBar";
import GradientButton from "../../components/GradientButton";
import { goBack, navigate } from "../../navigation/NavigationService";
import { Routes } from "../../navigation";
import firebase, { projectsRef } from "../../config/firebase";
import useMinuit from "react-native-minuit/src/hooks/useMinuit.js";
import moment from "moment";
import { responsiveHeight } from "react-native-responsive-dimensions";
import { FONT_FAMILY } from "../../styles/Fonts";
import useDataFromRef from "../../hooks/useDataFromRef";

const GeneratingSong = ({ route }) => {
  const { config, projectId } = route.params;
  const [progress, setProgress] = useState(0);
  const { setIsLoading } = useMinuit();
  const progressTimerRef = useRef(null);
  const navigatedRef = useRef(false);

  const { data: project } = useDataFromRef({
    ref: projectId ? projectsRef.doc(projectId) : null,
    simpleRef: true,
    listener: true,
    condition: !!projectId,
    refreshArray: [projectId],
  });

  // Progress based on 8 minutes cap or until status changes
  useEffect(() => {
    const totalMs = 8 * 60 * 1000;
    const clearTimer = () => {
      if (progressTimerRef.current) {
        clearInterval(progressTimerRef.current);
        progressTimerRef.current = null;
      }
    };
    if (project?.musicStatus !== "GENERATING") {
      setProgress(100);
      clearTimer();
      return () => clearTimer();
    }
    const update = () => {
      const startDate = project?.generationStartAt?.toDate
        ? project.generationStartAt.toDate()
        : new Date(project?.generationStartAt || Date.now());
      const elapsed = moment().diff(moment(startDate));
      const raw = Math.floor((elapsed / totalMs) * 100);
      // While status is GENERATING, block visual progress at 99%
      const pct = Math.max(0, Math.min(99, raw));
      setProgress(pct);
    };
    update();
    clearTimer();
    progressTimerRef.current = setInterval(update, 1000);
    return () => clearTimer();
  }, [project?.musicStatus]);

  // Auto navigate to SongReady when generation completed
  useEffect(() => {
    if (!config?.projectId) return;
    if (project?.musicStatus !== "GENERATING" && !navigatedRef.current) {
      navigatedRef.current = true;
      navigate(Routes.SongReady, { projectId: config.projectId });
    }
  }, [project?.musicStatus, config?.projectId]);

  async function startMusicGeneration() {
    try {
      console.log("startMusicGeneration");
      await setIsLoading(true);
      const callable = firebase
        .functions()
        .httpsCallable("music-generateMusic");
      const { data } = await callable({
        title: config?.title,
        lyrics: config?.lyrics,
        genres: config?.genres,
        voice: config?.voice,
        instruments: config?.instruments,
        tempo: config?.tempo,
        projectId: config?.projectId,
      });
      const taskId =
        data?.response?.data?.taskId || data?.response?.data?.task_id;
      if (config?.projectId && taskId) {
        const baseUpdate = {
          sunoTaskId: taskId,
          musicStatus: "GENERATING",
          generationStartAt: firebase.firestore.FieldValue.serverTimestamp(),
          updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
        };
        const updatePayload = project?.musicConfig
          ? baseUpdate
          : {
              ...baseUpdate,
              musicConfig: {
                title: config?.title || "",
                lyrics: config?.lyrics || [],
                genres: config?.genres || [],
                voice: config?.voice || "",
                instruments: config?.instruments || [],
                tempo: config?.tempo || "",
              },
            };
        await projectsRef
          .doc(config.projectId)
          .set(updatePayload, { merge: true });
      }
    } catch (e) {
      console.log("GeneratingSong error", e?.message);
    } finally {
      await setIsLoading(false);
    }
  }

  // Trigger generation only if not already GENERATING
  useEffect(() => {
    if (!!project?.title && project?.musicStatus !== "GENERATING") {
      startMusicGeneration();
    }
  }, [project]);

  return (
    <Page headerType="NONE" backgroundImg={background.studioBG2}>
      <MusicLandHeader onPressBack={goBack} progress={63} />
      <View style={{ flex: 1, marginTop: 16 }}>
        <CreateLyricsHeader
          title="Ta musique est en cours de création !"
          subTitle="Encore un peu de patience"
          containerStyle={{ marginBottom: responsiveHeight(2) }}
        />
        <View
          style={{
            height: responsiveHeight(50),
            marginTop: responsiveHeight(10),
            gap: 16,
          }}
        >
          <View
            style={{
              zIndex: 1,
              position: "absolute",
              top: -150,
              width: "50%",
              height: "100%",
              alignSelf: "center",
            }}
          >
            <Image
              source={ai.theo}
              style={{ width: "100%", height: "100%", right: -10 }}
              resizeMode="contain"
            />
          </View>
          <BlurView
            intensity={40}
            tint="dark"
            style={{
              flex: 1,
              borderRadius: 16,
              overflow: "hidden",
              padding: 12,
              backgroundColor: "#FFFFFF0A",
            }}
            experimentalBlurMethod={
              Platform.OS !== "ios" ? "dimezisBlurView" : "none"
            }
          >
            <View style={{ flex: 1 }}>
              <BlurView
                intensity={40}
                tint="dark"
                style={{ flex: 1, padding: 10, paddingBottom: 20 }}
                experimentalBlurMethod={
                  Platform.OS !== "ios" ? "dimezisBlurView" : "none"
                }
              >
                <View style={{ flex: 1, justifyContent: "flex-end", gap: 20 }}>
                  <Text
                    style={{
                      fontSize: 22,
                      color: Palette.white,
                      fontFamily: FONT_FAMILY.InterSemiBold,
                      textAlign: "center",
                    }}
                  >
                    Ta musique est{"\n"}en cours de création
                  </Text>
                  <View style={{ alignItems: "center", gap: 16 }}>
                    <ProgressBar gradient progress={progress} />
                    <Text
                      style={{
                        fontSize: 14,
                        color: Palette.white,
                        fontFamily: FONT_FAMILY.InterRegular,
                      }}
                    >
                      {progress}%
                    </Text>
                  </View>
                  <GradientButton
                    title={"Création en cours..."}
                    disabled={project?.musicStatus === "GENERATING"}
                    containerStyle={{ width: "80%", alignSelf: "center" }}
                    onPress={() =>
                      navigate(Routes.SongReady, {
                        projectId: config?.projectId,
                      })
                    }
                  />
                </View>
              </BlurView>
            </View>
          </BlurView>
        </View>
      </View>
    </Page>
  );
};

export default GeneratingSong;
