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, navigate } 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 { useRoute } from "@react-navigation/native";
import { projectsRef } from "../../config/firebase";
import useDataFromRef from "../../hooks/useDataFromRef";
import { Routes } from "../../navigation";

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([]);
  const [voice, setVoice] = useState(null);
  const [instruments, setInstruments] = useState([]);
  const [rhythm, setRhythm] = useState(null);

  // Fetch selected project to get title + lyrics
  const { data: project } = useDataFromRef({
    ref: projectId ? projectsRef.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 = () => {
    if (selectedIndex === 3) {
      navigate(Routes.GeneratingSong, { config: musicConfig, projectId });
      return;
    }
    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>
          </SwiperFlatList>
        </View>
        {selectedIndex !== 4 && (
          <GradientButton
            title={selectedIndex === 3 ? "Générer" : "Suivant"}
            onPress={onPressNext}
            disabled={!isStepValid}
          />
        )}
      </View>
    </Page>
  );
};

export default ComposeSong;
