import React, { useCallback, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import {
  CustomModalLayout,
  Modal,
  Box,
  TextButton,
  AddItem,
  Text,
  Divider,
  Search,
  ToastContainer,
} from '@wix/design-system';
import { useCollectionReachBottom } from '../../../useCollectionReachBottom';
import { InfiniteScrollLoader } from '../../../InfiniteScrollLoader/InfiniteScrollLoader';
import { Add } from '@wix/wix-ui-icons-common';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { TagsListItem } from './List/TagsListItem';
import { st, classes } from './ManageTagsModal.st.css.js';
import { ScrollableContent } from '../../../ScrollableContent';
import { MessageActionModal } from '../../../ActionModal';
import { Trans } from '../../../Trans';
import { TagsModalState } from '../../../../state/TagsModalState';
import { NewTagItemEditable } from './NewTagItemEditable';
import { minimalRequiredWdsRuntimeCheck } from '../../../../minimalRequiredWdsRuntimeCheck';
import { ManageTagsNotification } from './ManageTagsNotification';
import { TAG_MAX_LENGTH, ToastConfig } from '@wix/bex-core';

export interface ManageTagsModalProps {
  state: TagsModalState;
}

const ManageTagsModalContent = observer(({ state }: ManageTagsModalProps) => {
  const { translate: t } = useWixPatternsContainer();
  const closeModal = useCallback(() => {
    state.closeManageTagsModal();
  }, [state]);

  const handleCreateClick = useCallback(() => {
    state.handleCreateCtaClick();
  }, [state]);

  const handleCreateTagFromSearch = useCallback(() => {
    state.createTagFromSearch();
  }, [state]);

  const handleSearchClear = useCallback(() => {
    state.handleSearchClear();
  }, [state]);

  const handleSearchChange = useCallback(
    (event) => {
      const newSearchValue = event.target.value;
      state.handleSearchChange(newSearchValue);
    },
    [state],
  );

  const handleNotificationClose = useCallback(
    (toastConfig: ToastConfig) => {
      state.hideNotification(toastConfig);
    },
    [state],
  );

  const shouldAllowTagsPagination =
    state.tagsManagementState.shouldAllowTagsPagination;

  const scrollRef = useRef<HTMLDivElement>(null);
  state.ref = scrollRef;
  const { targetRef } = useCollectionReachBottom({
    collection: state.tagsManagementState.collection,
    containerRef: shouldAllowTagsPagination ? scrollRef : undefined,
  });

  return (
    <Box width={510}>
      <CustomModalLayout
        className={st(classes.root)}
        overflowY="visible"
        showFooterDivider
        removeContentPadding
        title={t('cairo.tags.manageTags.modal.title', {
          EntityName: state.entityTypeName,
        })}
        subtitle={t('cairo.tags.manageTags.modal.subtitle')}
        sideActions={
          <Box>
            <TextButton
              dataHook="manage-tags-modal-create-btn"
              size="small"
              prefixIcon={<Add />}
              onClick={handleCreateClick}
              disabled={state.isShowingNewTagListItem}
            >
              {t('cairo.tags.manageTags.modal.add.CTA')}
            </TextButton>
          </Box>
        }
        primaryButtonText={t('cairo.tags.manageTags.modal.close.CTA')}
        primaryButtonOnClick={closeModal}
        onCloseButtonClick={closeModal}
        dataHook="manage-tags-modal-layout"
      >
        <Box direction="vertical" height="100%" flex={1}>
          <ToastContainer>
            {state.toastConfig && (
              <ManageTagsNotification
                toastConfig={state.toastConfig}
                onClose={handleNotificationClose}
                dataHook="manage-tags-modal-notification"
              />
            )}
          </ToastContainer>
          <Box direction="vertical" gap="SP2">
            <Box padding="0 SP4">
              <Search
                autoFocus
                dataHook="manage-tags-modal-search"
                onChange={handleSearchChange}
                value={state.searchValue}
                placeholder={t(
                  'cairo.tags.manageTags.modal.search.placeholder',
                )}
                onEnterPressed={handleCreateTagFromSearch}
                onClear={handleSearchClear}
              />
            </Box>
            <Divider />
          </Box>
          <Box
            ref={shouldAllowTagsPagination ? scrollRef : undefined}
            direction="vertical"
            maxHeight={446}
            minHeight={225}
            dataHook="manage-tags-modal-tags-list"
            overflowY="auto"
            paddingBottom="SP1"
          >
            <ScrollableContent
              overflowY={!shouldAllowTagsPagination}
              smooth={!shouldAllowTagsPagination}
              ref={!shouldAllowTagsPagination ? state.ref : undefined}
            >
              {state.searchValue && state.shownItems.length === 0 && (
                <div>
                  <AddItem
                    theme="plain"
                    size="tiny"
                    alignItems="left"
                    onClick={handleCreateTagFromSearch}
                    dataHook="manage-tags-modal-list-add"
                  >
                    <Text skin="primary">
                      <Trans
                        i18nKey="cairo.tags.manageTags.modal.list.create.CTA"
                        values={{
                          tagName: `${state.searchValue.slice(
                            0,
                            TAG_MAX_LENGTH,
                          )}`,
                        }}
                        components={{
                          name: <Text weight="bold" skin="primary" />,
                        }}
                      />
                    </Text>
                  </AddItem>
                </div>
              )}
              {state.shownItems.map((tag, idx) => (
                <TagsListItem
                  state={state}
                  key={tag.id}
                  tag={tag}
                  isLastTag={
                    !state.isShowingNewTagListItem &&
                    idx === state.shownItems.length - 1
                  }
                />
              ))}
              {state.isShowingNewTagListItem && (
                <NewTagItemEditable state={state} />
              )}
              {shouldAllowTagsPagination && (
                <InfiniteScrollLoader
                  targetRef={targetRef}
                  state={state.tagsManagementState.collection}
                  size="small"
                />
              )}
            </ScrollableContent>
          </Box>
        </Box>
      </CustomModalLayout>
    </Box>
  );
});

const ManageTagsModalComponent = ({ state }: ManageTagsModalProps) => {
  if (process.env.NODE_ENV !== 'production') {
    minimalRequiredWdsRuntimeCheck({
      required: '^1.72.0',
      requiredBy: 'WixPatterns/ManageTagsModal',
    });
  }

  const closeModal = useCallback(() => {
    state.closeManageTagsModal();
  }, [state]);

  return (
    <>
      <Modal
        isOpen={state.isOpen}
        onRequestClose={closeModal}
        shouldCloseOnOverlayClick
        dataHook="manage-tags-modal"
      >
        <ManageTagsModalContent state={state} />
      </Modal>
      {state.confirmModalState.value && (
        <MessageActionModal
          dataHook="manage-tags-modal-confirm-delete-modal"
          state={state.confirmModalState}
          content={
            <Trans
              i18nKey="cairo.tags.manageTags.modal.deleteModal.body"
              values={{ name: state.tagToDelete?.name }}
              components={{
                text: <Text />,
                name: <Text weight="bold" />,
              }}
            />
          }
          {...state.confirmModalState.value}
        />
      )}
    </>
  );
};

export const ManageTagsModal = observer(ManageTagsModalComponent);
