import { useState } from 'react';
import { getDescendants } from '../utils/tree';
import { useConversation } from '../context/ConversationContext';

export default function BranchDialog({ node, onClose, onConfirm }) {
  const { state } = useConversation();
  const conv = state.conversations[state.activeConversationId];
  const [editedMessage, setEditedMessage] = useState(node.userMessage);

  const descendantCount = conv
    ? getDescendants(conv.nodes, node.id).length
    : 0;

  const handleConfirm = () => {
    onConfirm(node.id, editedMessage);
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h3>⑂ Create Branch</h3>
          <p>
            Edit the prompt below to create an alternate conversation path.
          </p>
        </div>

        <div className="modal-body">
          <div>
            <div className="modal-label">Branching from this prompt</div>
            <textarea
              className="modal-textarea"
              value={editedMessage}
              onChange={(e) => setEditedMessage(e.target.value)}
              rows={3}
              autoFocus
            />
          </div>

          {descendantCount > 0 && (
            <div className="modal-info">
              <span>⚠️</span>
              <span>
                This will re-generate {descendantCount} downstream{' '}
                {descendantCount === 1 ? 'node' : 'nodes'} on this new
                branch. Each node will be re-run sequentially.
              </span>
            </div>
          )}
        </div>

        <div className="modal-footer">
          <button className="btn-secondary" onClick={onClose}>
            Cancel
          </button>
          <button
            className="btn-primary"
            onClick={handleConfirm}
            disabled={!editedMessage.trim()}
          >
            ⑂ Branch & Re-generate
          </button>
        </div>
      </div>
    </div>
  );
}
