import { FilterOpener, type OpenerBehaviour } from '@assets/filters/common/components/common';
import { useConfig, useFilterData } from '@assets/filters/state';
import { useTheme } from '@assets/filters/common/contexts/theme';
import { ChangeEvent, memo, useCallback, useContext } from 'react';
import { translate as _ } from '@assets/js-shop/ShopUtils';
import type { Selection } from '@assets/filters/in-store/filterDataSlice';
import { DataContext } from '@assets/js-shop/context';
import { useFormLayout } from '@assets/filters/common/contexts/formLayout';
import { createSelectedSetter } from '@assets/filters/utils';
import jsShopConfig from '@assets/js-shop/config';

type InStoreFilterProps = {
   openerBehaviour?: OpenerBehaviour;
   // Whether to show or hide the number of products. Defaults to `true`.
   showCount?: boolean;
};

function InStoreFilter({ openerBehaviour = {}, showCount = true }: InStoreFilterProps) {
   const { inStore: config } = useConfig();
   const {
      filterData,
      setFilterData,
   } = useFilterData();
   const { multiChoice: theme } = useTheme();
   const { isTopHorizontal } = useFormLayout();
   const { seller } = useContext(DataContext);
   const modalUrl = (document.querySelector('[data-seller-selection]') as HTMLElement | null)
      ?.dataset.selectionModalLink;
   const { inStore } = filterData;
   const storeIds = filterData.storeIds ?? [];

   const handleChange = useCallback(
      (ev: ChangeEvent<HTMLInputElement>) => {
         const target = ev.currentTarget;
         if (!target) {
            return;
         }

         setFilterData((prev) => {
            const newState = { ...prev };
            const inStoreKey = target.value as Selection['inStore'];

            if (target.checked) {
               newState.inStore = inStoreKey;

               return newState;
            }

            if (inStoreKey === 'inStore') {
               delete newState.inStore;
            } else if (newState.inStore === 'inStoreSupplier') {
               newState.inStore = 'inStore';
            }

            return newState;
         });
      },
      [setFilterData],
   );

   const handleSellerChange = () => {
      const setState = createSelectedSetter('storeIds', setFilterData);

      if (storeIds && seller) {
         if (storeIds.includes(seller.store.id)) {
            setState(storeIds.filter(store => store != seller.store.id));
         } else {
            setState([...storeIds, seller.store.id]);
         }
      }
   }

   if (!config || Object.keys(config).length === 0) {
      return <></>;
   }

   const options = (
      <>
         {!!config.inStore && (
            <span>
               <label className="custom-control custom-checkbox">
                  <input
                     className="custom-control-input"
                     type="checkbox"
                     value="inStore"
                     onChange={handleChange}
                     checked={!!inStore}
                  />
                  <span className="custom-control-indicator"></span>
                  <span className="custom-control-text">
                     {_('inStore')}&nbsp;
                     {showCount && <small>({config.inStore?.count ?? 0})</small>}
                  </span>
               </label>
            </span>
         )}
         {!!config.inStoreSupplier && (
            <span>
               <label className="custom-control custom-checkbox">
                  <input
                     className="custom-control-input"
                     type="checkbox"
                     value="inStoreSupplier"
                     onChange={handleChange}
                     checked={inStore === 'inStoreSupplier'}
                  />
                  <span className="custom-control-indicator"></span>
                  <span className="custom-control-text">
                     {_('inStoreSupplier')}&nbsp;
                     {showCount && <small>({config.inStoreSupplier?.count ?? 0})</small>}
                  </span>
               </label>
            </span>
         )}
         {jsShopConfig.moduleMySeller && (
            <span>
               <label className="custom-control custom-checkbox">
                  <input
                     className="custom-control-input"
                     type="checkbox"
                     value="mySeller"
                     onChange={handleSellerChange}
                     checked={storeIds.includes(seller?.store.id) ?? false}
                  />
                  <span className="custom-control-indicator"></span>
                  <span className="custom-control-text">
                     <span>
                        {_('inStoreSeller')}&nbsp;
                        <a role="button" data-wpj-modal={modalUrl}>
                           {seller?.name}
                        </a>
                     </span>
                  </span>
               </label>
            </span>
         )}
      </>
   );

   return (
      <FilterOpener
         title={_('inStoreTitle')}
         isOpen={!!inStore}
         {...theme.openerBehaviour}
         {...openerBehaviour}>
         {isTopHorizontal ? <div className="filter-item-values">{options}</div> : options}
      </FilterOpener>
   );
}

const MemoizedInStoreFilter = memo(InStoreFilter);
export { MemoizedInStoreFilter as InStoreFilter };
