import { useFormContext } from 'react-hook-form';
import { useMatch } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import FormRadioCustomGroup from '@material-hu/components/deprecated/FormRadioCustomGroup';

import { STEPPER_HEIGHT } from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import { coursesRoutes } from 'src/pages/dashboard/Learning/Courses/routes';
import {
  AudienceTypes,
  CourseTypes,
  DeadlineTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import FormSegmentation, {
  type FormSegmentationValue,
} from 'src/components/FormInputs/FormSegmentation';
import FormSelect from 'src/components/FormInputs/FormSelect';
import FormTextField from 'src/components/FormInputs/FormTextField';

import Card from './Card';
import CertificateModal from './CertificateModal';
import { ConfigurationInstructor } from './ConfigurationInstructor';
import ConfigurationNotifications from './ConfigurationNotifications';
import Layout from './Layout';
import SatisfactionSurveyModal from './SatisfactionSurveyModal';
import Switch from './Switch';

export type ConfigurationProps = {
  disabled?: boolean;
};

const DEFAULT_AUTOCOMPLETE_USERS = 5;

export const Configuration = ({ disabled = false }: ConfigurationProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { watch, getValues } = useFormContext();

  const isEdit = !!useMatch(coursesRoutes.editCourse());

  const deadline = watch(newCourseFields.configuration.deadline());

  const {
    modal: satisfactionSurveyModal,
    showModal: showSatisfactionSurveyModal,
    closeModal: closeSatisfactionSurveyModal,
  } = useModal(
    () => <SatisfactionSurveyModal onClose={closeSatisfactionSurveyModal} />,
    {
      maxWidth: 'xs',
      fullWidth: true,
    },
  );

  const { modal: certificateModal, showModal: showCertificateModal } = useModal(
    CertificateModal,
    {
      sx: {
        '& .MuiPaper-root': {
          maxWidth: '1017px',
          height: '681.55px',
          borderRadius: '0px',
        },
      },
    },
  );

  const typeOptions = [
    {
      value: CourseTypes.REQUIRED,
      label: t('course.required'),
      helperText: t('course.required_course'),
    },
    {
      value: CourseTypes.OPTIONAL,
      label: t('course.optional'),
      helperText: t('course.optional_course'),
    },
  ];

  const deadlineTypeOptions = [
    {
      value: DeadlineTypes.FROM_ASSIGNMENT,
      label: t('common.assigned_to'),
    },
  ];

  const handleChangeTypeSegmentation = (newValue: FormSegmentationValue) => {
    const courseName = getValues(newCourseFields.basicInformation.title());

    logEvent(LogEvents.COURSE_AUDIENCE_UPDATED, {
      courseName,
      audienceType: !newValue ? AudienceTypes.ALL : AudienceTypes.SEGMENTS,
    });
  };

  const handleSeeSatisfactionSurvey = () => showSatisfactionSurveyModal();
  const handleSeeCertificate = () => showCertificateModal();

  return (
    <>
      {satisfactionSurveyModal}
      {certificateModal}
      <Stack
        sx={{
          height: `calc(100% - ${STEPPER_HEIGHT})`,
          overflow: 'auto',
        }}
      >
        <Layout.Container>
          <Layout.Title>{t('common.configuration')}</Layout.Title>
          <Card.Container>
            <Card.Title id="new-course-configuration-type">
              {t('common.type')}
            </Card.Title>
            <Card.Content>
              <FormRadioCustomGroup
                aria-labelledby="new-course-configuration-type"
                name={newCourseFields.configuration.type()}
                options={typeOptions}
                labelProps={{ disabled }}
                column
              />
            </Card.Content>
          </Card.Container>
          <Card.Container>
            <Card.Title>{t('common.content')}</Card.Title>
            <Card.Content>
              <Switch
                label={t('common.sequentiality')}
                helperText={t('common.sequentialy_description')}
                disabled={disabled}
                name={newCourseFields.configuration.sequentiality()}
              />
              <Stack sx={{ gap: 2, width: '100%' }}>
                <Switch
                  label={t('common.auto_progress_update')}
                  helperText={t('common.auto_progress_update_description')}
                  disabled={disabled}
                  name={newCourseFields.configuration.refreshFinishedCourseUsers()}
                />
                <Switch
                  label={t('common.deadline')}
                  helperText={t('common.deadline_description')}
                  disabled={disabled}
                  name={newCourseFields.configuration.deadline()}
                />
                {deadline && (
                  <Stack
                    sx={{
                      gap: 2,
                      flexDirection: 'row',
                      justifyContent: 'flex-start',
                      alignItems: 'flex-start',
                      width: '100%',
                      '& .MuiFormControl-root': {
                        minWidth: '100px',
                        '& .MuiInputBase-root': {
                          height: '57px',
                        },
                      },
                      '& > p': { mt: 2 },
                    }}
                  >
                    <Typography variant="body1">
                      {t('general:finalize')}
                    </Typography>
                    <FormTextField
                      type="number"
                      name={newCourseFields.configuration.deadlineDays()}
                      label={t('common.days')}
                      disabled={disabled}
                      required={isEdit}
                      positive
                      sx={{ width: '106px' }}
                    />
                    <FormSelect
                      label={t('general:from')}
                      options={deadlineTypeOptions}
                      name={newCourseFields.configuration.deadlineType()}
                    />
                  </Stack>
                )}
              </Stack>
              <Switch
                label={t('reports.type.surveys')}
                helperText={t('reports.surveys_description')}
                disabled={disabled}
                name={newCourseFields.configuration.hasSurvey()}
                secondaryAction={{
                  onClick: handleSeeSatisfactionSurvey,
                  label: t('common.view_survey_model'),
                }}
              />
            </Card.Content>
          </Card.Container>
          <ConfigurationInstructor disabled={disabled} />
          <Card.Container>
            <Card.Title>{t('common.target_audience')}</Card.Title>
            <Card.Content>
              <FormSegmentation
                name={newCourseFields.configuration.segmentation()}
                segmentationErrorMessage={t(
                  'common.target_audience_description',
                )}
                showLabel={false}
                accordionSummaryProps={{
                  sx: { backgroundColor: '#F8F9FA' },
                }}
                radioProps={{
                  sx: {
                    '&.Mui-checked': {
                      color: theme => theme.palette.humand?.main,
                    },
                  },
                }}
                autoCompleteDefaultSearchOptions={{
                  enableEmptyQuery: true,
                  defaultLimit: DEFAULT_AUTOCOMPLETE_USERS,
                }}
                onChangeType={handleChangeTypeSegmentation}
              />
            </Card.Content>
          </Card.Container>
          <Card.Container>
            <Card.Title>{t('general:validations')}</Card.Title>
            <Card.Content>
              <Switch
                label={t('common.completion_certificate')}
                helperText={t('common.completion_certificate_description')}
                disabled={disabled}
                name={newCourseFields.configuration.issueCertificate()}
                secondaryAction={{
                  onClick: handleSeeCertificate,
                  label: t('common.view_certificate_model'),
                }}
              />
              <Switch
                label={t('course.signature.label')}
                helperText={t('course.signature.description')}
                disabled={disabled}
                name={newCourseFields.configuration.digitalSignature()}
              />
            </Card.Content>
          </Card.Container>
          <ConfigurationNotifications disabled={disabled} />
        </Layout.Container>
      </Stack>
    </>
  );
};

export default Configuration;
