import { useFormContext } from 'react-hook-form';

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

import { FormDropTypes } from '@material-hu/components/deprecated/FormDrop/types';

import TaskLayout from 'src/pages/dashboard/Learning/Courses/New/components/TaskLayout';
import { FILE_MAX_SIZE } from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import {
  ReadingTypes,
  type Selected,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormDrop from 'src/components/FormInputs/FormDrop';
import FormRichEditor from 'src/components/FormInputs/FormRichEditor';
import FormSelect from 'src/components/FormInputs/FormSelect';

export type TaskReadingProps = {
  disabled?: boolean;
  selected: Selected;
};

export const TaskReading = ({
  disabled = false,
  selected,
}: TaskReadingProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { watch } = useFormContext();

  const tasksName = newCourseFields.content.modules.tasks;

  const { body, type } = watch(
    tasksName.reading.all(selected.module, selected.task),
  );

  const typeOptions = Object.values(ReadingTypes).map(option => ({
    value: option,
    label: t(`course.reading.origin_type.${option.toLowerCase()}`),
  }));

  const inputByType = {
    [ReadingTypes.MANUAL]: (
      <Stack sx={{ gap: 1 }}>
        <FormRichEditor
          simplifyEditor
          disabled={disabled}
          name={tasksName.reading.body(selected.module, selected.task)}
          placeholder={t('general:write_answer')}
          editorProps={{
            value: body,
          }}
        />
        {(!body || body?.length <= 0) && (
          <Typography
            variant="caption"
            color="error"
            sx={{ fontWeight: 400 }}
          >
            {t('course.lesson.complete_pending')}
          </Typography>
        )}
      </Stack>
    ),
    [ReadingTypes.PDF]: (
      <FormDrop
        name={tasksName.reading.pdf.all(selected.module, selected.task)}
        type={FormDropTypes.PDF}
        maxSize={FILE_MAX_SIZE}
      />
    ),
  };

  return (
    <TaskLayout.Container>
      <TaskLayout.Description
        disabled={disabled}
        selected={selected}
      />
      <TaskLayout.Content>
        <FormSelect
          label={t('course.reading.origin_label')}
          options={typeOptions}
          name={tasksName.reading.type(selected.module, selected.task)}
          formControlProps={{ disabled, sx: { width: '100%' } }}
        />
        {inputByType[type as ReadingTypes]}
      </TaskLayout.Content>
      <TaskLayout.Attachments
        selected={selected}
        disabled={disabled}
      />
    </TaskLayout.Container>
  );
};

export default TaskReading;
