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

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

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getInternalId } from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import { getDuplicateTitle } from 'src/pages/dashboard/Learning/Courses/New/utils';
import { coursesRoutes } from 'src/pages/dashboard/Learning/Courses/routes';
import {
  CreateQuestionModes,
  type Question as QuestionType,
  type Selected,
  type StepsTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import DeleteQuestionModal from './DeleteQuestionModal';
import Question from './Question';
import QuestionActions from './QuestionActions';
import QuestionScore from './QuestionScore';
import TotalScore from './TotalScore';
import { useCreateQuestionDrawerConfig } from './useCreateQuestionDrawerConfig';

export type QuestionsProps = {
  questionCount: number;
  disabled?: boolean;
  selected: Selected;
  questions: QuestionType[];
  onCreate?: (index: number, values: QuestionType) => void;
  onEdit?: (index: number, values: QuestionType) => void;
  onDuplicate?: (index: number, values: QuestionType) => void;
  onMove?: (from: number, to: number) => void;
  onDelete?: (index: number) => void;
};

const Questions = ({
  questionCount,
  disabled = false,
  selected,
  questions,
  onCreate = () => null,
  onEdit = () => null,
  onDuplicate = () => null,
  onMove = () => null,
  onDelete = () => null,
}: QuestionsProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { getValues, control } = useFormContext<StepsTypes>();
  const HuGoThemeProvider = useHuGoTheme();
  const taskName = newCourseFields.content.modules.tasks;

  const [taskTag, isCourseStarted] = useWatch({
    name: [
      taskName.tag(selected.module, selected.task),
      'basicInformation.isCourseStarted',
    ],
    control,
  });

  const isEdit = !!useMatch(coursesRoutes.editCourse());
  const editDisabled = isEdit && !!taskTag && isCourseStarted;

  const { showModal: showDeleteQuestionModal, modal: deleteQuestionModal } =
    useModal(DeleteQuestionModal, { fullWidth: true, maxWidth: 'sm' });

  const { showDrawer: showCreateQuestionDrawer, drawer: createQuestionDrawer } =
    useDrawerV2<{
      index: number;
      defaultValues: QuestionType;
      onSubmitValues: (index: number, values: QuestionType) => void;
    }>(args =>
      useCreateQuestionDrawerConfig({
        ...args,
        disabled,
        selected,
        questionCount,
        editDisabled,
      }),
    );

  const edit = (
    index: number,
    onSubmit: (index: number, values: QuestionType) => void,
    mode: CreateQuestionModes = CreateQuestionModes.CREATE,
    originalIndex?: number,
  ) => {
    let defaultValues: QuestionType | undefined;

    if (mode !== CreateQuestionModes.CREATE) {
      if (originalIndex == null) return;

      const questionDetail = taskName.form.questions.detail(
        selected.module,
        selected.task,
        originalIndex,
      );
      const question: QuestionType = getValues(questionDetail);

      defaultValues =
        mode === CreateQuestionModes.EDIT
          ? question
          : {
              ...question,
              id: getInternalId(questionCount + 1),
              title: getDuplicateTitle(question.title),
            };
    }

    showCreateQuestionDrawer({
      index,
      defaultValues,
      onSubmitValues: onSubmit,
    });
  };

  const handleCreate = () => edit(questions.length, onCreate);

  const handleEdit = (index: number) => () => {
    edit(index, onEdit, CreateQuestionModes.EDIT, index);
  };

  const handleDuplicate = (index: number) => () => {
    edit(index + 1, onDuplicate, CreateQuestionModes.DUPLICATE, index);
  };

  const handleMoveUp = (index: number) => () => onMove(index, index - 1);
  const handleMoveDown = (index: number) => () => onMove(index, index + 1);

  const handleDelete = (index: number) => () => {
    showDeleteQuestionModal({
      onConfirm: () => onDelete(index),
      questionName: questions[index].title,
    });
  };

  return (
    <Stack sx={{ gap: 2 }}>
      <HuGoThemeProvider>{createQuestionDrawer}</HuGoThemeProvider>
      {deleteQuestionModal}
      {questions?.length > 0 && (
        <>
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
            <Typography variant="h5">{t('general:questions')}</Typography>
            <Chip
              label={questions.length}
              color="primary"
              size="small"
              sx={{ fontSize: '11px', p: 0 }}
            />
          </Stack>
          {questions.map((question, index) => (
            <Stack
              key={question.id}
              sx={{ gap: 3, flexDirection: 'row', width: '100%' }}
            >
              <QuestionActions
                disabled={disabled}
                index={index}
                length={questions.length}
                onMoveUp={!editDisabled ? handleMoveUp(index) : undefined}
                onMoveDown={!editDisabled ? handleMoveDown(index) : undefined}
                onDuplicate={!editDisabled ? handleDuplicate(index) : undefined}
                onDelete={!editDisabled ? handleDelete(index) : undefined}
              />
              <Question
                disabled={disabled}
                selected={selected}
                index={index}
                onClick={handleEdit(index)}
              />
              <QuestionScore
                disabled={disabled}
                selected={selected}
                index={index}
              />
            </Stack>
          ))}
          <TotalScore selected={selected} />
        </>
      )}
      {!editDisabled && (
        <Button
          id="create-question-button"
          variant="contained"
          onClick={handleCreate}
          disabled={disabled}
        >
          {t('common.create_question')}
        </Button>
      )}
    </Stack>
  );
};

export default Questions;
