import { View, Dimensions } from "react-native";
import React, { useMemo, useRef, useState } from "react";
import Page from "../../layouts/Page";
import MusicLandHeader from "../../components/MusicLandHeader";
import GradientButton from "../../components/GradientButton";
import { gutters } from "../../styles";
import { SwiperFlatList } from "react-native-swiper-flatlist";
import Goals from "./Goals";
import { goBack, navigate } from "../../navigation/NavigationService";
import { Routes } from "../../navigation";
import SpecificityContext from "./SpecificityContext";
import EmotionConvey from "./EmotionConvey";
import SongStyle from "./SongStyle";
import SongTo from "./SongTo";
import SongStructure from "./SongStructure";
import CustomizeSongStructure from "./CustomizeSongStructure";
import Rhymes from "./Rhymes";
import CreatingLyrics from "./CreatingLyrics";
import { responsiveHeight } from "react-native-responsive-dimensions";

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

const CreateLyricsWithAi = ({ route }) => {
  const { hasLyrics = false, regenerateKey } = route?.params || {};
  const scrollRef = useRef(null);
  // If user already has lyrics, start at SongStructure (index 5)
  const [selectedIndex, setSelectedIndex] = useState(hasLyrics ? 5 : 0);
  const [progress, setProgress] = useState(16);
  const [parentLayout, setparentLayout] = useState(null);

  // Collected state across steps
  const [objective, setObjective] = useState(null); // from Goals list
  const [otherObjective, setOtherObjective] = useState("");
  const [context, setContext] = useState("");
  const [emotion, setEmotion] = useState(null);
  const [style, setStyle] = useState(null); // from list
  const [otherStyle, setOtherStyle] = useState("");
  const [audience, setAudience] = useState("");
  const [structure, setStructure] = useState(null); // selected structure string
  const [rhymes, setRhymes] = useState(null);
  const [customStructure, setCustomStructure] = useState(null); // array like ['couplet','refrain']

  const parsedStructure = useMemo(() => {
    // Parses strings like "1 couplet, 1 refrain, 1 couplet, 1 refrain"
    try {
      if (!structure || typeof structure !== "string") return null;
      const parts = structure.split(",");
      const result = [];
      parts.forEach((seg) => {
        const s = seg.trim().toLowerCase();
        const coupletMatch = s.match(/(\d+)\s+couplet/);
        const refrainMatch = s.match(/(\d+)\s+refrain/);
        if (coupletMatch) {
          const count = parseInt(coupletMatch[1], 10);
          for (let i = 0; i < count; i++) result.push("couplet");
        }
        if (refrainMatch) {
          const count = parseInt(refrainMatch[1], 10);
          for (let i = 0; i < count; i++) result.push("refrain");
        }
      });
      return result.length ? result : null;
    } catch (e) {
      return null;
    }
  }, [structure]);

  const lyricsConfig = useMemo(() => {
    return {
      objective: otherObjective?.trim()
        ? otherObjective.trim()
        : objective || undefined,
      context: context?.trim() ? context.trim() : undefined,
      emotion:
        emotion?.title && emotion?.description
          ? `${emotion.title} : ${emotion.description}`
          : undefined,
      style: otherStyle?.trim() ? otherStyle.trim() : style || undefined,
      audience: audience?.trim() ? audience.trim() : undefined,
      structure:
        (customStructure &&
        parsedStructure &&
        customStructure.length === parsedStructure.length
          ? customStructure
          : parsedStructure) || undefined,
      rhymes: rhymes || undefined,
    };
  }, [
    objective,
    otherObjective,
    context,
    emotion,
    style,
    otherStyle,
    audience,
    parsedStructure,
    rhymes,
    customStructure,
  ]);

  const onPressNext = () => {
    // If user already has lyrics and just finished CustomizeSongStructure (index 6),
    // skip AI generation and go straight to Lyrics editor
    if (hasLyrics && selectedIndex === 6) {
      const chosenStructure =
        (customStructure &&
        parsedStructure &&
        customStructure.length === parsedStructure.length
          ? customStructure
          : parsedStructure) || [];
      navigate(Routes.Lyrics, {
        config: { structure: chosenStructure },
        selections: {
          objective,
          otherObjective,
          context,
          emotion,
          style,
          otherStyle,
          audience,
          structure,
          parsedStructure,
          customStructure,
          rhymes,
        },
        hasLyrics: true,
      });
      return;
    }
    setSelectedIndex((idx) => idx + 1);
  };

  const onPressBack = () => {
    // If currently on SongStructure, go back to previous screen instead of previous step
    if (selectedIndex === 5) {
      goBack();
    } else if (selectedIndex > 0) {
      setSelectedIndex((idx) => Math.max(0, idx - 1));
    } else {
      goBack();
    }
  };

  // Sync scroll position and progress with selectedIndex
  React.useEffect(() => {
    if (!parentLayout?.height) return;
    try {
      const nextProgress = 16 + selectedIndex * 9;
      setProgress(nextProgress);
      scrollRef.current?.scrollToIndex?.({
        index: selectedIndex,
        animated: true,
      });
    } catch (_) {}
  }, [selectedIndex, parentLayout?.height]);

  return (
    <Page headerType="NONE">
      <MusicLandHeader
        onPressBack={onPressBack}
        progress={progress}
        showSkip={selectedIndex === 4}
      />
      <View
        style={{
          flex: 1,
          paddingBottom: gutters,
          gap: responsiveHeight(5),
        }}
      >
        <View
          style={{ flex: 1 }}
          onLayout={(e) => setparentLayout(e.nativeEvent.layout)}
        >
          <SwiperFlatList
            style={{ width, left: -gutters }}
            ref={scrollRef}
            disableGesture
            index={selectedIndex}
          >
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <Goals
                selected={objective}
                setSelected={setObjective}
                otherObjective={otherObjective}
                setOtherObjective={setOtherObjective}
              />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <SpecificityContext context={context} setContext={setContext} />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <EmotionConvey selected={emotion} setSelected={setEmotion} />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <SongStyle
                selected={style}
                setSelected={setStyle}
                otherStyle={otherStyle}
                setOtherStyle={setOtherStyle}
              />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <SongTo audience={audience} setAudience={setAudience} />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <SongStructure selected={structure} setSelected={setStructure} />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <CustomizeSongStructure
                baseStructure={parsedStructure || []}
                onChange={setCustomStructure}
              />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <Rhymes selected={rhymes} setSelected={setRhymes} />
            </View>
            <View
              style={{
                width: width,
                height: parentLayout?.height,
                paddingHorizontal: gutters,
              }}
            >
              <CreatingLyrics
                active={selectedIndex === 8}
                config={lyricsConfig}
                regenerateKey={regenerateKey}
                selections={{
                  objective,
                  otherObjective,
                  context,
                  emotion,
                  style,
                  otherStyle,
                  audience,
                  structure,
                  parsedStructure,
                  customStructure,
                  rhymes,
                }}
              />
            </View>
          </SwiperFlatList>
        </View>
        {selectedIndex !== 8 && (
          <GradientButton title="Suivant" onPress={onPressNext} />
        )}
      </View>
    </Page>
  );
};

export default CreateLyricsWithAi;
