import { GetServerSideProps, NextPage } from 'next';
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import Layout from '@/components/layouts';
import { BasePageProps } from '@/types';
import { authentication } from '@/utils/authentication';
import localeLinkGenerator from '@/utils/localeLinkGenerator';
import { Alert, Carousel } from 'antd';
import { useQuery } from '@tanstack/react-query';
import { getNotice, getSupport, getUncommentedTasks } from '@/services/data';
import HtmlParser from '@/components/HtmlParser';

const Dashboard: NextPage<BasePageProps> = ({ member }) => {
    const { t } = useTranslation(['dashboard', 'layout', 'common', 'messages']);

    const { data } = useQuery({
        queryKey: ['contact-information'],
        queryFn: async () => {
            const response = await getSupport();

            return response.data;
        },
    });

    const { data: noticeData } = useQuery({
        queryKey: ['notice'],
        queryFn: async () => {
            const response = await getNotice();

            return response.data;
        },
    });

    const { data: uncommentData } = useQuery({
        queryKey: ['uncommented-tasks'],
        queryFn: async () => {
            const response = await getUncommentedTasks();

            return response.data;
        },
    });

    const seoConfig = {
        title: t('dashboard'),
    };

    const breadCrumbItems = [
        {
            label: t('layout:dashboard'),
            path: '/',
        },
    ];

    const email = data?.email ?? '';
    const contactNumber = data?.contactNumber ?? '';

    return (
        <Layout member={member} breadCrumbItems={breadCrumbItems} activeMenu={['dashboard']} seoConfig={seoConfig}>
            <div className='flex flex-col gap-4 mb-4 w-full'>
                {/* Contact Support Information */}
                <div className='w-full'>
                    <Alert
                        message={t('contact-support')}
                        description={
                            <div>
                                {t('you-may-contact-support-via-the-details-below-if-necessary')}
                                <br />
                                <strong>{t('common:email')}:</strong> <a href={`mailto:${email}`}>{email}</a>
                                <br />
                                <strong>{t('common:contact-number')}:</strong> <a href={`tel:${contactNumber}`}>{contactNumber}</a>
                            </div>
                        }
                        type="info"
                        showIcon
                        style={{ backgroundColor: '#f0f5ff', border: '1px solid #adc6ff', borderRadius: '5px' }}
                    />
                </div>
                {/* Today Task */}
                <div className='w-full'>
                    <Alert
                        message={t('uncommented-tasks')}
                        description={
                            <div>
                                {t('you-have-not-commented-on-study-group-below')}
                                <br />
                                {
                                    uncommentData?.map((task: any, index: number) => (
                                        <div key={index}>
                                            {index + 1}. <a href={`/study-group/${task.studyGroup.id}`}>{task.studyGroup.name}</a>
                                        </div>
                                    ))
                                }
                            </div>
                        }
                        type="warning"
                        style={{ borderRadius: '5px' }}
                    />
                </div>
            </div>
            <h2>Notice</h2>
            <Carousel autoplay dotPosition="bottom">
                {noticeData &&
                    noticeData.length > 0 &&
                    noticeData[0].jsonValue.length > 0 &&
                    noticeData[0].jsonValue.map((item: any, index: number) => {
                        if (item.image) {
                            return (
                                <div key={index} className="!flex flex-col sm:flex-row w-full">
                                    <img
                                        src={item.image}
                                        alt={'Notice'}
                                        className="object-contain bg-transparent w-auto h-auto aspect-square sm:max-w-[400px] max-h-[400px]"
                                    />
                                    <div className="!flex justify-center items-center w-full bg-red-100 py-4 sm:h-[400px] p-8">
                                        <HtmlParser html={item.description} />
                                    </div>
                                </div>
                            );
                        } else {
                            return (
                                <div key={index} className="!flex justify-center items-center bg-red-100 h-auto min-h-[400px]">
                                    <HtmlParser html={item.description} />
                                </div>
                            );
                        }
                    })}
            </Carousel>
        </Layout>
    );
};

export const getServerSideProps: GetServerSideProps = async ({ req, locale, resolvedUrl }) => {
    try {
        const authResponse = await authentication(req);

        return {
            props: {
                member: authResponse,
                ...(await serverSideTranslations(locale as string, ['dashboard', 'layout', 'common', 'messages', 'api-messages', 'my-profile'])),
            },
        };
    } catch (error: any) {
        if (error.response?.data?.unauthorized) {
            return {
                redirect: {
                    destination: localeLinkGenerator(locale, `/unauthorized`),
                    permanent: false,
                },
            };
        }

        return {
            redirect: {
                destination: localeLinkGenerator(locale, `/?redirect=/${resolvedUrl}`),
                permanent: false,
            },
        };
    }
};

export default Dashboard;
