/* 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,
  useEffect,
  useRef,
  useState,
} from 'react';
import { twMerge } from 'tailwind-merge';

import useDisclosure from '@/hooks/useDisclosure';

interface SelectorProps {
  selections: { name: string; key: string }[];
  onChange: (key: string) => void;
  initialSelection?: string;
  selectorButtonClassName?: string;
}

const Selector: React.FC<SelectorProps> = ({
  selections,
  onChange,
  initialSelection,
  selectorButtonClassName,
}) => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const dropdownRef = useRef<HTMLDivElement>(null);
  const toggleRef = useRef<HTMLDivElement>(null);
  const [selectedKey, setSelectedKey] = useState(selections?.[0]?.key);

  useEffect(() => {
    setSelectedKey(initialSelection || selections?.[0]?.key);
  }, [initialSelection]);

  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();
    }
  };

  return (
    <div className='relative inline-flex justify-center text-left font-sans'>
      <div
        tabIndex={0}
        className={twMerge(
          'inline-flex min-w-20 cursor-pointer items-center rounded-lg bg-background-tertiary px-2 py-1 text-sm font-medium text-foreground-primary select-none md:px-3',
          selectorButtonClassName
        )}
        ref={toggleRef}
        onClick={(e: MouseEvent) => {
          e.preventDefault();
          e.stopPropagation();
          handleToggle();
        }}
        onKeyDown={(e: KeyboardEvent) => {
          if (e.key === 'Enter') {
            e.preventDefault();
            e.stopPropagation();
            handleToggle();
          }
        }}
      >
        <span className='line-clamp-1'>
          {selections.find((s) => s.key === selectedKey)?.name}
        </span>
        <svg
          className='h-4 w-4'
          xmlns='http://www.w3.org/2000/svg'
          viewBox='0 0 20 20'
          fill='currentColor'
        >
          <path
            fillRule='evenodd'
            d='M5.23 7.21a.75.75 0 011.06 0L10 10.93l3.71-3.72a.75.75 0 111.06 1.06l-4.25 4.25a.75.75 0 01-1.06 0L5.23 8.27a.75.75 0 010-1.06z'
            clipRule='evenodd'
          />
        </svg>
      </div>
      {isOpen && (
        /*ReactDOM.createPortal(*/
        <div
          className={`absolute z-100 mt-4 w-32 overflow-y-auto rounded-md bg-background-tertiary shadow-lg`}
          ref={dropdownRef}
          style={{
            left: `0px`,
            //top: `${(toggleRef.current?.getBoundingClientRect().top || 0) + (toggleRef.current?.getBoundingClientRect().height || 0)}px`,
            right: '0px',
            top: '16px',
            maxHeight: '200px',
            overflowY: 'auto',
          }}
        >
          <div className='py-1'>
            {selections.map((selection: { name: string; key: string }) => (
              <div
                tabIndex={0}
                key={selection.key}
                className='flex cursor-pointer items-center justify-between px-3 py-1 text-sm text-foreground-primary hover:bg-background-secondary'
                onClick={() => {
                  setSelectedKey(selection.key);
                  onChange(selection.key);
                  onClose();
                }}
                onKeyDown={(e: KeyboardEvent) => {
                  if (e.key === 'Enter') {
                    setSelectedKey(selection.key);
                    onChange(selection.key);
                    onClose();
                  }
                }}
              >
                <div className='font-sans font-medium'>{selection.name}</div>
              </div>
            ))}
          </div>
        </div>
        //document.body
      )}
    </div>
  );
};

export default Selector;
