import { createMemo, type Component } from "solid-js";
import { Community } from "../../components/Community";
import { dispatch, state } from "../../store/state";
import { CommunityActionTypes } from "../../store/community";

const CommunityView: Component = () => {
    const communityIds = createMemo(() => {
        const loggedUserId = state.user.loggedUserId;
        if (!loggedUserId) {
            return [];
        }

        const loggedUser = state.user.users[loggedUserId];
        if (!loggedUser) {
            return [];
        }

        return loggedUser.communities ?? [];
    });

    const onCommunityClick = (id: string) => {
        dispatch({
            type: CommunityActionTypes.FETCH_COMMUNITY_START,
            payload: id,
        });
        dispatch({
            type: CommunityActionTypes.SET_ACTIVE_COMMUNITY,
            payload: id,
        });
    };

    const mapCommunity = (communityId: string) => {
        const community = state.community.communities[communityId];
        if (!community) {
            return undefined;
        }

        return (
            <Community
                id={community.id}
                name={community.name ?? ""}
                avatar={
                    "https://img.daisyui.com/images/profile/demo/yellingcat@192.webp"
                }
                active={community.id === state.community.active}
                onCommunityClick={onCommunityClick}
            />
        );
    };

    return (
        <div class="bg-stone-950 w-18 h-full shadow-panel z-30 flex flex-col p-2 gap-2">
            {communityIds().map(mapCommunity)}
        </div>
    );
};

export { CommunityView };
