import { useEffect, useMemo, useState } from 'react';
import { SecondaryButton } from '../../../components/button/SecondaryButton';
import { cn } from '../../../lib/cn';
import { useAppDispatch, useAppSelector } from '../../../redux/hooks';
import GroupsBlock from './GroupsBlock';
import { setMenuActivePage } from '../../../redux/slices/store';
import { fetchMyGroups } from '../../../redux/slices/groups';
import ModalCreate from './ModalCreate';
import ModalUpdate from './ModalUpdate';

export interface GroupUpdate {
    id: number;
    name: string;
    description: string;
}

const Groups = () => {
    const [modalActive, setModalActive] = useState<boolean>(false);
    const [modelUpdateActive, setModalUpdateActive] = useState<boolean>(false);
    const [updateGroup, setUpdateGroup] = useState<GroupUpdate>({
        id: 0,
        name: '',
        description: '',
    });

    const dispatch = useAppDispatch();

    // Берём группы из стора
    const groups = useAppSelector((store) => store.groups.groups);

    // Берём текущего пользователя
    const currentUserName = useAppSelector((store) => store.auth.username);

    useEffect(() => {
        dispatch(setMenuActivePage('groups'));
        dispatch(fetchMyGroups());
    }, [dispatch]);

    // Разделяем группы
    const { managedGroups, currentGroups, hiddenGroups } = useMemo(() => {
        if (!groups || !currentUserName) {
            return { managedGroups: [], currentGroups: [], hiddenGroups: [] };
        }

        const managed: typeof groups = [];
        const current: typeof groups = [];
        const hidden: typeof groups = []; // пока пустые, без логики

        groups.forEach((group) => {
            const me = group.members.find(
                (m) => m.username === currentUserName,
            );
            if (!me) return;

            if (me.role === 'Administrator') {
                managed.push(group);
            } else {
                current.push(group);
            }
        });

        return {
            managedGroups: managed,
            currentGroups: current,
            hiddenGroups: hidden,
        };
    }, [groups, currentUserName]);

    return (
        <div className="h-full w-[calc(100%+250px)] box-border p-[20px] pt-[20p]">
            <div className="h-full box-border">
                <div className="relative flex items-center mb-[20px]">
                    <div
                        className={cn(
                            'h-[50px] text-[40px] font-bold text-liquid-white flex items-center',
                        )}
                    >
                        Группы
                    </div>
                    <SecondaryButton
                        onClick={() => {
                            setModalActive(true);
                        }}
                        text="Создать группу"
                        className="absolute right-0"
                    />
                </div>

                <div className="bg-liquid-lighter h-[50px] mb-[20px]"></div>

                <GroupsBlock
                    className="mb-[20px]"
                    title="Управляемые"
                    groups={managedGroups}
                    setUpdateActive={setModalUpdateActive}
                    setUpdateGroup={setUpdateGroup}
                />
                <GroupsBlock
                    className="mb-[20px]"
                    title="Текущие"
                    groups={currentGroups}
                    setUpdateActive={setModalUpdateActive}
                    setUpdateGroup={setUpdateGroup}
                />
                <GroupsBlock
                    className="mb-[20px]"
                    title="Скрытые"
                    groups={hiddenGroups} // пока пусто
                    setUpdateActive={setModalUpdateActive}
                    setUpdateGroup={setUpdateGroup}
                />
            </div>

            <ModalCreate setActive={setModalActive} active={modalActive} />
            <ModalUpdate
                setActive={setModalUpdateActive}
                active={modelUpdateActive}
                groupId={updateGroup.id}
                groupName={updateGroup.name}
                groupDescription={updateGroup.description}
            />
        </div>
    );
};

export default Groups;
