import * as path from 'path';

import stylesConfig from '../../../styleNames';
import { createElement } from '../../../utils';

type ConfigControlButtonProps = {
  type: 'collapseAll' | 'edit' | 'add' | 'delete';
  parent: HTMLElement;
  onClick: (e: MouseEvent) => void;
};

// создаёт кнопки изменения конфига и кнопку "свернуть всё"
export const createConfigControlButton = ({
  type,
  parent,
  onClick,
}: ConfigControlButtonProps) => {
  const svg = createElement('img', {
    src: path.join(__dirname, '../../../..', `assets/${type}.svg`),
    alt: type,
  });

  return createElement(
    'button',
    {
      className: (type !== 'collapseAll' ? stylesConfig.devButton + ' ' : '').concat(
        stylesConfig[`${type}Button` as keyof typeof stylesConfig],
      ),
      onclick: onClick,
    },
    parent,
    svg,
  );
};

export const showInvalidInputs = (wrapper: HTMLElement) => {
  const highestNode = wrapper.querySelector(`.${stylesConfig.highestNode}`);

  highestNode
    ?.querySelectorAll('details[open]')
    .forEach((details) => ((details as HTMLDetailsElement).open = false));

  highestNode?.querySelectorAll(':invalid').forEach((node) => {
    let parent = node.parentElement;
    while (parent && parent !== highestNode) {
      if (parent.nodeName === 'DETAILS') {
        (parent as HTMLDetailsElement).open = true;
      }

      parent = parent.parentElement;
    }
  });
};

// модальное окно, появляется при нажатии на кнопку удаления поля
export const createSubmitDeleteModal = (
  configHTML: HTMLElement,
  deletingNode: HTMLElement,
) => {
  const layout = createElement(
    'div',
    {
      className: stylesConfig.modalLayout,
      onclick: (e) => {
        if (!e.composedPath().includes(modalSubmit)) {
          layout.remove();
        }
      },
    },
    configHTML,
  );

  const modalSubmit = createElement(
    'div',
    { className: stylesConfig.modalSubmitDelete },
    layout,
  );
  createElement(
    'p',
    {
      innerHTML: `Подтвердите удаление.${
        deletingNode.nodeName === 'DETAILS'
          ? '<br />Также удалятся все дочерние поля.'
          : ''
      }${
        deletingNode.parentElement?.children.length === 2 &&
        !deletingNode.parentElement?.classList.contains(stylesConfig.highestNode)
          ? '<br />Пустые разделы будут удалены.'
          : ''
      }`,
      className: stylesConfig.modalText,
    },
    modalSubmit,
  );

  const buttonsContainer = createElement(
    'div',
    { className: stylesConfig.modalButtons },
    modalSubmit,
  );

  createElement(
    'button',
    {
      onclick: () => {
        configHTML.dataset.isChanged = 'true';
        let parent = deletingNode.parentElement;
        const highestNode = document.querySelector(`.${stylesConfig.highestNode}`);
        deletingNode.remove();

        while (parent && parent !== highestNode && parent.children.length === 1) {
          const tmp = parent.parentElement;
          parent.remove();
          parent = tmp;
        }
        layout.remove();
      },
      innerHTML: 'Удалить',
    },
    buttonsContainer,
  );

  createElement(
    'button',
    { onclick: () => layout.remove(), innerHTML: 'Отменить' },
    buttonsContainer,
  );
};

export const sortComparator = (textA: string | null, textB: string | null) => {
  if (textA && textB) {
    if (textA > textB) {
      return 1;
    } else if (textA < textB) {
      return -1;
    }
  }

  return 0;
};
