import { PropsWithChildren, createContext, useContext, useState } from 'react';
import { UseQueryResult, useQuery } from '@tanstack/react-query';
import { toast } from 'react-toastify';
import { errorMessageFormatter } from '@/utils';
import { useTranslation } from 'next-i18next';
import { useRouter } from 'next/router';
import { AxiosErrorResponse, StudyGroup, StudyGroupMember, StudyGroupTask } from '@/types';
import { getStudyGroupById, getStudyGroupMember, getStudyGroupTaskById } from '@/services/study-group';

interface StudyGroupProps {
    studyGroupMember: UseQueryResult<StudyGroupMember>;
    studyGroup: UseQueryResult<StudyGroup>;
    studyGroupTask: UseQueryResult<StudyGroupTask>;
    studyGroupId: string;
    studyGroupTaskId: string;
    setStudyGroupTaskId: (studyGroupTaskId: string) => void;
}

const StudyGroupContext = createContext<StudyGroupProps>({
    studyGroupMember: {} as UseQueryResult<StudyGroupMember>,
    studyGroup: {} as UseQueryResult<StudyGroup>,
    studyGroupTask: {} as UseQueryResult<StudyGroupTask>,
    studyGroupId: '',
    studyGroupTaskId: '',
    setStudyGroupTaskId: () => void 0,
});

interface StudyGroupProviderProps extends PropsWithChildren {}

export const StudyGroupProvider: React.FC<StudyGroupProviderProps> = ({ children }) => {
    const { t } = useTranslation(['study-group', 'common', 'messages', 'layout']);
    const [studyGroupTaskId, setStudyGroupTaskId] = useState<string>('');
    const router = useRouter();
    const { studyGroupId } = router.query;

    // Study Group Members
    const studyGroupMemberQuery = useQuery({
        queryKey: ['study-group-members', studyGroupId],
        enabled: !!studyGroupId,
        queryFn: async () => {
            const res = await getStudyGroupMember(studyGroupId as string);

            return res.data;
        },
    });

    // Study Group
    const studyGroupQuery = useQuery({
        queryKey: ['study-group', studyGroupId],
        enabled: !!studyGroupId,
        queryFn: async () => {
            const res = await getStudyGroupById(studyGroupId as string);

            return res.data;
        },
        onError: (error: AxiosErrorResponse & Error) => {
            toast.error(t(errorMessageFormatter(error)));
        },
    });

    // Task
    const studyGroupTaskQuery = useQuery({
        queryKey: ['study-group-task', studyGroupTaskId],
        enabled: !!studyGroupTaskId,
        queryFn: async () => {
            const res = await getStudyGroupTaskById(studyGroupTaskId as string);

            return res.data;
        },
        onError: (error: AxiosErrorResponse & Error) => {
            toast.error(t(errorMessageFormatter(error)));
        },
    });

    return (
        <StudyGroupContext.Provider
            value={{
                studyGroupMember: studyGroupMemberQuery,
                studyGroup: studyGroupQuery,
                studyGroupTask: studyGroupTaskQuery,
                studyGroupId: studyGroupId as string,
                studyGroupTaskId,
                setStudyGroupTaskId,
            }}
        >
            {children}
        </StudyGroupContext.Provider>
    );
};

export const useStudyGroupContext = () => {
    const context = useContext(StudyGroupContext);

    if (!context) {
        throw new Error('useStudyGroupContext must be used within StudyGroupProvider');
    }

    return context;
};
