import { useState } from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form';

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

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

import Configuration from './Configuration';
import Questions from './Questions';

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

export const TaskQuestionnaire = ({
  disabled = false,
  selected,
}: TaskQuestionnaireProps) => {
  const [questionCount, setQuestionCount] = useState(1);
  const { t } = useLokaliseTranslation(['learning', 'attachments']);
  const { control, setValue } = useFormContext<StepsTypes>();

  const taskName = newCourseFields.content.modules.tasks;
  const questionsName = taskName.form.questions.all(
    selected.module,
    selected.task,
  );

  const { fields, append, move, remove, insert } = useFieldArray({
    name: questionsName,
    control,
  });

  const questions = fields as Question[];

  const withoutConfiguration = isTextQuestions(questions);

  const isValidIndex = (index: number, withMaxLimit: boolean = true) =>
    index >= 0 && (withMaxLimit ? index < questions.length : true);

  const handleCreate = (_: unknown, values: Question) => {
    append(values);
    setQuestionCount(questionCount + 1);
  };

  const handleEdit = (index: number, values: Question) => {
    if (!isValidIndex(index)) return;

    const questionPath = taskName.form.questions.detail(
      selected.module,
      selected.task,
      index,
    );
    setValue(questionPath, values);
  };

  const handleDuplicate = (index: number, values: Question) => {
    if (!isValidIndex(index, false)) return;

    insert(index, values);
    setQuestionCount(questionCount + 1);
  };

  const handleMove = (from: number, to: number) =>
    isValidIndex(to) && move(from, to);

  const handleDelete = (index: number) => isValidIndex(index) && remove(index);

  return (
    <TaskLayout.Container>
      <TaskLayout.Description
        disabled={disabled}
        selected={selected}
      />
      <TaskLayout.Content>
        {fields.length <= 0 && (
          <Stack
            sx={{
              py: 3,
              px: 2,
              gap: 0.5,
              flexDirection: 'column',
              justifyContent: 'flex-start',
              alignItems: 'center',
              border: '1px dashed #9E9E9E',
              borderRadius: '16px',
              textAlign: 'center',
            }}
          >
            <InfoIcon sx={{ fontSize: '40px', color: '#616161' }} />
            <Typography variant="h6">
              {t('course.lesson.questionnaire_info_title')}
            </Typography>
            <Typography variant="body1">
              {t('course.lesson.questionnaire_info_description')}
            </Typography>
          </Stack>
        )}
        <Questions
          disabled={disabled}
          selected={selected}
          questions={questions}
          onCreate={handleCreate}
          onEdit={handleEdit}
          onDuplicate={handleDuplicate}
          onMove={handleMove}
          onDelete={handleDelete}
          questionCount={questionCount}
        />
        <Configuration
          disabled={disabled || withoutConfiguration}
          selected={selected}
          info={
            withoutConfiguration
              ? t('common.alert_disabled_configuration')
              : undefined
          }
        />
      </TaskLayout.Content>
    </TaskLayout.Container>
  );
};

export default TaskQuestionnaire;
