/*!
 * Copyright (c) 2024 PLANKA Software GmbH
 * Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
 */

import { dequal } from 'dequal';
import React, { useCallback, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import TextareaAutosize from 'react-textarea-autosize';
import { Button, Form, TextArea } from 'semantic-ui-react';
import { useClickAwayListener } from '../../../lib/hooks';

import selectors from '../../../selectors';
import entryActions from '../../../entry-actions';
import { useForm, useNestedRef } from '../../../hooks';
import { focusEnd } from '../../../utils/element-helpers';
import { isModifierKeyPressed } from '../../../utils/event-helpers';

import styles from './Edit.module.scss';

const Edit = React.memo(({ commentId, onClose }) => {
  const selectCommentById = useMemo(() => selectors.makeSelectCommentById(), []);

  const comment = useSelector((state) => selectCommentById(state, commentId));

  const dispatch = useDispatch();
  const [t] = useTranslation();

  const defaultData = useMemo(
    () => ({
      text: comment.text,
    }),
    [comment.text],
  );

  const [data, handleFieldChange] = useForm(() => ({
    text: '',
    ...defaultData,
  }));

  const [textFieldRef, handleTextFieldRef] = useNestedRef();
  const [buttonRef, handleButtonRef] = useNestedRef();

  const submit = useCallback(() => {
    const cleanData = {
      ...data,
      text: data.text.trim(),
    };

    if (cleanData.text && !dequal(cleanData, defaultData)) {
      dispatch(entryActions.updateComment(commentId, cleanData));
    }

    onClose();
  }, [commentId, onClose, dispatch, defaultData, data]);

  const handleSubmit = useCallback(() => {
    submit();
  }, [submit]);

  const handleFieldKeyDown = useCallback(
    (event) => {
      if (event.key === 'Enter') {
        if (isModifierKeyPressed(event)) {
          submit();
        }
      } else if (event.key === 'Escape') {
        onClose();
      }
    },
    [onClose, submit],
  );

  const handleClickAwayCancel = useCallback(() => {
    textFieldRef.current.focus();
  }, [textFieldRef]);

  const clickAwayProps = useClickAwayListener(
    [textFieldRef, buttonRef],
    submit,
    handleClickAwayCancel,
  );

  useEffect(() => {
    focusEnd(textFieldRef.current);
  }, [textFieldRef]);

  return (
    <Form onSubmit={handleSubmit}>
      <TextArea
        {...clickAwayProps} // eslint-disable-line react/jsx-props-no-spreading
        ref={handleTextFieldRef}
        as={TextareaAutosize}
        name="text"
        value={data.text}
        maxLength={1048576}
        minRows={3}
        spellCheck={false}
        className={styles.field}
        onKeyDown={handleFieldKeyDown}
        onChange={handleFieldChange}
      />
      <div className={styles.controls}>
        <Button
          {...clickAwayProps} // eslint-disable-line react/jsx-props-no-spreading
          positive
          ref={handleButtonRef}
          content={t('action.save')}
        />
      </div>
    </Form>
  );
});

Edit.propTypes = {
  commentId: PropTypes.string.isRequired,
  onClose: PropTypes.func.isRequired,
};

export default Edit;
