import React, { useRef, useState } from 'react';

import Switch from '../switch/Switch';

interface SwitchButtonProps {
  buttonText: string;
  onChange: (checked: boolean) => void;
  checked?: boolean;
  disabled?: boolean;
  buttonProps?: object;
  tooltip?: string;
}

const SwitchButton: React.FC<SwitchButtonProps> = ({
  buttonText,
  checked = false,
  disabled = false,
  onChange,
  buttonProps = {},
  tooltip,
}) => {
  const [showTooltip, setShowTooltip] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const handleMouseEnter = () => {
    setShowTooltip(true);
  };

  const handleMouseLeave = () => {
    setShowTooltip(false);
  };

  return (
    <>
      <button
        {...buttonProps}
        ref={buttonRef}
        className='flex flex-row items-center rounded-md bg-background-primary p-1 pl-2 outline-none'
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
        <span className={`font-sans text-sm text-foreground-primary`}>
          {buttonText}
        </span>
        <div className='ml-2'>
          <Switch
            small
            checked={checked}
            disabled={disabled}
            onChange={onChange}
          />
        </div>
      </button>
      {tooltip && showTooltip && buttonRef.current && (
        <div
          style={{
            position: 'fixed',
            left: `${buttonRef.current.getBoundingClientRect().left + buttonRef.current.offsetWidth / 2}px`,
            top: `${buttonRef.current.getBoundingClientRect().bottom + 8}px`,
            transform: 'translateX(-50%)',
          }}
          className='z-10 w-[220px] rounded bg-background-primary p-2 text-center text-sm text-foreground-primary'
        >
          {tooltip}
        </div>
      )}
    </>
  );
};

export default SwitchButton;
