jQuery(document).ready($ => {
    const juriRoot = Joomla.getOptions('system.paths').root;
    const $container = $('.course-review-container');
    const courseId = $container.data('course-id');
    let currentUrl = juriRoot + `/index.php?option=com_guru&view=gurureview&course_id=${courseId}&tmpl=component`;

    loadReview($container);
    initReviewDropdown($container);

    function initReviewDropdown($container)
    {
        $(window).on('click', e => {
            $('.review-report.show').removeClass('show');

            const $el = $(e.target);
            if (!$el.hasClass('review-report-btn')) {;
                return;
            }

            const $report = $el.parent();
            $report.addClass('show');
        })
    }

    function loading(state) {
        if (state) {
            $('.review-loader').addClass('active');
        } else {
            $('.review-loader').removeClass('active');
        }
    }

    function loadReview($container, url) {
        currentUrl = url ? url : currentUrl;

        return new Promise((resolve, reject) => {
            $.ajax({
                url: currentUrl,
                cache: true,
            }).done(html => {
                const $reviewWrapper = $(html).find('.review-wrapper');
                $container.find('.review-wrapper').html($reviewWrapper.html());

                initRatingFilter($container);
                initPagination($container);
                initComposer($container);
                initReport($container);

                resolve();
            }).fail(error => {
                reject(error);
            })
        });

    }

    function initReport($container) {
        if (!$container.find('.review-report').length) {
            return;
        }

        const courseId = $container.data('course-id');

        $container.find('.review-report').each((idx, el) => {
            const $item = $(el);
            const $btn = $item.find('.review-report-btn');
            const reviewId = $btn.data('review-id');

            $item.find('.report-type-list .report-type').on('click', e => {
                const $el = $(e.currentTarget);
                const url = juriRoot + `/index.php?option=com_guru&view=gurureview&task=reportReview`;
                const token = Joomla.getOptions('csrf.token');
                const data = {
                    courseId,
                    reviewId,
                    reportType: $el.data('type'),
                };
                data[token] = 1;

                $.ajax({
                    method: 'post',
                    url: url,
                    data,
                }).always(() => {
                    alert(Joomla.JText._('GURU_REVIEW_REPORT_THANK'));
                })
            })
        })
    }

    function initPagination($container) {
        $container.find('.pagination-review a').each((idx, el) => {
            const $el = $(el);
            const href = $el.attr('href');

            $el.attr('href', 'javascript:;');

            if (href.indexOf('#') === 0) {
                return;
            }

            $el.on('click', async () => {
                loading(true);
                await loadReview($container, href);
                loading(false);

                $('html').stop().animate(
                    {
                        scrollTop: $('.review-heading').offset().top,
                    },
                    100,
                );
            })
        })
    }

    function initRatingFilter($container) {
        const courseId = $container.data('course-id');
        const $filter = $container.find('.rating-filter select');
        $filter.on('change', async event => {
            const rating = event.currentTarget.value;
            const url = juriRoot + `/index.php?option=com_guru&view=gurureview&course_id=${courseId}&rating=${rating}&tmpl=component`;

            loading(true);
            await loadReview($container, url);
            loading(false);
        })
    }

    function initComposer($container) {
        const courseId = $container.data('course-id');

        if (!$container.find('.review-composer').length) {
            return;
        }

        $container.find('.review-submit').on('click', () => {
            const rating = $container.find('input[name="rating"]:checked').val();
            const content = $container.find('.content-composer textarea').val().trim();
            if (!content) {
                return alert(Joomla.JText._('GURU_YOUR_REVIEW_CONTENT_IS_EMPTY'));
            }

            const url = juriRoot + `/index.php?option=com_guru&view=gurureview&task=doReview`;
            const data = {
                course_id: courseId,
                rating,
                content,
            };

            const token = Joomla.getOptions('csrf.token');
            data[token] = 1;

            loading(true);

            $.ajax({
                method: 'post',
                url,
                data,
                dataType: 'json',
            }).done(res => {
                if (res.error) {
                    loading(false);
                    return alert(res.error);
                }
            }).always(async () => {
                await loadReview($container)
                loading(false);
            })
        })

        $container.find('.review-edit').on('click', () => {
            $container.find('.current-user-review').hide();
            $container.find('.review-composer').show();
        })

        $container.find('.review-cancel').on('click', () => {
            $container.find('.current-user-review').show();
            $container.find('.review-composer').hide();
        })

        $container.find('.review-delete').on('click', () => {
            const ok = confirm('are you sure?');

            if (!ok) {
                return;
            }

            const url = juriRoot + `/index.php?option=com_guru&view=gurureview&task=deleteReview`;
            const token = Joomla.getOptions('csrf.token');
            const data = {
                course_id: courseId,
            };
            data[token] = 1;

            loading(true);
            $.ajax({
                method: 'post',
                url,
                data,
                dataType: 'json',
            }).done(async res => {
                if (res.error) {
                    loading(false);
                    return alert(res.error);
                }

                await loadReview($container);
                loading(false);

                $('html').stop().animate(
                    {
                        scrollTop: $('.review-heading').offset().top,
                    },
                    100,
                );
            }).fail(error => {
                alert('error');
            })
        })
    }
})