import React, { FunctionComponent, useState, useEffect, useRef } from 'react';
import cn from 'classnames';

import { Paragraph } from '../Paragraph';
import { Menu } from '../Menu';
import { Title } from '../Title';
import { useTheme } from '../Theme';
import { CustomSelectProps } from './types.d';

export const CustomSelect: FunctionComponent<CustomSelectProps> = ({
  className = '',
  data,
  onSelect,
  predefinedText,
  style,
  textSize = 16,
  value,
  variant = 'standard',
}) => {
  const theme = useTheme();
  const ref = useRef<HTMLDivElement>(null);
  const [isOpen, setIsOpen] = useState(false);
  const title = data.find((item) => item.value === value)?.title ?? '';
  const [width, setWidth] = useState(120);

  useEffect(() => {
    if (ref.current) setWidth(ref.current.offsetWidth);
  }, []);

  const anchorClassNames = cn({
    'square-select-anchor-container': true,
    [className]: true,
    [variant]: true,
  });

  const renderAnchor = () => {
    return (
      <div
        ref={ref}
        className={anchorClassNames}
        style={{ ...style, backgroundColor: variant === 'standard' ? theme.background.light : 'transparent' }}
      >
        <div className="square-select-anchor-text-container">
          <Paragraph size={textSize}>{`${predefinedText ?? ''} `}</Paragraph>
          <Title size={textSize}>{title}</Title>
        </div>
        <div
          className="square-select-anchor-icon-container"
          style={{ borderLeftColor: variant === 'standard' ? theme.pallet.gray : 'transparent' }}
        >
          <svg
            className={`square-custom-select-icon ${isOpen ? 'open' : ''}`}
            width="11"
            height="7"
            viewBox="0 0 11 7"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              fillRule="evenodd"
              clipRule="evenodd"
              d="M9.97127 0C10.3885 0 10.6222 0.480846 10.3644 0.808911L5.89316 6.49962C5.69297 6.7544 5.30703 6.7544 5.10684 6.49962L0.635572 0.80891C0.377808 0.480846 0.611516 0 1.02873 0L9.97127 0Z"
              fill={theme.text.secondary}
            />
          </svg>
        </div>
      </div>
    );
  };
  return (
    <Menu className="square-custom-select" anchor={renderAnchor()} isOpen={isOpen} setIsOpen={setIsOpen}>
      {data.map((item) => {
        return (
          <Menu.Item
            style={{ width, fontSize: textSize }}
            isRenderEmptyIcon
            isSelected={item.value === value}
            title={item.title}
            key={item.title + item.value.toString()}
            onClick={() => onSelect(item.value)}
          />
        );
      })}
    </Menu>
  );
};
