import { useCallback } from 'react';

import type { StoreProduct } from '~/src/lib/pageMetadata/types';
import type { FC } from 'react';
import type { CarouselItem } from '../types';

import Clickable from '~/src/components/Clickable';
import { useAppAlert } from '~/src/components/NextApp/lib/CoreUi';
import Text from '~/src/components/Text';
import useHash from '~/src/hooks/useHash';
import { useI18n } from '~/src/lib/i18n';
import { useEditActions } from '../../../ItemPageEdit/useEditActions';
import EditCarouselItemDialog from './EditCarouselItemDialog';

/**
 * Cap the number of items in the list to keep
 * layouts clean and performance fast.
 */
const MAX_ITEMS = 8;

const AddItemButton: FC<{
  sectionPath: string;
  items: CarouselItem[];
  onSubmit: (params: { item: StoreProduct }) => void;
}> = ({ sectionPath, items }) => {
  const { setHashParam, hashParams, backToBeforeFirstHash } = useHash();
  const { updateLayoutSection } = useEditActions();
  const hashParam = toAddItemDialogHashParam(sectionPath);
  const maxItemsReached = items.length >= MAX_ITEMS;
  const dialogOpen = hashParam in hashParams;
  const appAlert = useAppAlert();
  const { t } = useI18n();

  return (
    <>
      <Clickable
        testId="addCarouselItem"
        isCentered
        fullWidth={false}
        withActiveStyle={!maxItemsReached}
        onClick={useCallback(() => {
          if (maxItemsReached) {
            appAlert({
              content: t('itemEdit.itemLimitReached'),
            });

            return;
          }

          setHashParam({ [hashParam]: '' });
        }, [maxItemsReached])}
        margin="2rem auto 0"
        style={{
          opacity: maxItemsReached ? 0.3 : 1,
        }}
      >
        <Text size="1.7rem" isBold centered>
          {t('itemEdit.actions.addItem')}
        </Text>
      </Clickable>
      {dialogOpen && (
        <EditCarouselItemDialog
          title={t('itemEdit.actions.addItem')}
          item={undefined}
          onClose={() => {
            backToBeforeFirstHash();
          }}
          onSubmit={async (carouselItem) => {
            const itemsNext: CarouselItem[] = [
              {
                ...carouselItem,
              },
              ...items,
            ];

            updateLayoutSection({
              sectionPath,

              changedProps: {
                items: itemsNext,
              },
            });
          }}
        />
      )}
    </>
  );
};

export const toAddItemDialogHashParam = (sectionPath: string) =>
  `${sectionPath}:add`;

export default AddItemButton;
