import * as React from 'react';
import { IAvailableSymbol } from '../../Interfaces/IAvailableSymbol';
import { truncateString } from '../../utils/stringtools';

interface ISymbolsProps {
  componentOptions: IAvailableSymbol[]
  isOpen: boolean
  buttonOnClick: (type: string) => void
}

function handleDragStart(event: React.DragEvent<HTMLButtonElement>): void {
  event.dataTransfer.setData('type', (event.target as HTMLButtonElement).id);
}

export const Symbols: React.FC<ISymbolsProps> = (props: ISymbolsProps) => {
  const listElements = props.componentOptions.map(componentOption => {
    if (componentOption.Image.Url !== undefined || componentOption.Image.Base64Image !== undefined) {
      const url = componentOption.Image.Base64Image ?? componentOption.Image.Url;
      return (<button
        className='justify-center sidebar-component-card hover:h-full'
        key={componentOption.Name}
        id={componentOption.Name}
        title={componentOption.Name}
        onClick={() => props.buttonOnClick(componentOption.Name)}
        draggable={true}
        onDragStart={(event) => handleDragStart(event)}
      >
        <div>
          <img
            className='transition-all h-12 w-full object-cover'
            src={url}
          />
        </div>
        <div>
          {truncateString(componentOption.Name, 5)}
        </div>
      </button>);
    }

    return (<button
      className='group justify-center sidebar-component hover:h-full'
      key={componentOption.Name}
      id={componentOption.Name}
      title={componentOption.Name}
      onClick={() => props.buttonOnClick(componentOption.Name)}
      draggable={true}
      onDragStart={(event) => handleDragStart(event)}
    >

      {truncateString(componentOption.Name, 5)}
    </button>);
  });

  const isOpenClasses = props.isOpen ? 'left-16' : '-left-64';
  return (
    <div className={`fixed z-10 bg-slate-200
      text-gray-700 transition-all h-full w-64
      overflow-y-auto ${isOpenClasses}`}>
      <div className='bg-slate-100 sidebar-title'>
          Symbols
      </div>
      <div className='grid grid-cols-1 md:grid-cols-3 gap-2
         m-2 md:text-xs font-bold'>
        {listElements}
      </div>
    </div>
  );
};
