import { View, Text, Image, Pressable, Platform } from "react-native";
import React, { useMemo, useState } from "react";
import Page from "../layouts/Page";
import { ai, background, icons } from "../assets";
import { Palette, Style } from "../styles";
import { responsiveHeight } from "react-native-responsive-dimensions";
import BorderGradient from "../components/BorderGradient/BorderGradient";
import { BlurView } from "expo-blur";
import { FONT_FAMILY } from "../styles/Fonts";
import { size } from "../styles/Style";
import GradientButton from "../components/GradientButton";
import { goBack, navigate } from "../navigation/NavigationService";
import { Routes } from "../navigation";
import { useUser } from "../providers/UserDataProvider";

const CreateSongs = () => {
  const [selectedIndex, setSelectedIndex] = useState(null);
  const { userProjects = [] } = useUser();
  const projects = useMemo(
    () => (Array.isArray(userProjects) ? userProjects.slice(0, 3) : []),
    [userProjects],
  );
  const fmtDate = (ts) => {
    try {
      const d = ts?.toDate ? ts.toDate() : ts ? new Date(ts) : null;
      if (!d || Number.isNaN(d.getTime())) return "";
      const dd = `${d.getDate().toString().padStart(2, "0")}/${(d.getMonth() + 1)
        .toString()
        .padStart(2, "0")}`;
      return dd;
    } catch (_) {
      return "";
    }
  };

  return (
    <Page backgroundImg={background.homeBG} headerType="NONE">
      <View style={{ flex: 1, ...Style.containerCenter }}>
        <View
          style={{
            width: "100%",
            height: responsiveHeight(60),
          }}
        >
          <BorderGradient
            gradientProps={{
              colors: ["#FFFFFF00", Palette.white],
              start: { x: 0, y: 0 },
              end: { x: 1, y: 0.4 },
            }}
            style={{
              borderWidth: 1,
              borderRadius: 20,
              height: responsiveHeight(55),
            }}
          >
            <Image
              source={ai.nathalie}
              style={{
                width: 171,
                height: 250,
                position: "absolute",
                zIndex: 3,
                top: -100,
                alignSelf: "center",
              }}
              resizeMode="contain"
            />
            <BlurView
              intensity={40}
              style={{
                flex: 1,
                borderRadius: 20,
                overflow: "hidden",
                justifyContent: "flex-end",
                backgroundColor: Palette.glass,
                paddingHorizontal: 10,
                zIndex: 1,
                gap: 20,
                paddingVertical: 20,
              }}
              experimentalBlurMethod={
                Platform.OS !== "ios" ? "dimezisBlurView" : "none"
              }
            >
              <Pressable
                style={{
                  position: "absolute",
                  ...Style.containerCenter,
                  ...size({ size: 24 }),
                  top: 10,
                  left: 10,
                }}
                onPress={goBack}
              >
                <Image
                  source={icons.close}
                  style={{
                    ...size({ size: 15 }),
                  }}
                />
              </Pressable>
              <View style={{ alignItems: "center", zIndex: 2 }}>
                <Text
                  style={{
                    fontSize: 22,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.InterSemiBold,
                  }}
                >
                  Atelier écriture
                </Text>
                <Text
                  style={{
                    fontSize: 14,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.InterRegular,
                  }}
                >
                  C'est ici que je vais t'aider à écrire ta chanson.
                </Text>
              </View>
              <View style={{ gap: 10, zIndex: 1 }}>
                {projects.map((item, index) => (
                  <Pressable
                    key={index}
                    onPress={() => {
                      console.log("Pressed");
                      if (selectedIndex === index) {
                        setSelectedIndex(null);
                      } else {
                        setSelectedIndex(index);
                      }
                    }}
                    style={{ zIndex: 1 }}
                  >
                    <BlurView
                      tint={selectedIndex === index ? "default" : "dark"}
                      style={{
                        ...Style.containerSpaceBetween,
                        paddingHorizontal: 12,
                        paddingVertical: 10,
                        borderRadius: 14,
                        backgroundColor: Palette.glass,
                        overflow: "hidden",
                      }}
                      experimentalBlurMethod={
                        Platform.OS !== "ios" ? "dimezisBlurView" : "none"
                      }
                    >
                      <View>
                        <Text
                          style={{
                            fontSize: 16,
                            color:
                              selectedIndex === index
                                ? Palette.black
                                : Palette.white,
                            fontFamily: FONT_FAMILY.InterRegular,
                          }}
                        >
                          {item?.title || "Sans titre"}
                        </Text>
                        <Text
                          style={{
                            fontSize: 12,
                            color:
                              selectedIndex === index
                                ? Palette.black
                                : Palette.white,
                            fontFamily: FONT_FAMILY.InterRegular,
                          }}
                        >
                          {`Modifié le ${fmtDate(item?.updatedAt || item?.createdAt)}`}
                        </Text>
                      </View>
                      <Pressable>
                        <Image
                          source={icons.threeDots}
                          style={{
                            ...size({ size: 24 }),
                            transform: [{ rotateZ: "90deg" }],
                          }}
                          tintColor={
                            selectedIndex === index
                              ? Palette.black
                              : Palette.white
                          }
                          resizeMode="contain"
                        />
                      </Pressable>
                    </BlurView>
                  </Pressable>
                ))}
              </View>
              <GradientButton
                title={selectedIndex !== null ? "Poursuivre la création" : "Créer un texte"}
                containerStyle={{
                  width: "80%",
                  alignSelf: "center",
                  marginTop: 10,
                }}
                onPress={() => navigate(Routes.Writing)}
              />
            </BlurView>
          </BorderGradient>
        </View>
      </View>
    </Page>
  );
};

export default CreateSongs;
