import React, { FunctionComponent, useState } from 'react';
import { Input, Tooltip } from '@material-ui/core';
import { FaTimes } from 'react-icons/fa';
import cn from 'classnames';

import { Paragraph } from '../Paragraph';
import { useTheme } from '../Theme';

import { TabProps } from './types.d';
import { StyledCloseButton } from './styled-components';

export const Tab: FunctionComponent<TabProps> = (props): React.ReactElement => {
  const {
    customComponent = null,
    disabled = false,
    editable,
    hideCloseButton = false,
    id,
    isActive,
    name,
    onChangeTab,
    onClose,
    tooltip = '',
  } = props;
  const [text, setText] = useState(name);
  const theme = useTheme();

  const containerClassNames = cn({
    'tab-item': true,
    'just-text': !editable && !onClose && text,
    active: isActive,
    disabled,
  });

  const renderTitle = () => {
    if (!text) return null;
    if (editable)
      return (
        <Input
          value={text}
          onChange={(e) => setText(e.target.value)}
          style={{
            color: isActive ? theme.active ?? theme.pallet.primaryColor : theme.text.secondary,
          }}
          disableUnderline
          disabled={!editable || disabled}
          className="tab-text"
          onBlur={() => {
            if (onChangeTab) onChangeTab(text);
          }}
        />
      );
    return (
      <Paragraph
        size={14}
        className="tab-text"
        style={{ color: isActive ? theme.active ?? theme.pallet.primaryColor : theme.text.secondary, fontWeight: 500 }}
      >
        {text}
      </Paragraph>
    );
  };

  const renderCloseButton = () => {
    if (onClose && !hideCloseButton) {
      return (
        <StyledCloseButton $theme={theme} $isActive={isActive} className="tab-close">
          <FaTimes
            size={14}
            onClick={(): void => {
              onClose(id);
            }}
          />
        </StyledCloseButton>
      );
    }
    return null;
  };

  return (
    <Tooltip title={tooltip}>
      <div className={containerClassNames}>
        {customComponent}
        {renderTitle()}
        {renderCloseButton()}
      </div>
    </Tooltip>
  );
};
