import type { SidebarToggleFunc, Product } from '@assets/js-multisets/common/types';
import type { ResultOf } from '@graphql-typed-document-node/core';
import type { MULTI_SET_CATEGORY_FIELDS } from '@assets/js-multisets/common/constants/query';

import React, { type ReactNode, useEffect, useRef } from 'react';
import * as ReactDOM from 'react-dom';
import { translate as _t } from '@assets/js-multisets/common/utils/translate';
import { SelectionRow } from '@assets/js-multisets/sidebar/selection-row/SelectionRow';

export type SidebarProps = {
   row: number;
   categories: ResultOf<typeof MULTI_SET_CATEGORY_FIELDS>[];
   onSidebarToggle: SidebarToggleFunc;
   selection: Record<number, any>;
   product: Product;
   activeFocusVariation?: number;
   children?: ReactNode | ReactNode[];
};

export function Sidebar(props: SidebarProps) {
   const sidebarRef = useRef<HTMLDivElement>();

   useEffect(() => {
      sidebarRef.current?.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
   }, [sidebarRef.current]);

   const activeCategory = props.categories[props.row];

   return ReactDOM.createPortal(
      <div className="jsmultisets">
         <div className="jsmultisets-overlay" onClick={props.onSidebarToggle}/>
         <div className="jsmultisets-sidebar" ref={sidebarRef}>
            <div className="jsmultisets-sidebar-header">
               <span className="title-default">{`${MODULES.COMPONENTS ? `${_t('vyberte')} ${activeCategory.name}` : _t('vlozitDoSetu')}`}</span>

               <a href="#" className="focus-close" onClick={props.onSidebarToggle} dangerouslySetInnerHTML={{ __html: MODULES.COMPONENTS ? require('@assets/icons/close.svg?raw') : '<i class="fc icons_close"></i>' }} />
            </div>
            <SelectionRow
               key={props.row}
               data={activeCategory}
               row={props.row}
               onSidebarToggle={props.onSidebarToggle}
               selection={props.selection}
               activeProduct={props.product}
               activeFocusVariation={props.activeFocusVariation}
            />
            <div className="jsmultisets-sidebar-inner">{props.children}</div>
         </div>
      </div>
   , document.querySelector('body'));
}
