import clsx from 'clsx';
import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';
import { twMerge } from 'tailwind-merge';

import { ConditionalTooltip } from './ConditionalTooltip';

export type Option = {
  title: string;
  value: string;
  rightIcon?: React.FC<React.SVGProps<SVGSVGElement>>;
  leftIcon?: React.FC<React.SVGProps<SVGSVGElement>>;
  disabled?: boolean;
  disabledTooltip?: string;
};

const DEFAULT_CLASSES =
  'w-auto h-full text-base px-6 py-3 flex flex-row flex-1 text-nowrap items-center gap-2 justify-center';

export const AnimatedTabs = ({
  options,
  onChange,
  value,
  id, // a unique ID for the component on the page
  className = '',
  buttonClassName = '',
  overlayClassName = '',
  shouldAnimate = true,
  disabled = false,
}: {
  value?: string;
  options: Option[];
  onChange: (option: Option) => void;
  id: string;
  className?: string;
  buttonClassName?: string;
  overlayClassName?: string;
  shouldAnimate?: boolean;
  disabled?: boolean;
}) => {
  const [activeOption, setActiveOption] = useState(value || options[0].value);
  useEffect(() => {
    if (value) {
      setActiveOption(value);
    }
  }, [value]);

  return (
    <div
      className={twMerge(
        clsx(
          'flex h-auto w-auto flex-row rounded-full border border-white/10 bg-white/10 transition',
          {
            'brightness-50': disabled,
          }
        ),
        className
      )}
    >
      {options.map((option: Option) => (
        <ConditionalTooltip
          key={option.value}
          isTooltipEnabled={
            !!option.disabled && (option.disabledTooltip || '') !== ''
          }
          label={option.disabledTooltip || ''}
        >
          <button
            disabled={disabled || option.disabled}
            key={option.value}
            aria-label={`Switch to ${option.title} mode`}
            onClick={(e) => {
              if (!disabled && !option.disabled) {
                setActiveOption(option.value);
                onChange(option);
              }
              e.stopPropagation();
            }}
            className={clsx(
              twMerge(DEFAULT_CLASSES, 'relative', buttonClassName),
              {
                'cursor-pointer whitespace-nowrap text-foreground-primary/70 hover:text-foreground-primary':
                  option.value !== activeOption,
                'cursor-default': option.value === activeOption,
                'brightness-50': option.disabled,
              }
            )}
          >
            {option.value === activeOption ? (
              <motion.div
                layout={false}
                layoutId={`active-${id}`}
                className={twMerge(
                  DEFAULT_CLASSES,
                  'absolute top-0 z-10 w-full rounded-full bg-white/10',
                  overlayClassName
                )}
                transition={{
                  type: 'spring',
                  bounce: 0.05,
                  duration: shouldAnimate ? 0.3 : 0,
                }}
              />
            ) : null}
            <span className='z-20 flex flex-row items-center gap-1 whitespace-nowrap select-none'>
              {option.leftIcon ? <option.leftIcon className='h-4 w-4' /> : null}
              {option.title}
              {option.rightIcon ? (
                <option.rightIcon className='h-4 w-4' />
              ) : null}
            </span>
          </button>
        </ConditionalTooltip>
      ))}
    </div>
  );
};
