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

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

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

export function Symbols(props: ISymbolsProps): JSX.Element {
  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 type="button"
        className='flex justify-start items-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-contain'
            src={url}
          />
        </div>
        <div className='ml-5'>
          {TruncateString(componentOption.Name, 20)}
        </div>
      </button>);
    }

    return (<button type="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>);
  });

  return (
    <div className='h-full overflow-y-auto'>
      <div className='grid grid-cols-1 md:grid-cols-1 gap-2
         overflow-auto m-2 md:text-xs font-bold'>
        {listElements}
      </div>
    </div>
  );
};
