'use client';

import type { ScenarioNodeJson } from './scenario-converter';

// ─── Shared types ───────────────────────────────────────────────

interface BlockProps {
  node: ScenarioNodeJson;
  onClick?: (nodeId: string) => void;
}

interface SimpleBlockProps {
  onClick?: () => void;
}

// ─── Helpers ────────────────────────────────────────────────────

function truncate(text: string, maxLines: number, maxChars: number): string {
  const stripped = text.replace(/<[^>]+>/g, '');
  const lines = stripped.split('\n').slice(0, maxLines);
  const joined = lines.join('\n');
  return joined.length > maxChars ? joined.slice(0, maxChars) + '...' : joined;
}

// ─── StartBlock ─────────────────────────────────────────────────

export function StartBlock({ onClick }: SimpleBlockProps) {
  return (
    <div
      onClick={onClick}
      className="cursor-pointer select-none"
      style={{
        width: 120,
        padding: '8px 0',
        borderRadius: 20,
        backgroundColor: '#4caf50',
        color: '#fff',
        textAlign: 'center',
        fontSize: 13,
        fontWeight: 600,
        lineHeight: '20px',
      }}
    >
      &#9654; Начало
    </div>
  );
}

// ─── EndBlock ───────────────────────────────────────────────────

export function EndBlock({ onClick }: SimpleBlockProps) {
  return (
    <div
      onClick={onClick}
      className="cursor-pointer select-none"
      style={{
        width: 120,
        padding: '8px 0',
        borderRadius: 20,
        backgroundColor: '#4caf50',
        color: '#fff',
        textAlign: 'center',
        fontSize: 13,
        fontWeight: 600,
        lineHeight: '20px',
      }}
    >
      &#9632; Конец
    </div>
  );
}

// ─── MessageBlock ───────────────────────────────────────────────

export function MessageBlock({ node, onClick }: BlockProps) {
  const text = (node.data.text ?? '') as string;
  const image = node.data.image as string | undefined;
  const buttons = (node.data.buttons ?? []) as Array<{ text: string }>;
  const preview = truncate(text, 3, 120);

  return (
    <div
      onClick={() => onClick?.(node.id)}
      className="cursor-pointer select-none rounded-xl overflow-hidden"
      style={{
        width: 200,
        backgroundColor: '#fff8e1',
        border: '2px solid #ffb300',
      }}
    >
      {/* Header */}
      <div
        className="flex items-center gap-1.5 px-3 py-2"
        style={{ borderBottom: '1px solid #ffe082' }}
      >
        <span style={{ fontSize: 13 }}>&#128172;</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#e65100' }}>Сообщение</span>
        {buttons.length > 0 && (
          <span
            className="ml-auto"
            style={{
              fontSize: 10,
              color: '#ff8f00',
              backgroundColor: '#fff3e0',
              borderRadius: 10,
              padding: '1px 6px',
            }}
          >
            {buttons.length} кн.
          </span>
        )}
      </div>

      {/* Image indicator */}
      {image && (
        <div className="px-2 pt-1.5">
          <div
            className="flex items-center justify-center rounded"
            style={{
              height: 28,
              backgroundColor: '#ffe0b2',
              fontSize: 10,
              color: '#e65100',
            }}
          >
            &#128444; Картинка
          </div>
        </div>
      )}

      {/* Text preview */}
      <div className="px-3 py-2">
        <p
          style={{
            fontSize: 11,
            color: '#4e342e',
            lineHeight: '16px',
            margin: 0,
            whiteSpace: 'pre-wrap',
            overflow: 'hidden',
            display: '-webkit-box',
            WebkitLineClamp: 3,
            WebkitBoxOrient: 'vertical',
          }}
        >
          {preview || (
            <span style={{ fontStyle: 'italic', color: '#bcaaa4' }}>Пустое сообщение</span>
          )}
        </p>
      </div>
    </div>
  );
}

// ─── ButtonBlock ────────────────────────────────────────────────

interface ButtonBlockProps {
  text: string;
  action: string;
  target?: string;
  url?: string;
  onClick?: () => void;
}

export function ButtonBlock({ text, action, target, url, onClick }: ButtonBlockProps) {
  return (
    <div
      onClick={onClick}
      className="cursor-pointer select-none rounded-lg overflow-hidden"
      style={{
        width: 130,
        backgroundColor: '#e3f2fd',
        border: '2px solid #42a5f5',
        textAlign: 'center',
      }}
    >
      <div className="px-2 py-2">
        <p
          style={{
            fontSize: 12,
            fontWeight: 600,
            color: '#1565c0',
            lineHeight: '16px',
            margin: 0,
            overflow: 'hidden',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
          }}
        >
          {text || '---'}
        </p>
      </div>
      {action === 'goto' && target && (
        <div
          style={{
            fontSize: 9,
            color: '#90a4ae',
            padding: '2px 4px 4px',
            borderTop: '1px solid #bbdefb',
          }}
        >
          &#8594; {target.length > 16 ? target.slice(0, 16) + '...' : target}
        </div>
      )}
      {action === 'url' && url && (
        <div
          style={{
            fontSize: 9,
            color: '#90a4ae',
            padding: '2px 4px 4px',
            borderTop: '1px solid #bbdefb',
          }}
        >
          &#128279; URL
        </div>
      )}
    </div>
  );
}

// ─── ConditionBlock ─────────────────────────────────────────────

export function ConditionBlock({ node, onClick }: BlockProps) {
  const rules = (node.data.rules ?? []) as Array<{ condition: string; target: string }>;
  const defaultTarget = node.data.default as string | undefined;

  return (
    <div
      onClick={() => onClick?.(node.id)}
      className="cursor-pointer select-none rounded-xl overflow-hidden"
      style={{
        width: 200,
        backgroundColor: '#fff3e0',
        border: '2px solid #ff9800',
      }}
    >
      <div
        className="flex items-center gap-1.5 px-3 py-2"
        style={{ borderBottom: '1px solid #ffe0b2' }}
      >
        <span style={{ fontSize: 13 }}>&#128256;</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#e65100' }}>Условие</span>
      </div>

      <div className="px-2 py-2 space-y-1">
        {rules.map((rule, i) => (
          <div key={i} className="flex items-center gap-1">
            <span style={{ fontSize: 9, color: '#e65100', fontWeight: 600, flexShrink: 0 }}>
              если
            </span>
            <span
              className="truncate"
              style={{
                fontSize: 10,
                color: '#bf360c',
                fontFamily: 'monospace',
                flex: 1,
                backgroundColor: '#fff',
                border: '1px solid #ffcc80',
                borderRadius: 4,
                padding: '1px 4px',
              }}
            >
              {rule.condition}
            </span>
          </div>
        ))}
        {defaultTarget && (
          <div className="flex items-center gap-1">
            <span style={{ fontSize: 9, color: '#9e9e9e', fontWeight: 600, flexShrink: 0 }}>
              иначе
            </span>
            <span style={{ fontSize: 9, color: '#ffa726', fontFamily: 'monospace' }}>
              &#8594;{' '}
              {defaultTarget.length > 12 ? defaultTarget.slice(0, 12) + '...' : defaultTarget}
            </span>
          </div>
        )}
        {rules.length === 0 && !defaultTarget && (
          <p style={{ fontSize: 10, fontStyle: 'italic', color: '#ffb74d', margin: 0 }}>
            Нет условий
          </p>
        )}
      </div>
    </div>
  );
}

// ─── ActionBlock ────────────────────────────────────────────────

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

export function ActionBlock({ node, onClick }: BlockProps) {
  const actions = (node.data.actions ?? []) as Array<{
    type: string;
    variable?: string;
    value?: unknown;
  }>;

  return (
    <div
      onClick={() => onClick?.(node.id)}
      className="cursor-pointer select-none rounded-xl overflow-hidden"
      style={{
        width: 200,
        backgroundColor: '#f3e5f5',
        border: '2px solid #ab47bc',
      }}
    >
      <div
        className="flex items-center gap-1.5 px-3 py-2"
        style={{ borderBottom: '1px solid #ce93d8' }}
      >
        <span style={{ fontSize: 13 }}>&#9889;</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#6a1b9a' }}>Действие</span>
      </div>

      <div className="px-2 py-2 space-y-1">
        {actions.length === 0 && (
          <p style={{ fontSize: 10, fontStyle: 'italic', color: '#ba68c8', margin: 0 }}>
            Нет действий
          </p>
        )}
        {actions.map((action, i) => (
          <div
            key={i}
            className="rounded"
            style={{
              backgroundColor: '#fff',
              border: '1px solid #e1bee7',
              padding: '2px 6px',
              fontSize: 10,
              color: '#6a1b9a',
            }}
          >
            <span
              className="font-medium"
              dangerouslySetInnerHTML={{
                __html: ACTION_LABELS[action.type] ?? action.type,
              }}
            />
            {action.variable && (
              <span
                style={{ marginLeft: 4, color: '#9c27b0', fontFamily: 'monospace', fontSize: 9 }}
              >
                {action.variable}
                {action.value !== undefined
                  ? ` = ${typeof action.value === 'object' ? JSON.stringify(action.value) : String(action.value as string | number | boolean)}`
                  : ''}
              </span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── InputBlock ─────────────────────────────────────────────────

export function InputBlock({ node, onClick }: BlockProps) {
  const prompt = (node.data.prompt ?? '') as string;
  const inputType = (node.data.inputType ?? 'text') as string;
  const saveAs = (node.data.saveAs ?? '') as string;

  const typeLabels: Record<string, string> = {
    text: 'Текст',
    phone: 'Телефон',
    email: 'Email',
    number: 'Число',
  };

  return (
    <div
      onClick={() => onClick?.(node.id)}
      className="cursor-pointer select-none rounded-xl overflow-hidden"
      style={{
        width: 200,
        backgroundColor: '#e0f2f1',
        border: '2px solid #26a69a',
      }}
    >
      <div
        className="flex items-center gap-1.5 px-3 py-2"
        style={{ borderBottom: '1px solid #80cbc4' }}
      >
        <span style={{ fontSize: 13 }}>&#9999;&#65039;</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#004d40' }}>Ввод данных</span>
        <span
          className="ml-auto"
          style={{
            fontSize: 9,
            color: '#00897b',
            backgroundColor: '#b2dfdb',
            borderRadius: 10,
            padding: '1px 6px',
          }}
        >
          {typeLabels[inputType] ?? inputType}
        </span>
      </div>

      <div className="px-3 py-2">
        <p style={{ fontSize: 11, color: '#00695c', lineHeight: '15px', margin: 0 }}>
          {prompt || (
            <span style={{ fontStyle: 'italic', color: '#80cbc4' }}>Введите запрос...</span>
          )}
        </p>
        {saveAs && (
          <p style={{ marginTop: 4, fontSize: 9, color: '#26a69a', fontFamily: 'monospace' }}>
            &#8594; {saveAs}
          </p>
        )}
      </div>
    </div>
  );
}

// ─── DelayBlock ─────────────────────────────────────────────────

export function DelayBlock({ node, onClick }: BlockProps) {
  const duration = (node.data.duration ?? '?') as string;
  const cancelOn = node.data.cancelOn as string | undefined;

  return (
    <div
      onClick={() => onClick?.(node.id)}
      className="cursor-pointer select-none rounded-xl overflow-hidden"
      style={{
        width: 200,
        backgroundColor: '#fbe9e7',
        border: '2px solid #ff7043',
      }}
    >
      <div
        className="flex items-center gap-1.5 px-3 py-2"
        style={{ borderBottom: '1px solid #ffab91' }}
      >
        <span style={{ fontSize: 13 }}>&#9200;</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#bf360c' }}>Задержка</span>
      </div>

      <div className="px-3 py-2">
        <p
          style={{
            fontSize: 14,
            fontWeight: 700,
            color: '#d84315',
            textAlign: 'center',
            margin: 0,
          }}
        >
          {duration}
        </p>
        {cancelOn && (
          <p
            style={{
              marginTop: 4,
              fontSize: 9,
              color: '#e64a19',
              backgroundColor: '#fff',
              border: '1px solid #ffccbc',
              borderRadius: 6,
              padding: '2px 6px',
            }}
          >
            Отмена: {cancelOn}
          </p>
        )}
      </div>
    </div>
  );
}

// ─── ReferralBlock ──────────────────────────────────────────────

export function ReferralBlock({ node, onClick }: BlockProps) {
  const targetCount = (node.data.targetCount ?? 0) as number;
  const trackVar = (node.data.trackVariable ?? 'invited_count') as string;

  return (
    <div
      onClick={() => onClick?.(node.id)}
      className="cursor-pointer select-none rounded-xl overflow-hidden"
      style={{
        width: 200,
        backgroundColor: '#fce4ec',
        border: '2px solid #ec407a',
      }}
    >
      <div
        className="flex items-center gap-1.5 px-3 py-2"
        style={{ borderBottom: '1px solid #f48fb1' }}
      >
        <span style={{ fontSize: 13 }}>&#127873;</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#880e4f' }}>Реферал</span>
      </div>

      <div className="px-2 py-2 space-y-1">
        <div
          className="rounded"
          style={{
            backgroundColor: '#fff',
            border: '1px solid #f8bbd0',
            padding: '2px 6px',
            fontSize: 11,
            color: '#ad1457',
          }}
        >
          Цель: <span style={{ fontWeight: 700 }}>{targetCount}</span> друзей
        </div>
        <div
          className="rounded"
          style={{
            backgroundColor: '#fff',
            border: '1px solid #f8bbd0',
            padding: '2px 6px',
            fontSize: 10,
            color: '#c2185b',
            fontFamily: 'monospace',
          }}
        >
          {trackVar}
        </div>
      </div>
    </div>
  );
}

// ─── CollapsedBlock ─────────────────────────────────────────────

export function CollapsedBlock({ onClick }: SimpleBlockProps) {
  return (
    <div
      onClick={onClick}
      className="cursor-pointer select-none rounded-lg"
      style={{
        width: 160,
        padding: '10px 12px',
        border: '2px dashed #bdbdbd',
        backgroundColor: '#fafafa',
        textAlign: 'center',
        fontSize: 11,
        color: '#9e9e9e',
      }}
    >
      нажмите, чтобы развернуть
    </div>
  );
}
