import { toast } from 'react-toastify';
import { GetServerSideProps, NextPage } from 'next';
import { useTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useQuery } from '@tanstack/react-query';
import { Tabs } from 'antd';
import Credential from '@/components/my-profile/tabs/Credential';
import Profile from '@/components/my-profile/tabs/Profile';
import Layout from '@/components/layouts';
import { getMyProfile } from '@/services/my-profile';
import { AxiosErrorResponse, BasePageProps } from '@/types';
import { authentication } from '@/utils/authentication';
import { errorMessageFormatter } from '@/utils/errorFormatter';
import localeLinkGenerator from '@/utils/localeLinkGenerator';

const MyProfile: NextPage<BasePageProps> = ({ member }) => {
    const { t } = useTranslation(['my-profile', 'layout', 'common', 'messages']);
    const memberId = member.id;

    const breadCrumbItems = [
        {
            label: t('my-profile'),
            path: '/my-profile',
        },
    ];

    const memberQuery = useQuery({
        queryKey: ['member', memberId],
        keepPreviousData: true,
        queryFn: async () => {
            const res = await getMyProfile();
            return res.data;
        },
        onError: (error: AxiosErrorResponse & Error) => {
            toast.error(t(errorMessageFormatter(error)));
        },
    });

    const tabItems = [
        // Profile Tab
        {
            label: t('common:profile'),
            key: 'profile',
            children: <Profile memberQuery={memberQuery} />,
        },
        // Credential Tab
        {
            label: t('common:credential'),
            key: 'credential',
            children: <Credential memberId={memberId} memberQuery={memberQuery} />,
        },
    ];

    return (
        <Layout
            member={member}
            breadCrumbItems={breadCrumbItems}
            seoConfig={{
                title: t('my-profile'),
            }}
            withBackground
            activeMenu={['my-profile']}
        >
            <Tabs items={tabItems} />
        </Layout>
    );
};

export default MyProfile;

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

        return {
            props: {
                member: authResponse,
                ...(await serverSideTranslations(locale as string, ['member', 'my-profile', 'layout', 'common', 'messages', 'auth', 'api-messages'])),
            },
        };
    } 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,
            },
        };
    }
};
