'use client';

import { X, Trash2 } from 'lucide-react';
import type { Node } from '@xyflow/react';

interface Props {
  node: Node;
  onUpdate: (nodeId: string, data: Record<string, unknown>) => void;
  onDelete: (nodeId: string) => void;
  onClose: () => void;
}

const inputClass = 'w-full rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm';
const labelClass = 'block text-xs font-medium text-gray-600 mb-1';

export function NodePropertiesPanel({ node, onUpdate, onDelete, onClose }: Props) {
  const data = node.data;
  const nodeType = (data.nodeType as string) ?? '';

  const update = (key: string, value: unknown) => {
    onUpdate(node.id, { [key]: value });
  };

  return (
    <div className="absolute right-0 top-0 h-full w-[320px] bg-white border-l border-gray-200 shadow-xl z-10 flex flex-col">
      {/* Header */}
      <div className="flex items-center justify-between border-b px-4 py-3">
        <div>
          <p className="text-sm font-semibold text-gray-800 capitalize">{nodeType}</p>
          <p className="text-xs text-gray-400 font-mono">{node.id}</p>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={() => {
              if (confirm('Удалить ноду?')) onDelete(node.id);
            }}
            className="rounded p-1 text-gray-400 hover:bg-red-50 hover:text-red-500"
            title="Удалить"
          >
            <Trash2 className="h-4 w-4" />
          </button>
          <button onClick={onClose} className="rounded p-1 text-gray-400 hover:bg-gray-100">
            <X className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Body */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {/* Common: next */}
        <div>
          <label className={labelClass}>Next (ID следующей ноды)</label>
          <input
            type="text"
            value={(data.next as string) ?? ''}
            onChange={(e) => update('next', e.target.value || null)}
            placeholder="node_id"
            className={inputClass + ' font-mono text-xs'}
          />
        </div>

        {/* Message node */}
        {nodeType === 'message' && (
          <>
            <div>
              <label className={labelClass}>Текст сообщения (HTML)</label>
              <textarea
                value={(data.text as string) ?? ''}
                onChange={(e) => update('text', e.target.value)}
                rows={5}
                className={inputClass + ' font-mono text-xs'}
              />
            </div>
            <div>
              <label className={labelClass}>Кнопки (JSON)</label>
              <textarea
                value={JSON.stringify(data.buttons ?? [], null, 2)}
                onChange={(e) => {
                  try {
                    update('buttons', JSON.parse(e.target.value));
                  } catch {
                    /* skip */
                  }
                }}
                rows={4}
                className={inputClass + ' font-mono text-xs'}
              />
            </div>
            <div>
              <label className={labelClass}>Layout кнопок</label>
              <select
                value={(data.buttonsLayout as string) ?? 'inline'}
                onChange={(e) => update('buttonsLayout', e.target.value)}
                className={inputClass}
              >
                <option value="inline">Inline</option>
                <option value="reply">Reply</option>
                <option value="remove">Remove</option>
              </select>
            </div>
          </>
        )}

        {/* Condition node */}
        {nodeType === 'condition' && (
          <>
            <div>
              <label className={labelClass}>Правила (JSON)</label>
              <textarea
                value={JSON.stringify(data.rules ?? [], null, 2)}
                onChange={(e) => {
                  try {
                    update('rules', JSON.parse(e.target.value));
                  } catch {
                    /* skip */
                  }
                }}
                rows={6}
                className={inputClass + ' font-mono text-xs'}
              />
              <p className="text-[10px] text-gray-400 mt-1">
                {'[{ "condition": "var >= 2", "target": "node_id" }]'}
              </p>
            </div>
            <div>
              <label className={labelClass}>Default (ID ноды по умолчанию)</label>
              <input
                type="text"
                value={(data.default as string) ?? ''}
                onChange={(e) => update('default', e.target.value || null)}
                className={inputClass + ' font-mono text-xs'}
              />
            </div>
          </>
        )}

        {/* Action node */}
        {nodeType === 'action' && (
          <div>
            <label className={labelClass}>Действия (JSON)</label>
            <textarea
              value={JSON.stringify(data.actions ?? [], null, 2)}
              onChange={(e) => {
                try {
                  update('actions', JSON.parse(e.target.value));
                } catch {
                  /* skip */
                }
              }}
              rows={8}
              className={inputClass + ' font-mono text-xs'}
            />
            <p className="text-[10px] text-gray-400 mt-1">
              {'[{ "type": "set_variable", "variable": "x", "value": 1 }]'}
            </p>
          </div>
        )}

        {/* Input node */}
        {nodeType === 'input' && (
          <>
            <div>
              <label className={labelClass}>Промпт</label>
              <textarea
                value={(data.prompt as string) ?? ''}
                onChange={(e) => update('prompt', e.target.value)}
                rows={3}
                className={inputClass}
              />
            </div>
            <div>
              <label className={labelClass}>Тип ввода</label>
              <select
                value={(data.inputType as string) ?? 'text'}
                onChange={(e) => update('inputType', e.target.value)}
                className={inputClass}
              >
                <option value="text">Текст</option>
                <option value="phone">Телефон</option>
                <option value="email">Email</option>
                <option value="choice">Выбор</option>
              </select>
            </div>
            <div>
              <label className={labelClass}>Сохранить в переменную</label>
              <input
                type="text"
                value={(data.saveAs as string) ?? ''}
                onChange={(e) => update('saveAs', e.target.value)}
                className={inputClass + ' font-mono'}
              />
            </div>
          </>
        )}

        {/* Delay node */}
        {nodeType === 'delay' && (
          <>
            <div>
              <label className={labelClass}>Длительность (10m, 1h, 24h, 3d)</label>
              <input
                type="text"
                value={(data.duration as string) ?? ''}
                onChange={(e) => update('duration', e.target.value)}
                className={inputClass + ' font-mono'}
              />
            </div>
            <div>
              <label className={labelClass}>Отменить при условии</label>
              <input
                type="text"
                value={(data.cancelOn as string) ?? ''}
                onChange={(e) => update('cancelOn', e.target.value)}
                placeholder="invited_count >= 2"
                className={inputClass + ' font-mono text-xs'}
              />
            </div>
          </>
        )}

        {/* Referral node */}
        {nodeType === 'referral' && (
          <>
            <div>
              <label className={labelClass}>Переменная для подсчёта</label>
              <input
                type="text"
                value={(data.trackVariable as string) ?? ''}
                onChange={(e) => update('trackVariable', e.target.value)}
                className={inputClass + ' font-mono'}
              />
            </div>
            <div>
              <label className={labelClass}>Целевое количество</label>
              <input
                type="number"
                value={(data.targetCount as number) ?? 2}
                onChange={(e) => update('targetCount', parseInt(e.target.value, 10))}
                className={inputClass}
              />
            </div>
            <div>
              <label className={labelClass}>Нода при достижении цели</label>
              <input
                type="text"
                value={(data.onReach as string) ?? ''}
                onChange={(e) => update('onReach', e.target.value)}
                className={inputClass + ' font-mono text-xs'}
              />
            </div>
            <div>
              <label className={labelClass}>Стартовая нода для друга</label>
              <input
                type="text"
                value={(data.friendStartNode as string) ?? ''}
                onChange={(e) => update('friendStartNode', e.target.value)}
                className={inputClass + ' font-mono text-xs'}
              />
            </div>
          </>
        )}
      </div>
    </div>
  );
}
