import React, {useEffect, useMemo} from "react";
import {Text, View} from "react-native-ui-lib";
import * as ScreenOrientation from "expo-screen-orientation";
import TabletContainer from "../tablet_components/TabletContainer";
import SingleUserChoreList from "./SingleUserChoreList";
import { useGetFamilyMembers } from "@/hooks/firebase/useGetFamilyMembers";
import { ImageBackground, StyleSheet } from "react-native";
import { ScrollView } from "react-native-gesture-handler";
import { ProfileType, useAuthContext } from "@/contexts/AuthContext";
import AddChore from "../../todos/AddChore";
import { useAtom } from "jotai";
import { selectedUserAtom } from "@/components/pages/calendar/atoms";

const TabletChoresPage = () => {
    const {data: users} = useGetFamilyMembers();
    const { user: currentUser } = useAuthContext();
    const [selectedUser] = useAtom(selectedUserAtom);

    const sortedUsers = useMemo(() => {
      return users
        ?.filter(member => member.userType !== ProfileType.FAMILY_DEVICE)
        .sort((a, b) => {
          if (a.uid === currentUser?.uid) return -1;
          if (b.uid === currentUser?.uid) return 1;

          const typePriority = {
            [ProfileType.PARENT]: 0,
            [ProfileType.CHILD]: 1,
            [ProfileType.CAREGIVER]: 2
          };

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

    const lockScreenOrientation = async () => {
        await ScreenOrientation.lockAsync(
            ScreenOrientation.OrientationLock.LANDSCAPE_RIGHT
        );
    };

    useEffect(() => {
        lockScreenOrientation();

        return () => {
            ScreenOrientation.unlockAsync();
        };
    }, []);

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

    return (
        <TabletContainer>
            <ScrollView horizontal>
                <View row gap-25 padding-25>
                    {sortedUsers
                        ?.filter((member) => 
                            !selectedUser || 
                            selectedUser.uid === 'family-view' || 
                            selectedUser.uid === member.uid
                        )
                        .map((user, index) => (
                            <View key={index}>
                                <View row centerV>
                                    {user.pfp ? (
                                        <ImageBackground
                                            source={{ uri: user.pfp }}
                                            style={styles.pfp}
                                            imageStyle={(user.eventColor && {
                                                borderWidth: 2,
                                                borderColor: user.eventColor,
                                            }) || undefined}
                                            borderRadius={13.33}
                                        />
                                    ) : (
                                        <View
                                            center
                                            style={styles.pfp}
                                            backgroundColor={user.eventColor || "#00a8b6"}
                                        >
                                            <Text color="white">
                                                {user.firstName.at(0)}
                                                {user.lastName.at(0)}
                                            </Text>
                                        </View>
                                    )}
                                    <Text style={styles.name} marginL-15>
                                        {user.firstName}
                                    </Text>
                                    <Text style={[styles.name, { color: "#9b9b9b" }]} marginL-5>
                                        ({capitalizeFirstLetter(user.userType)})
                                    </Text>
                                </View>
                                <SingleUserChoreList user={user} />
                            </View>
                        ))}
                </View>
            </ScrollView>
            <View style={styles.addBtn}>
                <AddChore />
            </View>
        </TabletContainer>
    );
};

const styles = StyleSheet.create({
    pfp: {
        width: 46.74,
        aspectRatio: 1,
        borderRadius: 13.33,
    },
    name: {
        fontFamily: "Manrope_600SemiBold",
        fontSize: 22.43,
        color: "#2c2c2c",
    },
    addBtn: {
        position: 'absolute',
        bottom: 50,
        right: 220
    }
});

export default TabletChoresPage;