import React, { useCallback } from "react";
import { Alert, Image, StyleSheet, View } from "react-native";
import useMinuit from "react-native-minuit/src/hooks/useMinuit.js";
import { ai, background } from "../../assets";
import BorderGradientButton from "../../components/BorderGradientButton";
import GradientButton from "../../components/GradientButton";
import MusicLandHeader from "../../components/MusicLandHeader";
import firebase from "../../config/firebase";
import Page from "../../layouts/Page";
import { Routes } from "../../navigation";
import { goBack, navigate } from "../../navigation/NavigationService";
import { gutters } from "../../styles";

const Playback = ({ route }) => {
  const { project } = route.params;
  const projectId = project?.id;
  const songIndex = project?.songIndex;
  const sunoTaskId = project?.sunoTaskId;
  const { setIsLoading } = useMinuit();

  const onPressRecord = useCallback(async () => {
    try {
      if (!projectId || songIndex === undefined || !sunoTaskId) {
        return;
        // return navigate(Routes.RecordPlayback, { project });
      }
      if (project?.musicTimestamps?.[songIndex]) {
        console.log("exists");
        return navigate(Routes.RecordPlayback, { project });
      }

      await setIsLoading(true);
      const callable = firebase
        .functions()
        .httpsCallable("music-getSunoTimestamps");
      const { data } = await callable({
        taskId: sunoTaskId,
        musicIndex: Number(songIndex) || 0,
        projectId: projectId,
      });

      if (!data?.success) {
        console.log("getSunoTimestamps failed", data?.error || data);
        Alert.alert(
          "Timestamps",
          "Impossible de récupérer les timestamps pour ce playback pour le moment. Tu peux quand même continuer."
        );
      }

      await setIsLoading(false);
      navigate(Routes.RecordPlayback, { project });
    } catch (e) {
      console.log("getSunoTimestamps error", e?.message || e);
      Alert.alert(
        "Timestamps",
        "Une erreur est survenue lors de la génération des timestamps. Tu peux quand même continuer."
      );
      await setIsLoading(false);
    }
  }, [projectId, songIndex, sunoTaskId, project, setIsLoading]);

  return (
    <Page headerType="NONE" backgroundImg={background.playbackBG2}>
      <Image source={ai.john} style={styles.img} resizeMode="contain" />
      <MusicLandHeader onPressBack={goBack} progress={25} />
      <View
        style={{
          flex: 1,
          paddingBottom: gutters * 2,
          justifyContent: "flex-end",
        }}
      >
        <View style={{ width: "80%", alignSelf: "center", gap: 12 }}>
          <BorderGradientButton title="Guide du Playbacker" />
          {/* <BorderGradientButton title="Importer une vidéo" /> */}
          <GradientButton
            title="Enregistrer mon Playback"
            onPress={onPressRecord}
          />
        </View>
      </View>
    </Page>
  );
};

export default Playback;

const styles = StyleSheet.create({
  img: {
    width: "100%",
    height: "70%",
    position: "absolute",
    bottom: -40,
  },
});
