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

import TextField from '../../components/TextField';
import { useUsercentrics } from '../../contexts/UsercentricsContext';

import Content from './Content';

import { Navigation, getCategoriesBySearch, getContentDataByNavigation } from './extractContentData';

export type DetailsModalProps = {
  isOpen: boolean;
  onClose: VoidFunction;
  afterAcceptedAll: VoidFunction;
  showBackButton?: boolean;
};

export const DetailsModal = ({
  isOpen = false,
  onClose,
  afterAcceptedAll,
  showBackButton = true,
}: DetailsModalProps): JSX.Element => {
  const [search, setSearch] = React.useState<string>('');
  const [filtered, setFiltered] = React.useState<Category[]>([]);
  const [navigation, setNavigation] = React.useState<Navigation>({});

  const { categories, handlers, settingsLabels } = useUsercentrics();

  React.useEffect(() => {
    setFiltered(getCategoriesBySearch(categories, search));
  }, [categories, search]);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setNavigation({});
    setSearch(e.target.value);
  };

  const onAcceptAll = () => {
    handlers?.acceptAll();

    if (afterAcceptedAll) {
      afterAcceptedAll();
    }

    onClose();
  };

  const onClickMenuCategoryItem = (event: React.MouseEvent<HTMLButtonElement>) => {
    setNavigation({ categorySlug: event.currentTarget.dataset.categorySlug });
  };

  const onClickMenuServiceItem = (event: React.MouseEvent<HTMLButtonElement>) => {
    setNavigation({ serviceId: event.currentTarget.dataset.serviceId });
  };

  return (
    <Modal
      isOpen={isOpen}
      contentLabel="Details Modal"
      overlayClassName="uc-modal"
      className="uc-modal__content uc-flex uc-h-[90vh] md:uc-h-[720px] uc-max-w-[736px] uc-p-0"
    >
      <div className="uc-w-full uc-flex uc-flex-col uc-flex-1 uc-text-kilamanjaro uc-leading-tight">
        <div className="uc-p-4 uc-shadow-md uc-z-10">
          <TextField
            className="uc-w-full uc-py-2.5 uc-px-4 uc-rounded-md uc-border-2 uc-border-swirl uc-placeholder-swirl"
            placeholder="Search"
            aria-label="Search"
            value={search}
            onChange={handleSearch}
          />
        </div>
        <div className="uc-flex uc-flex-row uc-min-h-0 uc-flex-grow">
          <nav className="uc-hidden md:uc-flex uc-flex-col uc-flex-shrink-0 uc-w-52 uc-bg-primary-lightest uc-p-4 uc-space-y-6 uc-overflow-y-auto uc-rounded-bl-md">
            {filtered.map((category: Category) => (
              <div className="uc-flex uc-flex-col" key={category.slug}>
                <h4 className="uc-mb-4">
                  <button
                    className="uc-text-18 uc-text-left uc-font-medium"
                    onClick={onClickMenuCategoryItem}
                    data-category-slug={category.slug}
                  >
                    {category.label}
                  </button>
                </h4>
                <ul>
                  {category.services.map((service: Service) => (
                    <li key={service.id} className="uc-mb-4">
                      <button
                        className="uc-text-left uc-text-16"
                        data-service-id={service.id}
                        onClick={onClickMenuServiceItem}
                      >
                        {service.name}
                      </button>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </nav>
          <div className="uc-w-full uc-flex-grow uc-flex uc-flex-col uc-justify-between">
            <div className="uc-overflow-y-auto">
              <Content data={getContentDataByNavigation(filtered, navigation)} />
            </div>
            <div className="uc-p-4 uc-pb-2 sm:uc-pb-4 uc-border-t-2 uc-border-dotted uc-border-swirl uc-bg-[f7edea] sm:uc-flex sm:uc-justify-between sm:uc-flex-row-reverse">
              <div className="uc-mb-2 sm:uc-mb-0">
                <button className="uc-button uc-button--primary uc-w-full" onClick={onAcceptAll}>
                  {settingsLabels?.buttons.acceptAll}
                </button>
              </div>
              {showBackButton ? (
                <div className="uc-flex uc-justify-center" id={`cool-beans-${showBackButton}`}>
                  <button className="uc-button uc-button--text" onClick={onClose}>
                    {settingsLabels?.general.back}
                  </button>
                </div>
              ) : (
                <></>
              )}
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
