import { useMemberContext } from '@/providers/MemberContext';
import { getReplies, updateReply } from '@/services/study-group';
import { AxiosErrorResponse, Replies } from '@/types';
import { errorMessageFormatter } from '@/utils';
import { PlusOutlined } from '@ant-design/icons';
import { QueryClient, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Editor } from '@tinymce/tinymce-react';
import { Button, Form, FormInstance, Modal } from 'antd';
import { useTranslation } from 'next-i18next';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { v4 as uuid } from 'uuid';

interface ReplyModalProps {
    onReset: () => void;
    studyGroupTaskId: string;
    parentId: string;
}

const ReplyModal: React.FC<ReplyModalProps> = ({ onReset, studyGroupTaskId, parentId }) => {
    const { t, i18n } = useTranslation(['study-group-task', 'common']);
    const currentLocale = i18n.language;
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [updateReplyForm] = Form.useForm();
    const queryClient = useQueryClient();
    const { member } = useMemberContext();

    const getReplyQuery = useQuery({
        queryKey: ['replies', studyGroupTaskId, parentId],
        enabled: !!parentId,
        queryFn: async () => {
            const res = await getReplies(studyGroupTaskId, parentId as string);

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

    const ownReplyData = replyData?.find((reply: Replies) => reply.member?.id === member?.id && reply.parent_id === parentId);

    const updateReplyMutation = useMutation({
        mutationFn: async () => {
            const reply = updateReplyForm.getFieldsValue().reply;

            const response = await updateReply(studyGroupTaskId, reply, parentId);

            return response.data;
        },
        onSuccess: () => {
            queryClient.invalidateQueries(['replies']);
            onReset();
            setIsModalOpen(false);
        },
    });

    const onSubmitHandler = () => {
        updateReplyForm.validateFields().then(() => {
            toast.promise(updateReplyMutation.mutateAsync(), {
                pending: t('common:updating-reply'),
                success: t('common:reply-updated'),
                error: {
                    render({ data }) {
                        return t(errorMessageFormatter(data as AxiosErrorResponse));
                    },
                },
            });
        });
    };

    const onResetHandler = () => {
        onReset();
        setIsModalOpen(false);
    };

    useEffect(() => {
        if (parentId) {
            updateReplyForm.setFieldsValue({
                reply: ownReplyData?.comment,
            });
        } else {
            updateReplyForm.setFieldsValue({
                reply: '',
            });
        }
    }, [parentId]);

    return (
        <div className="mb-2 sm:mb-0">
            <Button icon={<PlusOutlined />} type="primary" onClick={() => setIsModalOpen(true)} className="w-full sm:w-fit">
                {ownReplyData?.comment && ownReplyData?.parent_id == parentId ? t('update-reply') : t('add-reply')}
            </Button>
            <Modal title={t('common:reply')} onCancel={onResetHandler} open={isModalOpen} footer={null} width={800}>
                <Form form={updateReplyForm}>
                    <Form.Item
                        name="reply"
                        trigger="onEditorChange"
                        className="w-full mb-4"
                        rules={[
                            {
                                required: true,
                                message: t('reply-is-required', { field: t('common:reply') }),
                            },
                        ]}
                    >
                        <Editor
                            id={uuid()}
                            tinymceScriptSrc={'/tinymce/js/tinymce/tinymce.min.js'}
                            init={{
                                height: 200,
                                menubar: '',
                                plugins: ['advlist', 'autolink', 'lists', 'link', 'searchreplace', 'code', 'preview', 'wordcount', 'table', 'paste'],
                                toolbar:
                                    'undo redo | blocks | ' +
                                    'bold italic forecolor | link | alignleft aligncenter ' +
                                    'alignright alignjustify | bullist numlist outdent indent | ' +
                                    'fullscreen',
                                block_formats: 'Paragraph=p;Header 2=h2;Header 3=h3;Header 4=h4',
                                content_style: 'body { font-family:var(--font-ubuntu); font-size:14px; text-align:left }',
                                language: currentLocale === 'en-GB' ? undefined : currentLocale,
                                language_url: currentLocale === 'en-GB' ? undefined : '/editor-translation/' + currentLocale + '.js',
                                promotion: false,
                                paste_data_images: true,
                                contextmenu: false,
                            }}
                        />
                    </Form.Item>
                    <div className="flex justify-end gap-x-3">
                        <Form.Item className="m-0">
                            <Button danger onClick={onResetHandler}>
                                {t('common:cancel')}
                            </Button>
                        </Form.Item>
                        <Form.Item className="m-0">
                            <Button type="primary" onClick={onSubmitHandler}>
                                {t('common:submit')}
                            </Button>
                        </Form.Item>
                    </div>
                </Form>
            </Modal>
        </div>
    );
};

export default ReplyModal;
