import FontAwesome from "@expo/vector-icons/FontAwesome";
import { BlurView } from "expo-blur";
import React, { useMemo } from "react";
import { Image, Platform, Pressable, Text, View } from "react-native";
import { ai, background } from "../assets";
import Page from "../layouts/Page";
import { Routes } from "../navigation";
import { navigate } from "../navigation/NavigationService";
import { useUserData } from "../providers/UserDataProvider";
import { Palette } from "../styles";
import { FONT_FAMILY } from "../styles/Fonts";
import palette from "../styles/Palette";

const CREATE_DATA = [
  {
    img: ai.nathalie,
    bg: background.writingBG,
    label: "Nathalie",
    desc: "Let’s write lyrics together !",
    type: "Songwriter",
  },
  {
    img: ai.theo,
    bg: background.studioBG,
    label: "Theo",
    desc: "Come back, when\nyou’ll have lyrics!",
    type: "Beatmaker",
  },
  {
    img: ai.bena,
    bg: background.productionBG,
    label: "Bena",
    desc: "Come back when you want\nto generate cover!",
    type: "Designer",
  },
  {
    img: ai.john,
    bg: background.playbackBG,
    label: "John",
    desc: "Come back when your\naudio is ready!",
    type: "Director",
  },
];

const NewMusicOptions = ({ route }) => {
  const { userProjects } = useUserData();
  const { projectId = null } = route?.params || {};

  const currentProjet = useMemo(() => {
    if (!projectId) {
      return null;
    }
    return userProjects?.find((p) => p.id === projectId) || null;
  }, [projectId, userProjects]);

  const hasProject = !!currentProjet;
  const hasLyrics = Array.isArray(currentProjet?.lyrics)
    ? currentProjet.lyrics.length > 0
    : !!currentProjet?.lyrics;
  const hasCover = !!currentProjet?.coverUrl;
  console.log("current projet cover", currentProjet?.coverUrl);

  const isLocked = (index) => {
    // 0: Songwriter, 1: Beatmaker, 2: Producer, 3: Director
    // Rules:
    // - If no project: only Songwriter (0) is available.
    // - If project exists: Songwriter (0) is always available.
    // - If lyrics exist: Beatmaker (1) becomes available.
    // - If cover exists: Producer (2) and Director (3) become available.
    if (!hasProject) return index !== 0;

    const allowed = new Set([0]); // songwriter always allowed when project exists
    if (hasLyrics) {
      allowed.add(1);
    }
    if (hasCover) {
      allowed.add(2);
      allowed.add(3);
    }

    return !allowed.has(index);
  };

  const onPressOption = (index, item) => {
    if (isLocked(index)) return;
    switch (index) {
      case 0:
        navigate(Routes.WritingLyrics, {
          projectId: currentProjet?.id || null,
        });
        break;
      case 1:
        if (currentProjet?.musicStatus === "GENERATING") {
          navigate(Routes.GeneratingSong, { projectId: currentProjet.id });
        } else if (currentProjet?.musicStatus === "GENERATED") {
          navigate(Routes.SongReady, { projectId: currentProjet.id });
        } else {
          navigate(Routes.Compose, { projectId: currentProjet.id });
        }
        break;
      case 2:
        navigate(Routes.PouchReady, { projectId: currentProjet.id });
        break;
      case 3:
        console.log("test");
        navigate(Routes.Playback, {
          project: currentProjet,
        });
      default:
        break;
    }
  };

  return (
    <Page
      backgroundImg={background.homeBG}
      headerType="NAVIGATION"
      title={!!currentProjet ? "Continuer la création" : "Nouvelle musique"}
      scrollEnabled={true}
    >
      <View style={{ gap: 10 }}>
        {CREATE_DATA.map((item, index) => {
          const locked = isLocked(index);
          return (
            <Pressable key={index} onPress={() => onPressOption(index, item)}>
              <BlurView
                tint="dark"
                intensity={20}
                style={{
                  position: "absolute",
                  zIndex: 1,
                  left: 110,
                  top: 10,
                  paddingVertical: 8,
                  paddingHorizontal: 12,
                  borderRadius: 14,
                  borderBottomLeftRadius: 0,
                  overflow: "hidden",
                  backgroundColor: Palette.glass,
                }}
                experimentalBlurMethod={
                  Platform.OS !== "ios" ? "dimezisBlurView" : "none"
                }
              >
                <Text
                  style={{
                    fontSize: 13,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.InterSemiBold,
                  }}
                >
                  {item.label}, {item.type}
                </Text>
                <Text
                  style={{
                    fontSize: 14,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.InterRegular,
                  }}
                >
                  {item.desc}
                </Text>
              </BlurView>
              <Image
                source={item.bg}
                style={{
                  width: "100%",
                  height: 152,
                  borderRadius: 20,
                  position: "absolute",
                  bottom: 0,
                }}
              />
              <Image
                source={item.img}
                style={{ width: 130, height: 200 }}
                resizeMode="contain"
              />
              {locked && (
                <View
                  pointerEvents="none"
                  style={{
                    position: "absolute",
                    left: 0,
                    right: 0,
                    top: 0,
                    bottom: 0,
                    backgroundColor: "rgba(0,0,0,0.35)",
                    borderRadius: 20,
                    justifyContent: "center",
                    alignItems: "center",
                  }}
                >
                  <View
                    style={{
                      width: 36,
                      height: 36,
                      borderRadius: 18,
                      backgroundColor: "rgba(0,0,0,0.4)",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    <FontAwesome
                      name="lock"
                      size={24}
                      color={palette.primary}
                    />
                  </View>
                </View>
              )}
            </Pressable>
          );
        })}
      </View>
    </Page>
  );
};

export default NewMusicOptions;
