import { View, Text, TouchableOpacity } 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 { useAtom } from "jotai";
import { selectedUserAtom } from "@/components/pages/calendar/atoms";

const UsersList = () => {
  const { user: currentUser } = useAuthContext();
  const { data: familyMembers, refetch: refetchFamilyMembers } =
    useGetFamilyMembers();
  const [selectedUser, setSelectedUser] = useAtom(selectedUserAtom);

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

  const sortedMembers = useMemo(() => {
    const filtered = familyMembers
      ?.filter((member) => member.userType !== ProfileType.FAMILY_DEVICE);
    
    const currentUserData = filtered?.find(m => m.uid === currentUser?.uid);
    const parents = filtered?.filter(m => m.userType === ProfileType.PARENT && m.uid !== currentUser?.uid) || [];
    const children = filtered?.filter(m => m.userType === ProfileType.CHILD && m.uid !== currentUser?.uid) || [];
    const caregivers = filtered?.filter(m => m.userType === ProfileType.CAREGIVER && m.uid !== currentUser?.uid) || [];
  
    const familyViewOption = {
      uid: 'family-view',
      firstName: 'Family',
      lastName: 'View',
      userType: 'Family View',
      eventColor: colorMap.pink
    };
  
    return currentUserData 
      ? [currentUserData, ...parents, ...children, familyViewOption, ...caregivers]
      : [...parents, ...children, familyViewOption, ...caregivers];
  }, [familyMembers, currentUser]);

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

  useEffect(() => {
    console.log(selectedUser);
  }, [selectedUser]);

  return (
    <View centerH paddingT-10 marginB-70>
      {sortedMembers?.map((member, index) => (
        <TouchableOpacity
          key={member.uid}
          onPress={() => {
            if (member.uid === 'family-view') {
              setSelectedUser(null);
            } else {
              setSelectedUser(selectedUser?.uid === member.uid ? null : member);
            }
          }}
          style={[
            styles.memberContainer,
            selectedUser?.uid === member.uid && styles.selectedMember,
          ]}
        >
          {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>
        </TouchableOpacity>
      ))}
    </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,
  },
  memberContainer: {
    alignItems: "center",
    marginBottom: 20,
  },
  selectedMember: {
    opacity: 1,
  },
});

export default UsersList;
