import React from 'react';

export interface PaletteDragPayload {
  type: 'operator' | 'indicator' | 'start';
  value: string;
  label: string;
  composite?: boolean;
}

interface Props {
  type: 'operator' | 'indicator' | 'start';
  value: string;
  label: string;
  desc?: string;
  color?: string;
  period?: string;
  composite?: boolean;
  selected?: boolean;
  onSelect?: () => void;
  onAdd: () => void;
}

export default function PaletteChip({
  type, value, label, desc, color, period, composite = false, selected = false, onSelect, onAdd,
}: Props) {
  const onDragStart = (e: React.DragEvent) => {
    const payload: PaletteDragPayload = { type, value, label, composite: composite || undefined };
    e.dataTransfer.setData('application/json', JSON.stringify(payload));
    e.dataTransfer.effectAllowed = 'copy';
  };

  const handleClick = () => {
    if (onSelect) onSelect();
    else onAdd();
  };

  const handleDoubleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    onAdd();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key !== 'Enter' && e.key !== ' ') return;
    e.preventDefault();
    if (onSelect) {
      if (selected) onAdd();
      else onSelect();
    } else {
      onAdd();
    }
  };

  return (
    <div
      draggable
      className={`se-palette-card ${color ? `se-palette-card--${color}` : 'se-palette-card--ind'}${composite ? ' se-palette-card--composite' : ''}${selected ? ' se-palette-card--selected' : ''}`}
      onDragStart={onDragStart}
      onClick={handleClick}
      onDoubleClick={handleDoubleClick}
      role="button"
      tabIndex={0}
      onKeyDown={handleKeyDown}
    >
      <div className="se-palette-card-head">
        <span className="se-palette-card-icon">{label.slice(0, 1)}</span>
        <div className="se-palette-card-meta">
          <span className="se-palette-card-name">
            {composite ? `${label} + ${label}` : label}
          </span>
          {desc ? <span className="se-palette-card-desc">{desc}</span> : null}
        </div>
      </div>
      {period ? (
        <div className="se-palette-card-period">
          <span>기간</span>
          <input readOnly value={period} className="se-palette-period-input" tabIndex={-1} />
          <span className="se-palette-sync" title="차트 지표 설정과 동기화">⟳</span>
        </div>
      ) : null}
    </div>
  );
}
