import * as React from 'react';
import Modal from 'react-modal';
import { Category } from '@usercentrics/cmp-browser-sdk';

import { SettingItem } from './SettingItem';
import { AcceptAndCloseCTA } from '../AcceptAndCloseCTA';
import { useUsercentrics } from '../../contexts/UsercentricsContext';
import { DecisionsContext, selectAllDecisions } from '../../contexts/DecisionsContext';

type Props = {
  isOpen: boolean;
  onAcceptAll: VoidFunction;
  onCloseAndAcceptAll: VoidFunction;
  onSave: VoidFunction;
  onMoreInfo: VoidFunction;
  categories: Category[];
};

export const SettingsModal = ({
  categories,
  isOpen,
  onAcceptAll,
  onCloseAndAcceptAll,
  onSave,
  onMoreInfo,
}: Props): JSX.Element => {
  const { settingsLabels, showCloseAndAcceptAllButton } = useUsercentrics();
  const { decisions, updateDecision } = React.useContext(DecisionsContext);

  const isCategoryChecked = (category: Category) => {
    if (category.isEssential) {
      return true;
    }

    return selectAllDecisions(decisions)
      .filter(({ categorySlug }) => categorySlug === category.slug)
      .every(({ status }) => status);
  };

  const onChangeSetting = (event: React.ChangeEvent<HTMLInputElement>) => {
    const id = event.currentTarget.name;
    const allDecisions = selectAllDecisions(decisions).filter(({ categorySlug }) => categorySlug === id);
    const isAllSelected = allDecisions.every(({ status }) => status);

    allDecisions.forEach(({ serviceId }) => updateDecision(serviceId, !isAllSelected));
  };

  return (
    <Modal
      isOpen={isOpen}
      contentLabel="Warning about GDPR"
      overlayClassName="uc-modal uc-modal--overlay"
      className="uc-modal__content uc-relative uc-overflow-hidden uc-h-[440px] sm:uc-h-[560px]"
    >
      <div className="uc-absolute uc-top-0 uc-left-0 uc-w-full uc-h-full uc-overflow-auto uc-px-4 uc-pt-6 uc-pb-28 uc-md:pb-20 uc-text-kilamanjaro">
        {showCloseAndAcceptAllButton && <AcceptAndCloseCTA onClick={onCloseAndAcceptAll} />}
        <h3 className="uc-mb-4 uc-text-18 uc-font-medium">{settingsLabels?.secondLayer.title}</h3>
        <p className="uc-mb-4">{settingsLabels?.secondLayer.description}</p>

        {categories &&
          categories
            .filter((catg) => !catg.isHidden)
            .map((catg) => (
              <SettingItem
                key={catg.slug}
                data={catg}
                checked={isCategoryChecked(catg)}
                onChange={onChangeSetting}
                onMoreInfo={onMoreInfo}
              />
            ))}
      </div>

      <div className="uc-settings-modal__footer uc-bg-white uc-absolute uc-bottom-0 uc-right-0 uc-left-0 uc-w-full uc-p-4 uc-pb-2">
        <div className="uc-mb-2">
          <button onClick={onAcceptAll} className="uc-w-full uc-button uc-button--primary">
            {settingsLabels?.buttons.acceptAll}
          </button>
        </div>
        <div className="uc-flex uc-justify-center">
          <button className="uc-button" onClick={onSave}>
            {settingsLabels?.buttons.save}
          </button>
        </div>
      </div>
    </Modal>
  );
};
