import { type SyntheticEvent, useEffect, useMemo, useState } from 'react';
import {
  FormProvider,
  useFieldArray,
  useFormContext,
  useWatch,
} from 'react-hook-form';

import { uniqueId } from 'lodash-es';
import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import { ReviewQuestionType } from 'src/types/performance';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { validateRequiredStringRule } from 'src/utils/validation';

import FormCheckbox from 'src/components/FormInputs/FormCheckbox';
import FormRichEditor from 'src/components/FormInputs/FormRichEditor';
import FormSwitch from 'src/components/FormInputs/FormSwitch';
import FormTextField from 'src/components/FormInputs/FormTextField';

import TabsWrapper from '../components/TabsWrapper';
import { REVIEWS_BACKGROUND } from '../constants';
import { cleanPastedContent, getTypeTab } from '../utils';

import Options from './components/Options';
import { TEMPLATE_INSTRUCTIONS_MAX_LENGTH } from './constants';
import {
  getReviewQuestionTabs,
  isGoalOrCompetencies,
  shouldDisableResponseTypeChange,
} from './utils';

type Props = {
  name: string | 'goalQuestion';
  index?: number;
  unfocus?: () => void;
  isTemplateInUse?: boolean;
};

const QuestionEdition = ({
  name,
  index = 0,
  unfocus,
  isTemplateInUse,
}: Props) => {
  const { t } = useLokaliseTranslation('performance');
  const form = useFormContext();
  const { control, setValue } = form;

  const questionObject = useWatch({ control, name });

  const isGoalOrCompetenciesQuestion = isGoalOrCompetencies(name);
  const question = isGoalOrCompetenciesQuestion
    ? questionObject
    : questionObject[index];
  const questionName = isGoalOrCompetenciesQuestion ? name : `${name}.${index}`;

  const { type, hasAnswer, hasComment } = question || {};

  const disableResponseTypeChange = shouldDisableResponseTypeChange({
    questionFieldName: name,
    question: question ?? undefined,
    isTemplateInUse,
  });

  const [currentTabIndex, setCurrentTabIndex] = useState(() => {
    const tabIndex = getTypeTab(type);
    return tabIndex >= 0 ? tabIndex : 0;
  });

  const isQuestionInvalid = !hasAnswer && !hasComment;

  const {
    fields: possibleAnswers,
    append,
    remove: removeOption,
  } = useFieldArray({
    name: `${questionName}.possibleAnswers`,
    control,
  });

  const addNewOption = (
    i = possibleAnswers.length + 1,
    description = `${t('questions.answer')} ${i}`,
  ) => append({ value: description, id: uniqueId() });

  const tabs = useMemo(() => getReviewQuestionTabs(t), [t]);
  const currentTabType =
    tabs[currentTabIndex]?.type || ReviewQuestionType.RATING;

  useEffect(() => {
    if (hasAnswer) {
      setValue(`${questionName}.type`, currentTabType, { shouldDirty: false });
    } else {
      setValue(`${questionName}.type`, ReviewQuestionType.TEXT, {
        shouldDirty: false,
      });
    }
  }, [hasAnswer, currentTabType, setValue, questionName]);

  const handleTabChange = (_: SyntheticEvent, value: number) => {
    if (disableResponseTypeChange) return;
    setCurrentTabIndex(value);
    setValue(
      `${questionName}.type`,
      tabs[value]?.type || ReviewQuestionType.RATING,
      { shouldDirty: true },
    );
  };

  const handleHasCommentChange = (_: SyntheticEvent, checked: boolean) => {
    if (checked) {
      setValue(`${questionName}.commentRequired`, true);
    } else {
      setValue(`${questionName}.commentRequired`, false);
    }
  };

  return (
    <FormProvider {...form}>
      <Typography
        sx={{ mt: 2, ml: 1 }}
        variant="subtitle2"
      >
        {t('questions.question')}
      </Typography>
      <Stack
        sx={{
          my: 2,
          p: 2,
          backgroundColor: REVIEWS_BACKGROUND,
          borderRadius: 2,
        }}
      >
        <FormTextField
          name={`${questionName}.title`}
          label={t('templates.template_title')}
          inputProps={{ maxLength: 255 }}
          sx={{ backgroundColor: 'white' }}
          rules={{ validate: validateRequiredStringRule }}
          defaultValue={question?.title || ''}
        />
        <Typography
          variant="subtitle2"
          sx={{ my: 2 }}
        >
          {t('questions.description')}
        </Typography>
        <FormRichEditor
          simplifyEditor
          name={`${questionName}.description`}
          maxLength={TEMPLATE_INSTRUCTIONS_MAX_LENGTH}
          showCounter
          editorProps={{
            init: {
              paste_postprocess: (_, args: { node: HTMLElement }) => {
                cleanPastedContent(args.node);
              },
            },
          }}
        />
      </Stack>
      <Typography variant="subtitle2">{t('questions.answer')}</Typography>
      <Stack
        sx={{
          mt: 2,
          p: 2,
          backgroundColor: REVIEWS_BACKGROUND,
          borderRadius: 2,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Typography
            variant="body2"
            sx={{ maxWidth: '200px' }}
          >
            {t('templates.answer_subtitle')}
          </Typography>
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 1,
            }}
          >
            {hasAnswer && (
              <FormCheckbox
                name={`${questionName}.answerRequired`}
                label={t('questions.required')}
                typographyProps={{ fontSize: '13px' }}
              />
            )}
            <FormSwitch
              name={`${questionName}.hasAnswer`}
              label={t(hasAnswer ? 'general:yes' : 'general:no')}
              disabled={disableResponseTypeChange}
              formControlLabelProps={{
                componentsProps: { typography: { minWidth: 20 } },
              }}
            />
          </Stack>
        </Stack>
        {hasAnswer && (
          <>
            <TabsWrapper disabled={disableResponseTypeChange}>
              <RoundedTabs
                tabs={tabs}
                tabIndex={currentTabIndex}
                onChange={handleTabChange}
              />
            </TabsWrapper>
            <Box sx={{ mt: 3 }}>
              <Options
                isGoalQuestion={isGoalOrCompetenciesQuestion}
                name={name}
                questionIndex={index}
                options={possibleAnswers}
                remove={removeOption}
                addNewOption={addNewOption}
                type={currentTabType}
              />
            </Box>
          </>
        )}
      </Stack>
      <Stack
        sx={{
          mt: 2,
          p: 2,
          backgroundColor: REVIEWS_BACKGROUND,
          borderRadius: 2,
        }}
      >
        <Stack
          direction="row"
          alignItems="center"
          justifyContent="space-between"
        >
          <Stack
            direction="row"
            alignItems="center"
            spacing={1}
          >
            <Typography variant="body2">{t('questions.comments')}</Typography>
          </Stack>
          <Stack
            sx={{
              flexDirection: 'row',
              gap: 1,
            }}
          >
            {hasComment && (
              <FormCheckbox
                name={`${questionName}.commentRequired`}
                label={t('questions.required')}
                typographyProps={{ fontSize: '13px' }}
              />
            )}
            <FormSwitch
              name={`${questionName}.hasComment`}
              onChange={handleHasCommentChange}
              label={t(hasComment ? 'general:yes' : 'general:no')}
              formControlLabelProps={{
                componentsProps: { typography: { minWidth: 20 } },
              }}
            />
          </Stack>
        </Stack>
      </Stack>
      {index !== null && !isGoalOrCompetenciesQuestion && (
        <Button
          sx={{ ml: 'auto', mt: 2, py: 0.5 }}
          onClick={unfocus}
          variant="contained"
          disabled={isQuestionInvalid}
        >
          {t('general:done')}
        </Button>
      )}
    </FormProvider>
  );
};

export default QuestionEdition;
