import { View, Dimensions } from "react-native";
import React, { useMemo, useRef, useState } from "react";
import Page from "../../layouts/Page";
import { background } from "../../assets";
import MusicLandHeader from "../../components/MusicLandHeader";
import GradientButton from "../../components/GradientButton";
import { goBack } from "../../navigation/NavigationService";
import { gutters } from "../../styles";
import SwiperFlatList from "react-native-swiper-flatlist";
import ChooseGenre from "./ChooseGenre";
import CustomizeVoice from "./CustomizeVoice";
import ChooseInstruments from "./ChooseInstruments";
import ChooseRhythm from "./ChooseRhythm";
import CreatingSong from "./CreatingSong";
import { useRoute } from "@react-navigation/native";
import firebase from "../../config/firebase";
import useDataFromRef from "../../hooks/useDataFromRef";

const { width } = Dimensions.get("window");

const ComposeSong = () => {
  const scrollRef = useRef(null);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [progress, setProgress] = useState(18);
  const [containerLayout, setContainerLayout] = useState(null);
  const route = useRoute();
  const projectId = route?.params?.projectId;

  // Selections state
  const [genres, setGenres] = useState(__DEV__ ? ["Hip Hop/Rap", "Punk"] : []);
  const [voice, setVoice] = useState(
    __DEV__ ? "Deux voix pour interpreter ta chanson" : null,
  );
  const [instruments, setInstruments] = useState(
    __DEV__ ? ["Synthétiseur", "Trompette", "Piano classique"] : [],
  );
  const [rhythm, setRhythm] = useState(__DEV__ ? "Rapide" : null);

  // Fetch selected project to get title + lyrics
  const { data: project } = useDataFromRef({
    ref: projectId
      ? firebase.firestore().collection("projects").doc(projectId)
      : null,
    simpleRef: true,
    listener: true,
    condition: !!projectId,
  });

  const isStepValid = useMemo(() => {
    switch (selectedIndex) {
      case 0:
        return Array.isArray(genres) && genres.length > 0;
      case 1:
        return !!voice;
      case 2:
        return Array.isArray(instruments) && instruments.length > 0;
      case 3:
        return !!rhythm;
      default:
        return true;
    }
  }, [selectedIndex, genres, voice, instruments, rhythm]);

  const musicConfig = useMemo(() => {
    let lyricsArr = [];
    if (Array.isArray(project?.lyrics)) {
      lyricsArr = project.lyrics.map((s) => ({
        type: (s?.type || "").toLowerCase(),
        lyrics: s?.lyrics || "",
      }));
    } else {
      const c = project?.lyrics?.couplet;
      const r = project?.lyrics?.refrain;
      if (c) lyricsArr.push({ type: "couplet", lyrics: c });
      if (r) lyricsArr.push({ type: "refrain", lyrics: r });
    }
    return {
      title: project?.title || "",
      lyrics: lyricsArr,
      genres: Array.isArray(genres) ? genres : [],
      voice: voice || undefined,
      instruments: Array.isArray(instruments) ? instruments : [],
      tempo: rhythm || undefined,
      projectId: projectId || undefined,
    };
  }, [project, genres, voice, instruments, rhythm, projectId]);

  const onPressNext = () => {
    setSelectedIndex(selectedIndex + 1);
    setProgress(progress + 9);
    scrollRef.current.scrollToIndex({
      index: selectedIndex + 1,
      animated: true,
    });
  };

  const onPressBack = () => {
    if (selectedIndex > 0) {
      setSelectedIndex(selectedIndex - 1);
      setProgress(progress - 9);
      scrollRef.current.scrollToIndex({
        index: selectedIndex - 1,
        animated: true,
      });
    } else {
      goBack();
    }
  };

  return (
    <Page backgroundImg={background.studioBG2} headerType="NONE">
      <MusicLandHeader onPressBack={onPressBack} progress={progress} />
      <View style={{ flex: 1, paddingBottom: gutters, gap: 48 }}>
        <View
          style={{ flex: 1 }}
          onLayout={(event) => setContainerLayout(event.nativeEvent.layout)}
        >
          <SwiperFlatList
            style={{ width, left: -gutters }}
            ref={scrollRef}
            disableGesture
          >
            <View
              style={{
                width: width,
                height: containerLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <ChooseGenre selected={genres} setSelected={setGenres} />
            </View>
            <View
              style={{
                width: width,
                height: containerLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <CustomizeVoice selected={voice} setSelected={setVoice} />
            </View>
            <View
              style={{
                width: width,
                height: containerLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <ChooseInstruments
                selected={instruments}
                setSelected={setInstruments}
              />
            </View>
            <View
              style={{
                width: width,
                height: containerLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <ChooseRhythm selected={rhythm} setSelected={setRhythm} />
            </View>
            <View
              style={{
                width: width,
                height: containerLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <CreatingSong active={selectedIndex === 4} config={musicConfig} />
            </View>
          </SwiperFlatList>
        </View>
        {selectedIndex !== 4 && (
          <GradientButton
            title={selectedIndex === 3 ? "Générer" : "Suivant"}
            onPress={onPressNext}
            disabled={!isStepValid}
          />
        )}
      </View>
    </Page>
  );
};

export default ComposeSong;
