import { View, Text, Pressable, Image, Platform } from "react-native";
import React, { useEffect, useState } from "react";
import { Palette, Style } from "../../styles";
import { BlurView } from "expo-blur";
import { ai, icons } from "../../assets";
import { size } from "../../styles/Style";
import ProgressBar from "../../components/ProgressBar";
import { FONT_FAMILY } from "../../styles/Fonts";
import GradientButton from "../../components/GradientButton";
import { goBack, navigate } from "../../navigation/NavigationService";
import { Routes } from "../../navigation";
import firebase from "../../config/firebase";
import useMinuit from "react-native-minuit/src/hooks/useMinuit.js";

const CreatingLyrics = ({ active, config, regenerateKey, selections }) => {
  const [progress, setProgress] = useState(0);
  const [called, setCalled] = useState(false);
  const [result, setResult] = useState(null);
  const { setIsLoading } = useMinuit();

  // When asked to regenerate, reset flags so effect runs again
  useEffect(() => {
    if (active) {
      setCalled(false);
      setResult(null);
      setProgress(0);
    }
  }, [regenerateKey, active]);

  useEffect(() => {
    if (active) {
      const interval = setInterval(() => {
        setProgress((prevProgress) => {
          if (prevProgress >= 100) {
            clearInterval(interval);
            return 100;
          }
          return prevProgress + 1;
        });
      }, 100);

      return () => clearInterval(interval);
    }
  }, [active]);

  useEffect(() => {
    const run = async () => {
      try {
        setCalled(true);
        await setIsLoading(true);
        const callable = firebase
          .functions()
          .httpsCallable("lyrics-generateLyrics");
        const { data } = await callable({
          objective: config?.objective,
          context: config?.context,
          emotion: config?.emotion,
          style: config?.style,
          audience: config?.audience,
          structure: config?.structure,
          rhymes: config?.rhymes,
        });
        setResult(data);
        setProgress(100);
      } catch (e) {
        console.log(e);
      } finally {
        await setIsLoading(false);
      }
    };

    if (active && !called) {
      run();
    }
  }, [active, called, config, setIsLoading]);

  console.log(result);

  return (
    <View
      style={{
        flex: 1,
        ...Style.containerCenter,
      }}
    >
      <View
        style={{
          width: "100%",
          height: "50%",
        }}
      >
        <View
          style={{
            zIndex: 1,
            position: "absolute",
            top: -150,
            width: "50%",
            height: "80%",
            alignSelf: "center",
          }}
        >
          <Image
            source={ai.nathalie}
            style={{ width: "100%", height: "100%", right: -10 }}
            resizeMode="contain"
          />
        </View>
        <View
          style={{
            flex: 1,
            borderRadius: 20,
            overflow: "hidden",
            backgroundColor: "#0F0C1933",
          }}
        >
          <BlurView
            intensity={40}
            tint="dark"
            style={{ flex: 1, padding: 10, paddingBottom: 20 }}
            experimentalBlurMethod={
              Platform.OS !== "ios" ? "dimezisBlurView" : "none"
            }
          >
            <Pressable
              style={{
                ...size({ size: 24 }),
                ...Style.containerCenter,
                position: "absolute",
                top: 10,
                left: 10,
                zIndex: 3,
              }}
              onPress={goBack}
            >
              <Image source={icons.close} style={size({ size: 11 })} />
            </Pressable>
            <View style={{ flex: 1, justifyContent: "flex-end", gap: 20 }}>
              <Text
                style={{
                  fontSize: 22,
                  color: Palette.white,
                  fontFamily: FONT_FAMILY.InterSemiBold,
                  textAlign: "center",
                }}
              >
                Ton texte 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="Découvrir mon texte"
                containerStyle={{
                  width: "80%",
                  alignSelf: "center",
                }}
                onPress={() =>
                  navigate(Routes.Lyrics, {
                    lyricsData: result,
                    config,
                    selections,
                    hasLyrics: false,
                  })
                }
              />
            </View>
          </BlurView>
        </View>
      </View>
    </View>
  );
};

export default CreatingLyrics;
