import "./DeckColumn.css";

import { filters, findByPropsLazy, findComponentByCodeLazy, findStoreLazy, mapMangledModuleLazy } from "@webpack";
import { ChannelStore, GuildStore, MessageActions, useEffect, useMemo, useStateFromStores } from "@webpack/common";
import { ChannelDeck, ChannelDeckStore, DeckColumn } from "../ChannelDeckStore";
import { cl } from "./util";

const { HeaderBar, HeaderBarIcon } = mapMangledModuleLazy(".themedMobile]:", {
    HeaderBarIcon: filters.byCode('size:"custom",'),
    HeaderBar: filters.byCode(".themedMobile]:"),
});
const ChannelHeader = findComponentByCodeLazy(".forumPostTitle]:", '"channel-".concat');
const XSmallIcon = findComponentByCodeLazy("1.4L12 13.42l5.3 5.3Z");
const Chat = findComponentByCodeLazy("filterAfterTimestamp:", "chatInputType");
const ChatInputTypes = findByPropsLazy("FORM", "NORMAL");
const AuthenticationStore = findStoreLazy("AuthenticationStore");

export default function DeckColumn({ column, deck, index }: { column: DeckColumn; deck: ChannelDeck; index: number; }) {
    const channel = ChannelStore.getChannel(column.channelId);
    const guild = GuildStore.getGuild(channel.guild_id);
    const chatInputType = useMemo(() => ({
        ...ChatInputTypes.SIDEBAR
    }), []);
    // Load messages after reconnecting
    const sessionId = useStateFromStores([AuthenticationStore], () => AuthenticationStore.getSessionId());
    useEffect(() => {
        // Manually load messages :/
        MessageActions.fetchMessages({
            channelId: channel.id,
            limit: 50,
            isPreload: undefined,
            skipLocalFetch: undefined,
            jump: {
                jumpType: "ANIMATED"
            }
        });
        return () => { };
    }, [sessionId]);
    return <div className={cl("column")} style={{
        width: column.width
    }}>
        <HeaderBar
            toolbar={
                <>
                    <HeaderBarIcon
                        icon={XSmallIcon}
                        tooltip="Close Column"
                        onClick={() => {
                            const newColumns = deck.columns;
                            newColumns.splice(index, 1);
                            ChannelDeckStore.setDeck({ ...deck, columns: newColumns });
                        }}
                    />
                </>
            }
        >
            <ChannelHeader
                channel={channel}
                channelName={channel?.name}
                guild={guild}
                parentChannel={ChannelStore.getChannel(channel?.parent_id)}
            />
        </HeaderBar>
        <Chat
            channel={channel}
            guild={guild}
            chatInputType={chatInputType}
        />
    </div>;
};
