import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import CircularProgress from '@material-hu/mui/CircularProgress';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';

import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useUnsavedWarning from 'src/hooks/useUnsavedWarning';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName, getInitials } from 'src/utils/userUtils';

import FormSign from 'src/components/FormInputs/HuFormSign';

import useIds from '../../hooks/useIds';
import useRoutes from '../../hooks/useRoutes';
import useGetPath from '../../paths/hooks/useGetPath';
import { PathStatus } from '../../paths/types';
import useCoursesTitle from '../hooks/useCoursesTitle';
import useGetCourse from '../hooks/useGetCourse';
import useSignCourse from '../hooks/useSignCourse';
import MainLayout from '../Tasks/components/MainLayout';
import { type SignCourseData } from '../types';

import CloseSignatureDialog from './CloseSignatureDialog';

const PendingSignature = () => {
  const { t } = useLokaliseTranslation(['learning', 'general']);
  const HugoThemeProvider = useHuGoTheme();
  const title = useCoursesTitle();
  const navigate = useNavigate();
  const routes = useRoutes();
  const { pathId, courseId } = useIds();
  const { user } = useAuth();

  const form = useForm({
    defaultValues: {
      signatureUrl: '',
    },
    mode: 'onChange',
  });

  const {
    handleSubmit,
    formState: { isValid },
  } = form;

  const { refetch: refetchPath } = useGetPath({ pathId });
  const { course, isLoading: isLoadingCourse } = useGetCourse({
    courseId,
    options: {
      onError: () => {
        navigate(routes.courses.list());
      },
    },
  });

  const signMutation = useSignCourse(courseId!);

  const submit = (values: SignCourseData) =>
    signMutation.mutate(values, {
      onSuccess: async () => {
        if (pathId) {
          const { data: updatedPath } = await refetchPath();

          if (updatedPath?.status === PathStatus.FINISHED) {
            return navigate(routes.paths.completion(pathId));
          }
        }

        navigate(routes.courses.completion(courseId!));
      },
    });

  const confirmClose = useUnsavedWarning(
    CloseSignatureDialog,
    !signMutation.isIdle,
  );

  const handleExit = () => navigate(routes.courses.detail(courseId!));

  const nextButton = {
    children: t('general:finish'),
    onClick: handleSubmit(submit),
    disabled: !isValid,
  };

  const previousButton = {
    children: t('general:exit'),
    onClick: handleExit,
  };

  return (
    <HugoThemeProvider>
      <Helmet>
        <title>{formatTitle(title)}</title>
      </Helmet>
      <FormProvider {...form}>
        {confirmClose.modal}
        <MainLayout
          course={course}
          loading={isLoadingCourse}
          nextButton={nextButton}
          previousButton={previousButton}
          hideSidebar
        >
          <Typography
            variant="globalS"
            fontWeight="fontWeightSemiBold"
          >
            {t('course.signature.pending_title')}
          </Typography>
          {isLoadingCourse && (
            <Stack
              sx={{
                width: '100%',
                justifyContent: 'center',
                alignItems: 'center',
                mt: 2,
              }}
            >
              <CircularProgress />
            </Stack>
          )}
          {!isLoadingCourse && (
            <CardContainer
              sx={{
                '& .MuiCardContent-root': {
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 2,
                },
                '& .MuiTypography-root': {
                  color: ({ palette }) => palette.new.text.neutral.default,
                },
              }}
            >
              <ListItem
                text={{ title: getFullName(user) }}
                sx={{ '& li': { p: 0 } }}
                avatar={{
                  src: user!.profilePicture ?? '',
                  text: getInitials(getFullName(user)),
                  alt: '',
                }}
              />
              <Typography variant="globalS">
                {t('course.signature.pending_description', {
                  course: course?.title,
                })}
              </Typography>
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
              >
                {t('course.signature.sign_next')}
              </Typography>
              <FormSign
                name="signatureUrl"
                rules={{ required: true }}
              />
            </CardContainer>
          )}
        </MainLayout>
      </FormProvider>
    </HugoThemeProvider>
  );
};

export default PendingSignature;
