import React, { useMemo, useState } from "react";
import { Pressable, Text, View } from "react-native";
import { Image as ExpoImage } from "expo-image";
import Page from "../../layouts/Page";
import { background, img } from "../../assets";
import { Palette, Style } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts";
import { size } from "../../styles/Style";
import { useUser } from "../../providers/UserDataProvider";
import { usersRef } from "../../config/firebase";
import useDataFromArrayId from "react-native-minuit/src/hooks/useDataFromArrayId";
import useDataFromRef from "../../hooks/useDataFromRef";
import { Routes } from "../../navigation";
import { useRoute } from "@react-navigation/native";
import { navigate } from "../../navigation/NavigationService";

const Follows = () => {
  const { params } = useRoute();
  const initial = params?.selected || "Abonnés"; // "Abonnés" | "Abonnements"
  const targetUserId = params?.userId || null;
  const [selected, setSelected] = useState(initial);
  const { currentUID, currentUserData } = useUser();

  // Abonnés (followers): docs for IDs in currentUserData.followedBy
  // If viewing another user's profile, subscribe to that user's doc
  const { data: targetUserDoc = null } = useDataFromRef({
    ref: targetUserId ? usersRef.doc(targetUserId) : null,
    simpleRef: true,
    listener: true,
    condition: !!targetUserId,
    refreshArray: [targetUserId],
  });

  const followerIds = useMemo(() => {
    if (targetUserId) {
      return Array.isArray(targetUserDoc?.followedBy)
        ? targetUserDoc.followedBy
        : [];
    }
    return Array.isArray(currentUserData?.followedBy)
      ? currentUserData.followedBy
      : [];
  }, [
    targetUserId,
    targetUserDoc?.followedBy?.length || 0,
    currentUserData?.followedBy?.length || 0,
  ]);
  const { data: followers = [], loading: followersLoading } =
    useDataFromArrayId({
      ref: usersRef,
      arrayId: followerIds,
      condition: followerIds.length > 0,
      refreshArray: [followerIds.length],
    });

  // Abonnements (following): users whose followedBy includes currentUID
  const { data: following = [], loading: followingLoading } = useDataFromRef({
    ref:
      targetUserId || currentUID
        ? usersRef.where(
            "followedBy",
            "array-contains",
            targetUserId || currentUID,
          )
        : null,
    simpleRef: false,
    listener: true,
    condition: !!(targetUserId || currentUID),
    refreshArray: [targetUserId || currentUID],
  });

  const EmptyText = ({ text }) => (
    <View style={{ flex: 1, alignItems: "center", paddingVertical: 16 }}>
      <Text
        style={{
          fontSize: 14,
          color: Palette.white,
          fontFamily: FONT_FAMILY.InterRegular,
          opacity: 0.8,
        }}
      >
        {text}
      </Text>
    </View>
  );

  const UserRow = ({ user }) => (
    <Pressable
      style={{ gap: 14, ...Style.containerRow }}
      onPress={() => navigate(Routes.SingerProfile, { userId: user?.id })}
    >
      <ExpoImage
        source={
          user?.profilePictureURL
            ? { uri: user.profilePictureURL }
            : img.profile
        }
        cachePolicy="memory-disk"
        priority="high"
        contentFit="cover"
        transition={100}
        style={{ ...size({ size: 60 }), borderRadius: 100 }}
      />
      <Text
        style={{
          fontSize: 12,
          color: Palette.white,
          fontFamily: FONT_FAMILY.InterRegular,
        }}
      >
        {user?.userName || "Utilisateur"}
      </Text>
    </Pressable>
  );

  const list = selected === "Abonnés" ? followers : following;
  const loading = selected === "Abonnés" ? followersLoading : followingLoading;

  return (
    <Page
      headerType="NAVIGATION"
      backgroundImg={background.profileBG}
      title={"Abonnés et abonnements"}
      contentContainerStyle={{ paddingBottom: 20 }}
    >
      <View style={{ gap: 12 }}>
        <View style={{ ...Style.containerRow, gap: 6 }}>
          {["Abonnés", "Abonnements"].map((item) => (
            <Pressable
              key={item}
              onPress={() => setSelected(item)}
              style={{ flex: 1 }}
            >
              <View
                style={{
                  height: 30,
                  borderRadius: 100,
                  overflow: "hidden",
                  backgroundColor:
                    selected === item ? "#FFFFFF22" : Palette.glass,
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                <Text
                  style={{
                    fontSize: 12,
                    color: Palette.white,
                    fontFamily: FONT_FAMILY.InterRegular,
                  }}
                >
                  {item}
                </Text>
              </View>
            </Pressable>
          ))}
        </View>
        <View style={{ gap: 8 }}>
          {Array.isArray(list) && list.length > 0 ? (
            list.map((u) => <UserRow key={u.id} user={u} />)
          ) : !loading ? (
            <EmptyText
              text={
                selected === "Abonnés" ? "Aucun abonné" : "Aucun abonnement"
              }
            />
          ) : null}
        </View>
      </View>
    </Page>
  );
};

export default Follows;
