import { FC, useEffect, useState } from 'react';

import { useAppSelector, useAppDispatch } from '../../../../redux/hooks';
import { fetchGroupPosts } from '../../../../redux/slices/groupfeed';
import { setMenuActiveGroupPage } from '../../../../redux/slices/store';
import { fetchGroupById } from '../../../../redux/slices/groups';
import { SecondaryButton } from '../../../../components/button/SecondaryButton';
import ModalCreate from './ModalCreate';
import { PostItem } from './PostItem';
import ModalUpdate from './ModalUpdate';

interface PostsProps {
    groupId: number;
}

export const Posts: FC<PostsProps> = ({ groupId }) => {
    const dispatch = useAppDispatch();

    const [modalCreateActive, setModalCreateActive] = useState<boolean>(false);
    const [modalUpdateActive, setModalUpdateActive] = useState<boolean>(false);
    const [updatePostId, setUpdatePostId] = useState<number>(0);
    const [isAdmin, setIsAdmin] = useState<boolean>(false);
    const { pages, status } = useAppSelector(
        (state) => state.groupfeed.fetchPosts,
    );
    const { id: userId } = useAppSelector((state) => state.auth);

    const { group } = useAppSelector((state) => state.groups.fetchGroupById);

    // Загружаем только первую страницу
    useEffect(() => {
        dispatch(fetchGroupPosts({ groupId, page: 0, pageSize: 20 }));
        dispatch(fetchGroupById(groupId));
    }, [groupId]);

    useEffect(() => {
        dispatch(setMenuActiveGroupPage('home'));
    }, []);

    useEffect(() => {
        if (!group) return;

        const isUserAdmin =
            group.members?.some(
                (m) =>
                    Number(m.userId) === Number(userId) &&
                    m.role.includes('Administrator'),
            ) || false;

        setIsAdmin(isUserAdmin);
    }, [group, userId]);

    const page0 = pages[0];

    return (
        <div className="h-full relative">
            <div className="grid grid-rows-[40px,1fr,40px] h-full relative min-h-0 gap-[20px]">
                <div className="h-[40px] mb-[20px] relative">
                    {isAdmin && (
                        <div className=" h-[40px] w-[180px] absolute top-0 right-0 flex items-center">
                            <SecondaryButton
                                onClick={() => {
                                    setModalCreateActive(true);
                                }}
                                text="Создать пост"
                            />
                        </div>
                    )}
                </div>

                <>
                    {status === 'loading' && <div>Загрузка...</div>}
                    {status === 'failed' && <div>Ошибка загрузки постов</div>}

                    {status == 'successful' &&
                    page0?.items &&
                    page0.items.length > 0 ? (
                        <div className="min-h-0 overflow-y-scroll thin-dark-scrollbar">
                            <div className="flex flex-col gap-[20px] min-h-0 h-0 px-[16px]">
                                {page0.items.map((post, i) => (
                                    <PostItem
                                        {...post}
                                        key={i}
                                        isAdmin={isAdmin}
                                        setModalUpdateActive={
                                            setModalUpdateActive
                                        }
                                        setUpdatePostId={setUpdatePostId}
                                    />
                                ))}
                            </div>
                        </div>
                    ) : status === 'successful' ? (
                        <div>Постов пока нет</div>
                    ) : null}
                </>
            </div>

            <ModalCreate
                active={modalCreateActive}
                setActive={setModalCreateActive}
                groupId={groupId}
            />

            <ModalUpdate
                active={modalUpdateActive}
                setActive={setModalUpdateActive}
                groupId={groupId}
                postId={updatePostId}
            />
        </div>
    );
};
