import { View, Text, ScrollView, Pressable, Alert } from "react-native";
import React, { useState } from "react";
import Page from "../../layouts/Page";
import { background } from "../../assets";
import GradientButton from "../../components/GradientButton";
import { navigate } from "../../navigation/NavigationService";
import { Routes } from "../../navigation";
import { gutters } from "../../styles";
import { useUser } from "../../providers/UserDataProvider";
import { responsiveHeight } from "react-native-responsive-dimensions";

const Studio = () => {
  const [selected, setSelected] = useState(null);

  const { userProjects: projects } = useUser();

  return (
    <Page
      headerType="NONE"
      backgroundImg={background.studioBG}
      containerStyle={{ paddingHorizontal: 0 }}
      contentContainerStyle={{
        padding: gutters * 2,
      }}
    >
      <View style={{ flex: 1 }}>
        {projects?.length > 0 && (
          <View style={{ marginBottom: gutters * 2 }}>
            <Text
              style={{
                color: "#fff",
                fontSize: 18,
                marginBottom: 12,
                fontWeight: "600",
              }}
            >
              Derniers projets générés
            </Text>
            <ScrollView contentContainerStyle={{ gap: 10, paddingRight: 6 }}>
              {projects.map((p) => {
                const couplet = p?.lyrics?.couplet || "";
                const preview = couplet.split("\n").slice(0, 2).join(" ");
                const isSelected = selected === p;
                const createdAt = p?.createdAt?.toDate
                  ? p.createdAt.toDate()
                  : p?.createdAt
                    ? new Date(p.createdAt)
                    : null;
                const createdLabel =
                  createdAt && !Number.isNaN(createdAt.getTime())
                    ? `${createdAt.toLocaleDateString("fr-FR")} • ${createdAt.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" })}`
                    : "";
                return (
                  <Pressable
                    key={p.id}
                    onPress={() => setSelected(p)}
                    style={{
                      backgroundColor: "#0F0C1933",
                      borderRadius: 12,
                      padding: 12,
                      borderWidth: isSelected ? 2 : 0,
                      borderColor: isSelected ? "#F94697" : "transparent",
                    }}
                  >
                    <Text
                      style={{ color: "#fff", fontSize: 16, fontWeight: "600" }}
                    >
                      {p?.title || "Sans titre"}
                    </Text>
                    {!!createdLabel && (
                      <Text
                        style={{ color: "#bbb", marginTop: 4, fontSize: 12 }}
                      >
                        {createdLabel}
                      </Text>
                    )}
                    {!!preview && (
                      <Text
                        style={{ color: "#ddd", marginTop: 6 }}
                        numberOfLines={2}
                      >
                        {preview}
                      </Text>
                    )}
                    {p?.config?.style && (
                      <Text
                        style={{ color: "#aaa", marginTop: 6, fontSize: 12 }}
                      >
                        Style: {String(p.config.style)}
                      </Text>
                    )}
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>
        )}
      </View>
      <View style={{ justifyContent: "flex-end" }}>
        <GradientButton
          title="Commencer"
          disabled={!selected}
          onPress={() => {
            if (selected.musicStatus === "GENERATING") {
              Alert.alert(
                "Attention",
                "La chanson est en cours de génération. Veuillez patienter.",
              );
            } else {
              navigate(Routes.Compose, { projectId: selected.id });
            }
          }}
        />
        {selected?.musicUrls?.length > 0 && (
          <>
            <GradientButton
              title="Ecouter les audios"
              containerStyle={{
                marginTop: responsiveHeight(2),
              }}
              onPress={() =>
                navigate(Routes.SongReady, { projectId: selected.id })
              }
            />
            <GradientButton
              title="Générer une pochette"
              containerStyle={{
                marginTop: responsiveHeight(2),
              }}
              onPress={() =>
                navigate(Routes.PouchReady, { projectId: selected.id })
              }
            />
          </>
        )}
      </View>
    </Page>
  );
};

export default Studio;
