'use client';

import { NodeShell } from './node-shell';
import { PortRow } from './port-row';

interface ButtonData {
  text: string;
  action: string;
  target?: string;
  url?: string;
}

interface MessageNodeData {
  text?: string;
  image?: string;
  buttons?: ButtonData[];
  isStart?: boolean;
  nodeId?: string;
  [key: string]: unknown;
}

export function MessageNode({ data, id }: { data: MessageNodeData; id: string }) {
  const text = data.text ?? '';
  const image = data.image;
  const buttons = data.buttons ?? [];
  const isStart = data.isStart;
  const nodeId = (data.nodeId as string) || id;

  const preview = text.replace(/<[^>]+>/g, '');
  const truncated = preview.length > 100 ? preview.slice(0, 100) + '...' : preview;

  const gotoButtons = buttons.filter((btn) => btn.action === 'goto' && btn.target);
  const urlButtons = buttons.filter((btn) => btn.url);

  return (
    <NodeShell
      accentColor="#29b6f6"
      icon={'\uD83D\uDCAC'}
      title="Сообщение"
      nodeId={nodeId}
      isStart={isStart}
    >
      {/* Image indicator */}
      {image && (
        <div
          style={{
            fontSize: 10,
            color: '#999',
            marginBottom: 4,
          }}
        >
          {'\uD83D\uDDBC'} Картинка
        </div>
      )}

      {/* Text preview (2 lines) */}
      <p
        style={{
          fontSize: 11,
          color: '#666',
          lineHeight: '15px',
          margin: 0,
          overflow: 'hidden',
          display: '-webkit-box',
          WebkitLineClamp: 2,
          WebkitBoxOrient: 'vertical',
        }}
      >
        {truncated || (
          <span style={{ fontStyle: 'italic', color: '#bdbdbd' }}>Пустое сообщение</span>
        )}
      </p>

      {/* URL buttons — text only, no handles */}
      {urlButtons.length > 0 && (
        <div style={{ marginTop: 4 }}>
          {urlButtons.map((btn, i) => (
            <div
              key={`url-${i}`}
              style={{
                fontSize: 10,
                color: '#90a4ae',
                padding: '2px 0',
              }}
            >
              {'\uD83D\uDD17'} {btn.text || 'URL'}
            </div>
          ))}
        </div>
      )}

      {/* Goto buttons — PortRows with handles */}
      {gotoButtons.length > 0 && (
        <div style={{ margin: '4px -10px 0' }}>
          {gotoButtons.map((btn) => {
            const originalIndex = buttons.indexOf(btn);
            return (
              <PortRow
                key={`btn-${originalIndex}`}
                label={btn.text || '---'}
                handleId={`source-btn-${originalIndex}`}
              />
            );
          })}
        </div>
      )}
    </NodeShell>
  );
}
