import { createEffect, createMemo, type Component } from "solid-js";
import { dispatch, state } from "../../store/state";
import { CommunityActionTypes, ICommunity } from "../../store/community";
import { ChannelActionTypes } from "../../store/channel";
import { Channel } from "../../components/Channel";
import { CommunityBar } from "../../components/CommunityBar";

const ChannelView: Component = () => {
    const channelIds = createMemo(() => {
        const activeCommunityId = state.community.active;
        if (!activeCommunityId) {
            return [];
        }

        const community = state.community.communities[activeCommunityId];
        if (!community) {
            return [];
        }

        return community.channels ?? [];
    });

    const communityInfo = createMemo<ICommunity | undefined>(() => {
        const activeCommunityId = state.community.active;
        return state.community.communities[activeCommunityId ?? 0];
    });

    createEffect(() => {
        if (state.community.active) {
            dispatch({
                type: CommunityActionTypes.FETCH_COMMUNITY_CHANNELS_START,
                payload: state.community.active,
            });
        }
    });

    const onChannelClick = (id: string) => {
        dispatch({
            type: ChannelActionTypes.FETCH_CHANNEL_START,
            payload: id,
        });
        dispatch({
            type: ChannelActionTypes.SET_ACTIVE_CHANNEL,
            payload: id,
        });
    };

    const mapChannel = (channelId: string) => {
        const channel = state.channel.channels[channelId];
        if (!channel) {
            return undefined;
        }

        return (
            <Channel
                id={channel.id}
                name={channel.name ?? ""}
                active={channel.id === state.channel.active}
                onChannelClick={onChannelClick}
            />
        );
    };

    return (
        <div class="bg-stone-900 w-80 shadow-panel z-20 h-full relative">
            <CommunityBar
                id={communityInfo()?.id}
                name={communityInfo()?.name}
                description={communityInfo()?.description}
                avatar={
                    "https://img.daisyui.com/images/profile/demo/yellingcat@192.webp"
                }
            />
            <ul class="h-full list flex flex-col p-2 gap-1 pt-18 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-500 scrollbar-track-gray-800">
                {channelIds().map(mapChannel)}
            </ul>
        </div>
    );
};

export { ChannelView };
