import { useDrag } from 'react-dnd';
import React from 'react';

const ItemTypes = {
  SPECIALITY: 'speciality',
};

const lightenColor = (color, percent) => {
  const num = parseInt(color.slice(1), 16),
    amt = Math.round(2.55 * percent),
    R = (num >> 16) + amt,
    G = ((num >> 8) & 0x00ff) + amt,
    B = (num & 0x0000ff) + amt;
  return `#${(0x1000000 + (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 + (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 + (B < 255 ? (B < 1 ? 0 : B) : 255)).toString(16).slice(1).toUpperCase()}`;
};

const darkenColor = (color, percent) => {
  const num = parseInt(color.slice(1), 16),
    amt = Math.round(2.55 * percent),
    R = (num >> 16) - amt,
    G = ((num >> 8) & 0x00ff) - amt,
    B = (num & 0x0000ff) - amt;
  return `#${(0x1000000 + (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 + (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 + (B < 255 ? (B < 1 ? 0 : B) : 255)).toString(16).slice(1).toUpperCase()}`;
};

const SpecialityItem = ({ speciality, isDraggable = true }) => {
  const [{ isDragging }, drag] = useDrag(
    () => ({
      type: ItemTypes.SPECIALITY,
      item: { id: speciality.id, name: speciality.name },
      collect: (monitor) => ({
        isDragging: !!monitor.isDragging(),
      }),
      canDrag: () => isDraggable,
    }),
    [isDraggable]
  );

  return (
    <div
      ref={isDraggable ? drag : null}
      className={`inline-block px-3 py-1 rounded-lg font-bold text-white text-center transition-transform duration-200 ease-in-out ${
        isDragging ? 'opacity-30' : 'opacity-100'
      } ${isDraggable ? 'cursor-grabbing hover:shadow-lg hover:scale-105' : ''}`}
      style={{
        backgroundColor: isDragging
          ? lightenColor(speciality.color_code, 30)
          : speciality.color_code,
        border: `1px solid ${darkenColor(speciality.color_code, 20)}`,
        color: 'white',
        boxShadow: isDraggable ? '0 2px 4px rgba(0, 0, 0, 0.1)' : 'none',
      }}
    >
      {speciality.name}
    </div>
  );
};

export default SpecialityItem;
