import '@twig/scss/jsshop/filters/_filter-side-modal.scss';

import * as React from 'react';
import { FiltersWithDefaultOrder, OrderedFilters } from '@assets/filters/layouts/shared';
import { useFilterOrder } from '@assets/filters/common/contexts/sharedStatics';
import { translate as _t } from '@assets/js-shop/ShopUtils';

import { OpenerBehaviour } from '@assets/filters/common/components/common';
import { useConfig } from '@assets/filters/common/contexts/config';
import { useFilterData } from '@assets/filters/common/contexts/filterData';
import { FormLayoutProvider } from '@assets/filters/common/contexts/formLayout';

const openerBehaviour: OpenerBehaviour = { closeOnOutsideClick: false };

function confirmFilters(ev: React.MouseEvent<HTMLButtonElement>) {
   ev.currentTarget.dispatchEvent(new Event('modal:close', { bubbles: true }));
}

function ClearFiltersButton() {
   const { setFilterData, filterData } = useFilterData();

   function clearFilters() {
      setFilterData({});
   }

   return (
      <button
         className="btn btn-link"
         onClick={clearFilters}
         disabled={!Object.keys(filterData).length}
      >
         {_t('clearFilters')}
      </button>
   );
}

export function SideModal() {
   const config = useConfig();
   const filterOrder = useFilterOrder();

   if (!config) {
      return <></>;
   }

   if (!Object.keys(filterOrder ?? {}).length) {
      return (
         <FormLayoutProvider layout={{ isTopHorizontal: false }}>
            <div className="filter-side-modal">
               <FiltersWithDefaultOrder openerBehaviour={openerBehaviour} />

               <button className="btn btn-primary" onClick={confirmFilters}>
                  {_t('confirmFilters')}
               </button>

               <ClearFiltersButton />
            </div>
         </FormLayoutProvider>
      );
   }

   return (
      <FormLayoutProvider layout={{ isTopHorizontal: false }}>
         <div className="filter-side-modal">
            <OrderedFilters orderedFilters={filterOrder} openerBehaviour={openerBehaviour} />

            <button className="btn btn-primary" onClick={confirmFilters}>
               {_t('confirmFilters')}
            </button>

            <ClearFiltersButton />
         </div>
      </FormLayoutProvider>
   );
}
