'use client';

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

interface ActionNodeData {
  actions?: Array<{ type: string; variable?: string; value?: unknown }>;
  isStart?: boolean;
  nodeId?: string;
  [key: string]: unknown;
}

const ACTION_LABELS: Record<string, string> = {
  set_variable: 'Переменная',
  grant_bonus: 'Бонус',
  set_consent: 'Согласие',
  crm_deal: 'Сделка CRM',
  webhook: 'Webhook',
};

const ACTION_ICONS: Record<string, string> = {
  set_variable: '\uD83D\uDCCC',
  grant_bonus: '\uD83C\uDF81',
  set_consent: '\u2705',
  crm_deal: '\uD83D\uDCCB',
  webhook: '\uD83D\uDD17',
};

export function ActionNode({ data, id }: { data: ActionNodeData; id: string }) {
  const actions = (data.actions ?? []) as Array<{
    type: string;
    variable?: string;
    value?: unknown;
  }>;
  const isStart = data.isStart;
  const nodeId = (data.nodeId as string) || id;

  return (
    <NodeShell
      accentColor="#ab47bc"
      icon={'\u26A1'}
      title="Действие"
      nodeId={nodeId}
      isStart={isStart}
    >
      {actions.length === 0 && (
        <p
          style={{
            fontSize: 10,
            fontStyle: 'italic',
            color: '#bdbdbd',
            margin: 0,
          }}
        >
          Нет действий
        </p>
      )}

      {actions.slice(0, 3).map((action, i) => (
        <div
          key={i}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 4,
            padding: '2px 0',
            borderTop: i > 0 ? '1px solid #f5f5f5' : undefined,
          }}
        >
          <span style={{ fontSize: 10, lineHeight: 1 }}>
            {ACTION_ICONS[action.type] ?? '\u2022'}
          </span>
          <span
            style={{
              fontSize: 10,
              color: '#555',
              fontWeight: 500,
            }}
          >
            {ACTION_LABELS[action.type] ?? action.type}
          </span>
          {action.variable && (
            <span
              style={{
                fontSize: 9,
                color: '#9e9e9e',
                fontFamily: 'monospace',
                marginLeft: 'auto',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: 80,
              }}
            >
              {action.variable}
              {action.value !== undefined
                ? ` = ${typeof action.value === 'object' ? JSON.stringify(action.value) : String(action.value as string | number | boolean)}`
                : ''}
            </span>
          )}
        </div>
      ))}

      {actions.length > 3 && (
        <p
          style={{
            fontSize: 9,
            color: '#bdbdbd',
            margin: '2px 0 0',
            textAlign: 'center',
          }}
        >
          +{actions.length - 3} ещё
        </p>
      )}
    </NodeShell>
  );
}
