import { useEffect, useRef } from 'react';
import { useFormContext } from 'react-hook-form';

import { mapValues } from 'lodash-es';
import { useModal } from '@material-hu/hooks/useModal';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';

import {
  SIDEBAR_WIDTH,
  TASKS_ICONS,
  TITLE_MAX_LENGTH,
  TITLE_MIN_LENGTH,
} from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import { validateTask } from 'src/pages/dashboard/Learning/Courses/New/utils';
import {
  type Selected,
  type Task,
  TaskTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import BasicModal from 'src/components/BasicModal';
import FormClickableTextField from 'src/components/FormInputs/FormClickableTextField';

import TaskBlank from './TaskBlank';
import TaskNew from './TaskNew';
import TaskQuestionnaire from './TaskQuestionnaire';
import TaskReading from './TaskReading';
import TaskScorm from './TaskScorm';
import TaskVideo from './TaskVideo';

export type ContentTaskProps = {
  disabled?: boolean;
  selected: Selected;
  onSave?: (task: Task) => void;
  onCancel?: (task: Task) => void;
  onSelectType?: () => void;
};

export const ContentTask = ({
  disabled = false,
  selected,
  onSave = () => null,
  onCancel = () => null,
  onSelectType = () => null,
}: ContentTaskProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { watch } = useFormContext();

  const taskName = newCourseFields.content.modules.tasks.detail(
    selected.module,
    selected.task,
  );

  const task = watch(taskName);

  const handleCreateTask = () => onSave(task);

  const containerRef = useRef<HTMLDivElement>(null);

  // Scroll to top to restart scroll position
  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.scrollTop = 0;
    }
  }, [task?.type]);

  const { Icon, color } = TASKS_ICONS[task?.type as keyof typeof TASKS_ICONS];

  const taskByType = {
    [TaskTypes.NEW]: (
      <TaskNew
        key={`${selected.module}-${selected.task}-new`}
        selected={selected}
        disabled={disabled}
        onSelectType={onSelectType}
      />
    ),
    [TaskTypes.BLANK]: (
      <TaskBlank
        key={`${selected.module}-${selected.task}-blank`}
        selected={selected}
        disabled={disabled}
      />
    ),
    [TaskTypes.QUESTIONNAIRE]: (
      <TaskQuestionnaire
        key={`${selected.module}-${selected.task}-questionnaire`}
        selected={selected}
        disabled={disabled}
      />
    ),
    [TaskTypes.VIDEO]: (
      <TaskVideo
        key={`${selected.module}-${selected.task}-video`}
        selected={selected}
        disabled={disabled}
      />
    ),
    [TaskTypes.READING]: (
      <TaskReading
        key={`${selected.module}-${selected.task}-reading`}
        selected={selected}
        disabled={disabled}
      />
    ),
    [TaskTypes.SCORM]: (
      <TaskScorm
        key={`${selected.module}-${selected.task}-scorm`}
        selected={selected}
        disabled={disabled}
      />
    ),
  };

  const isDefaultTitle = task?.title === t('course.lesson.title_placeholder');

  const {
    modal: confirmationModal,
    showModal: showConfirmationModal,
    closeModal: closeConfirmationModal,
  } = useModal(() => (
    <BasicModal
      Icon={null}
      title={t('course.lesson.discard_lesson.modal_title')}
      body={t('course.lesson.discard_lesson.modal_description')}
      buttonColor="primary"
      primaryButtonProps={{
        children: t('general:keep_editing'),
        onClick: closeConfirmationModal,
      }}
      secondaryButtonProps={{
        children: t('general:discard'),
        onClick: () => {
          onCancel(task);
          closeConfirmationModal();
        },
      }}
    />
  ));

  return (
    <Stack
      ref={containerRef}
      sx={{
        p: 3,
        gap: 3,
        width: '100%',
        overflow: 'auto',
      }}
    >
      {confirmationModal}
      <Stack
        className="maxWidth"
        sx={{ gap: 4, maxWidth: '900px' }}
      >
        <Stack sx={{ width: '100%' }}>
          <Stack sx={{ alignItems: 'center', flexDirection: 'row', gap: 1 }}>
            <Icon
              sx={{
                color,
                fontSize: '33px',
                pb: '4px',
                mb: '20px',
              }}
            />
            <FormClickableTextField
              key={newCourseFields.content.modules.tasks.title(
                selected.module,
                selected.task,
              )}
              name={newCourseFields.content.modules.tasks.title(
                selected.module,
                selected.task,
              )}
              disabled={disabled}
              resetOnEmptyBlur
              blurOnEnter
              valueAsPlaceholder={isDefaultTitle}
              showCounter
              maxLength={TITLE_MAX_LENGTH}
              maxLengthError={t('course.title_max_length', {
                count: TITLE_MAX_LENGTH,
              })}
              minLength={TITLE_MIN_LENGTH}
              minLengthError={t('course.title_min_length', {
                count: TITLE_MIN_LENGTH,
              })}
              inputProps={{
                sx: {
                  fontSize: '24px',
                  fontWeight: 700,
                  mt: -1,
                },
              }}
              typographyProps={{ variant: 'h5' }}
            />
          </Stack>
          <Divider />
        </Stack>
        {taskByType[task?.type as keyof typeof taskByType]}
      </Stack>
      {task?.type !== TaskTypes.NEW && (
        <Stack
          sx={{
            position: 'fixed',
            backgroundColor: '#F2F2F7',
            bottom: 0,
            left: 0,
            zIndex: 300,
            width: '100%',
          }}
        >
          <Stack
            className="maxWidth"
            sx={{ px: 3, py: 2 }}
          >
            <Stack
              sx={{
                maxWidth: '900px',
                ml: mapValues(SIDEBAR_WIDTH, width => width),
                width: '100%',
                flexDirection: 'row',
                justifyContent: 'space-between',
              }}
            >
              <Button
                variant="text"
                onClick={showConfirmationModal}
              >
                {t('course.lesson.discard_lesson.button')}
              </Button>
              <Button
                variant="contained"
                onClick={handleCreateTask}
                disabled={!validateTask(task)}
              >
                {t('general:save')}
              </Button>
            </Stack>
          </Stack>
        </Stack>
      )}
    </Stack>
  );
};

export default ContentTask;
