import { FC } from 'react';
import { Element } from '../types';

interface ElementViewProps {
  onElementCombine: (elementId: number) => void;
  element: Element;
  interactive: boolean;
  isPreview: boolean;
}

const ElementView: FC<ElementViewProps> = ({
  onElementCombine,
  element,
  interactive,
  isPreview,
}) => {
  const onDragStart = (e: React.DragEvent<HTMLDivElement>) => {
    e.stopPropagation();

    e.dataTransfer.setData('text/plain', element.name);
    e.dataTransfer.setData('id', element.id.toString());
  };

  const onDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  };

  const onDrop = (e: React.DragEvent<HTMLDivElement>) => {
    const elementId = e.dataTransfer.getData('id');
    onElementCombine(Number.parseInt(elementId));
    e.preventDefault();
  };

  return (
    <div
      draggable={interactive}
      onDragStart={interactive ? onDragStart : undefined}
      onDragOver={interactive ? onDragOver : undefined}
      onDrop={interactive ? onDrop : undefined}
      className="element flex flex-row rounded-md border border-gray-300 bg-gray-100 w-[96px] h-fit">
      <div draggable={false} className="flex flex-col items-center w-full">
        {isPreview ? (
          <div
            style={{
              backgroundColor: element.icon,
            }}
            className="rounded-t w-full h-[96px]"></div>
        ) : (
          <img
            draggable={false}
            className="rounded-t"
            src={`data:image/png;base64,${element.icon}`}
            width="96px"
            height="96px"
          />
        )}
        <span
          draggable={false}
          className="my-1 mx-2 text-sm leading-tight text-center w-full">
          {element.name.length > 0 ? element.name : '\u00A0'}
        </span>
      </div>
    </div>
  );
};

export default ElementView;
