/* eslint jsx-a11y/no-static-element-interactions: warn */

/* eslint jsx-a11y/no-noninteractive-tabindex: warn */
import { useOutsideClick } from '@chakra-ui/react';
import React, { KeyboardEvent, MouseEvent, useRef } from 'react';

import useDisclosure from '@/hooks/useDisclosure';
import { SUPER_MODAL_Z_INDEX } from '@/utils/constants';

interface Selection {
  name: string;
  key: string;
  icon?: React.ComponentType<React.SVGAttributes<SVGSVGElement>>;
}

interface SelectorProps {
  selections: Selection[];
  onChange: (key: string) => void;
  customToggleStyle?: string;
  customIconStyle?: string;
}

const Selector: React.FC<SelectorProps> = ({
  selections,
  onChange,
  customToggleStyle = '',
  customIconStyle = '',
}) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const dropdownRef = useRef<HTMLDivElement>(null);
  const toggleRef = useRef<HTMLDivElement>(null);

  useOutsideClick({
    ref: dropdownRef as React.RefObject<HTMLDivElement>,
    handler: (e) => {
      if (!toggleRef.current?.contains(e.target as any)) {
        onClose();
      }
    },
  });

  const handleToggle = () => {
    if (isOpen) {
      onClose();
    } else {
      onOpen();
    }
  };

  const MoreIcon = selections[0].icon;

  return (
    <div className='relative inline-flex justify-center text-left font-sans'>
      <div
        tabIndex={0}
        className={`inline-flex cursor-pointer items-center rounded-lg p-2 select-none ${customToggleStyle}`}
        ref={toggleRef}
        onClick={(e: MouseEvent) => {
          e.preventDefault();
          e.stopPropagation();
          handleToggle();
        }}
        onKeyDown={(e: KeyboardEvent) => {
          if (e.key === 'Enter') {
            e.preventDefault();
            e.stopPropagation();
            handleToggle();
          }
        }}
      >
        {MoreIcon && <MoreIcon className={customIconStyle} />}
      </div>
      {isOpen && (
        <div
          className='fixed mt-2 w-40 overflow-y-auto rounded-md bg-background-tertiary shadow-lg'
          ref={dropdownRef}
          style={{
            zIndex: SUPER_MODAL_Z_INDEX,
            left: toggleRef.current
              ? toggleRef.current.getBoundingClientRect().left
              : 0,
            top: toggleRef.current
              ? toggleRef.current.getBoundingClientRect().bottom +
                window.scrollY
              : 0,
          }}
        >
          <div className='py-1'>
            {selections.slice(1).map((selection) => (
              <div
                tabIndex={0}
                key={selection.key}
                className='flex cursor-pointer items-center px-3 py-2 text-sm text-foreground-primary hover:bg-background-secondary/20'
                onClick={() => {
                  onChange(selection.key);
                  onClose();
                }}
                onKeyDown={(e: KeyboardEvent) => {
                  if (e.key === 'Enter') {
                    onChange(selection.key);
                    onClose();
                  }
                }}
              >
                {selection.icon && (
                  <selection.icon className='mr-2 h-3 w-3 fill-foreground-primary' />
                )}
                <div className='font-sans font-medium'>{selection.name}</div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default Selector;
