import { View, Text } from "react-native-ui-lib";
import React, { useEffect, useMemo } from "react";
import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers";
import { ImageBackground, StyleSheet } from "react-native";
import { colorMap } from "@/constants/colorMap";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import { ScrollView } from "react-native-gesture-handler";

const UsersList = () => {
  const { user: currentUser } = useAuthContext();
  const { data: familyMembers, refetch: refetchFamilyMembers } =
    useGetFamilyMembers();

  useEffect(() => {
    refetchFamilyMembers();
  }, []);

  const sortedMembers = useMemo(() => {
    return familyMembers
      ?.filter((member) => member.userType !== ProfileType.FAMILY_DEVICE)
      .sort((a, b) => {
        // Current user first
        if (a.uid === currentUser?.uid) return -1;
        if (b.uid === currentUser?.uid) return 1;

        // Then sort by user type priority
        const typePriority = {
          [ProfileType.PARENT]: 0,
          [ProfileType.CHILD]: 1,
          [ProfileType.CAREGIVER]: 2,
        };

        return typePriority[a.userType] - typePriority[b.userType];
      });
  }, [familyMembers, currentUser]);

  const capitalizeFirstLetter = (str: string) => {
    if (!str) return "";
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
  };

  return (
    <View centerH paddingT-10 marginB-70>
        {sortedMembers?.map((member, index) => (
          <React.Fragment key={member.uid}>
            {member.pfp ? (
              <ImageBackground
                key={index}
                source={{ uri: member.pfp }}
                style={styles.pfp}
                borderRadius={200}
                imageStyle={{ borderWidth: 2, borderColor: "red" }}
              />
            ) : (
              <View
                key={index}
                style={styles.pfp}
                center
                backgroundColor={member.eventColor || colorMap.teal}
              >
                <Text color="white">
                  {member.firstName.at(0)}
                  {member.lastName.at(0)}
                </Text>
              </View>
            )}
            <Text style={styles.fName}>{member.firstName}</Text>
            <Text style={styles.role}>
              {capitalizeFirstLetter(member.userType)}
            </Text>
          </React.Fragment>
        ))}
    </View>
  );
};

const styles = StyleSheet.create({
  pfp: {
    aspectRatio: 1,
    width: 113,
    borderRadius: 100,
    marginBottom: 8,
  },
  fName: {
    fontFamily: "Manrope_600SemiBold",
    fontSize: 18.15,
  },
  role: {
    fontFamily: "Manrope_600SemiBold",
    fontSize: 12.95,
    color: "#9b9b9b",
    marginBottom: 20,
  },
});

export default UsersList;
