/**
 * Dialogs - Handles extension UI dialogs
 */

export class DialogHandler {
  constructor(container, agentClient) {
    this.container = container;
    this.agentClient = agentClient;
    this.currentDialog = null;
    this.timeoutId = null;
  }

  showSelect(request) {
    this.clearCurrentDialog();

    const { id, title, options, timeout } = request;

    const dialog = document.createElement('div');
    dialog.className = 'dialog';
    dialog.innerHTML = `
      <div class="dialog-title">${this.escapeHtml(title || 'Select an option')}</div>
      <div class="dialog-options" id="dialog-options"></div>
      <div class="dialog-actions">
        <button id="dialog-cancel">Cancel</button>
      </div>
    `;

    const optionsContainer = dialog.querySelector('#dialog-options');
    
    (options || []).forEach(option => {
      const optionDiv = document.createElement('div');
      optionDiv.className = 'dialog-option';
      optionDiv.textContent = option;
      optionDiv.onclick = () => {
        this.respond(id, { value: option });
      };
      optionsContainer.appendChild(optionDiv);
    });

    dialog.querySelector('#dialog-cancel').onclick = () => {
      this.respond(id, { cancelled: true });
    };

    this.showDialog(dialog, timeout, id);
  }

  showConfirm(request) {
    this.clearCurrentDialog();

    const { id, title, message, timeout } = request;

    const dialog = document.createElement('div');
    dialog.className = 'dialog';
    dialog.innerHTML = `
      <div class="dialog-title">${this.escapeHtml(title || 'Confirm')}</div>
      ${message ? `<div class="dialog-message">${this.escapeHtml(message)}</div>` : ''}
      <div class="dialog-actions">
        <button id="dialog-no">No</button>
        <button id="dialog-yes">Yes</button>
      </div>
    `;

    dialog.querySelector('#dialog-yes').onclick = () => {
      this.respond(id, { confirmed: true });
    };

    dialog.querySelector('#dialog-no').onclick = () => {
      this.respond(id, { confirmed: false });
    };

    this.showDialog(dialog, timeout, id);
  }

  showInput(request) {
    this.clearCurrentDialog();

    const { id, title, placeholder, timeout } = request;

    const dialog = document.createElement('div');
    dialog.className = 'dialog';
    dialog.innerHTML = `
      <div class="dialog-title">${this.escapeHtml(title || 'Input')}</div>
      <input type="text" class="dialog-input" id="dialog-input" placeholder="${this.escapeHtml(placeholder || '')}" />
      <div class="dialog-actions">
        <button id="dialog-cancel">Cancel</button>
        <button id="dialog-submit">Submit</button>
      </div>
    `;

    const input = dialog.querySelector('#dialog-input');
    
    const submit = () => {
      const value = input.value.trim();
      this.respond(id, value ? { value } : { cancelled: true });
    };

    input.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') submit();
    });

    dialog.querySelector('#dialog-submit').onclick = submit;
    dialog.querySelector('#dialog-cancel').onclick = () => {
      this.respond(id, { cancelled: true });
    };

    this.showDialog(dialog, timeout, id);
    
    // Focus input after a short delay
    setTimeout(() => input.focus(), 100);
  }

  showEditor(request) {
    this.clearCurrentDialog();

    const { id, title, prefill, timeout } = request;

    const dialog = document.createElement('div');
    dialog.className = 'dialog';
    dialog.innerHTML = `
      <div class="dialog-title">${this.escapeHtml(title || 'Editor')}</div>
      <textarea class="dialog-textarea" id="dialog-textarea">${this.escapeHtml(prefill || '')}</textarea>
      <div class="dialog-actions">
        <button id="dialog-cancel">Cancel</button>
        <button id="dialog-save">Save</button>
      </div>
    `;

    const textarea = dialog.querySelector('#dialog-textarea');

    dialog.querySelector('#dialog-save').onclick = () => {
      const value = textarea.value;
      this.respond(id, value ? { value } : { cancelled: true });
    };

    dialog.querySelector('#dialog-cancel').onclick = () => {
      this.respond(id, { cancelled: true });
    };

    this.showDialog(dialog, timeout, id);
    
    // Focus textarea after a short delay
    setTimeout(() => textarea.focus(), 100);
  }

  showAskUser(request) {
    this.clearCurrentDialog();

    const {
      id,
      question,
      context,
      options = [],
      allowMultiple = false,
      allowFreeform = true,
      timeout,
    } = request;

    const dialog = document.createElement('div');
    dialog.className = 'dialog dialog-ask-user';

    const header = document.createElement('div');
    header.className = 'dialog-ask-user-header';
    header.innerHTML = `<div class="dialog-ask-user-badge">ask_user</div>`;
    dialog.appendChild(header);

    const title = document.createElement('div');
    title.className = 'dialog-title';
    title.textContent = question || 'Question';
    dialog.appendChild(title);

    if (context) {
      const contextEl = document.createElement('div');
      contextEl.className = 'dialog-ask-user-context';
      contextEl.textContent = context;
      dialog.appendChild(contextEl);
    }

    const optionsContainer = document.createElement('div');
    optionsContainer.className = 'dialog-ask-user-options';
    if (options.length === 0) {
      optionsContainer.classList.add('hidden');
    }
    dialog.appendChild(optionsContainer);

    const freeformPanel = document.createElement('div');
    freeformPanel.className = 'dialog-ask-user-freeform hidden';
    freeformPanel.innerHTML = `
      <div class="dialog-ask-user-freeform-label">Your answer</div>
      <textarea class="dialog-textarea" id="ask-user-freeform"></textarea>
    `;
    dialog.appendChild(freeformPanel);

    const actions = document.createElement('div');
    actions.className = 'dialog-actions';
    actions.innerHTML = `
      <button type="button" id="ask-user-back" class="hidden">Back</button>
      <button type="button" id="ask-user-cancel">Cancel</button>
      <button type="button" id="ask-user-submit" class="btn-primary">Submit</button>
    `;
    dialog.appendChild(actions);

    const backBtn = actions.querySelector('#ask-user-back');
    const submitBtn = actions.querySelector('#ask-user-submit');
    const cancelBtn = actions.querySelector('#ask-user-cancel');
    const freeformTextarea = freeformPanel.querySelector('#ask-user-freeform');

    const checked = new Set();
    let freeformMode = false;

    const updateSubmitVisibility = () => {
      submitBtn.classList.toggle('hidden', !allowMultiple && !freeformMode);
    };

    const updateBackVisibility = () => {
      backBtn.classList.toggle('hidden', !freeformMode || options.length === 0);
    };

    const showOptions = () => {
      freeformMode = false;
      freeformPanel.classList.add('hidden');
      if (options.length > 0) {
        optionsContainer.classList.remove('hidden');
      }
      updateSubmitVisibility();
      updateBackVisibility();
    };

    const showFreeform = () => {
      freeformMode = true;
      freeformPanel.classList.remove('hidden');
      optionsContainer.classList.add('hidden');
      updateSubmitVisibility();
      updateBackVisibility();
      setTimeout(() => freeformTextarea.focus(), 50);
    };

    const submitFreeform = () => {
      const text = freeformTextarea.value.trim();
      if (!text) {
        return;
      }
      this.respondAskUser(id, { kind: 'freeform', text });
    };

    const submitSelection = () => {
      const selections = options
        .map((option, index) => (checked.has(index) ? option.title : null))
        .filter(Boolean);
      if (selections.length === 0) {
        return;
      }
      this.respondAskUser(id, { kind: 'selection', selections });
    };

    const renderOptions = () => {
      optionsContainer.innerHTML = '';
      options.forEach((option, index) => {
        const row = document.createElement('button');
        row.type = 'button';
        row.className = 'dialog-ask-user-option';
        if (allowMultiple && checked.has(index)) {
          row.classList.add('selected');
        }

        const marker = document.createElement('span');
        marker.className = 'dialog-ask-user-marker';
        marker.textContent = allowMultiple ? (checked.has(index) ? '[x]' : '[ ]') : String(index + 1);
        row.appendChild(marker);

        const body = document.createElement('span');
        body.className = 'dialog-ask-user-option-body';
        const titleEl = document.createElement('span');
        titleEl.className = 'dialog-ask-user-option-title';
        titleEl.textContent = option.title;
        body.appendChild(titleEl);
        if (option.description) {
          const descEl = document.createElement('span');
          descEl.className = 'dialog-ask-user-option-desc';
          descEl.textContent = option.description;
          body.appendChild(descEl);
        }
        row.appendChild(body);

        row.onclick = () => {
          if (allowMultiple) {
            if (checked.has(index)) {
              checked.delete(index);
            } else {
              checked.add(index);
            }
            renderOptions();
            return;
          }
          this.respondAskUser(id, { kind: 'selection', selections: [option.title] });
        };

        optionsContainer.appendChild(row);
      });

      if (allowFreeform) {
        const freeformRow = document.createElement('button');
        freeformRow.type = 'button';
        freeformRow.className = 'dialog-ask-user-option dialog-ask-user-option-freeform';
        freeformRow.innerHTML = `
          <span class="dialog-ask-user-marker">...</span>
          <span class="dialog-ask-user-option-body">
            <span class="dialog-ask-user-option-title">Type custom response</span>
            <span class="dialog-ask-user-option-desc">Write your own answer</span>
          </span>
        `;
        freeformRow.onclick = () => showFreeform();
        optionsContainer.appendChild(freeformRow);
      }
    };

    renderOptions();
    if (options.length === 0) {
      showFreeform();
    } else {
      updateSubmitVisibility();
    }

    submitBtn.onclick = () => {
      if (freeformMode) {
        submitFreeform();
        return;
      }
      submitSelection();
    };

    cancelBtn.onclick = () => {
      this.respond(id, { cancelled: true });
    };

    backBtn.onclick = () => {
      showOptions();
    };

    freeformTextarea.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && options.length > 0) {
        e.preventDefault();
        showOptions();
        return;
      }
      if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        submitFreeform();
      }
    });

    this.showDialog(dialog, timeout, id);
  }

  showNotification(request) {
    const { message, notifyType } = request;
    
    // Create a temporary notification element
    const notification = document.createElement('div');
    notification.className = 'error-message';
    notification.textContent = `${notifyType === 'error' ? '⚠️' : notifyType === 'warning' ? '⚠️' : 'ℹ️'} ${message}`;
    
    // Add to messages container temporarily
    const messagesContainer = document.getElementById('messages');
    if (messagesContainer) {
      messagesContainer.appendChild(notification);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
      
      // Remove after 5 seconds
      setTimeout(() => {
        notification.remove();
      }, 5000);
    }
  }

  showDialog(dialogElement, timeout, requestId) {
    this.currentDialog = dialogElement;
    this.container.innerHTML = '';
    this.container.appendChild(dialogElement);
    this.container.classList.remove('hidden');

    // Set up timeout if specified
    if (timeout) {
      this.timeoutId = setTimeout(() => {
        this.respond(requestId, { cancelled: true });
      }, timeout);
    }
  }

  clearCurrentDialog() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    }
    
    this.container.innerHTML = '';
    this.container.classList.add('hidden');
    this.currentDialog = null;
  }

  respond(id, response) {
    this.clearCurrentDialog();
    this.agentClient.send({
      type: 'extension_ui_response',
      id,
      ...response
    });
  }

  respondAskUser(id, askUserResult) {
    this.clearCurrentDialog();
    this.agentClient.send({
      type: 'extension_ui_response',
      id,
      askUserResult,
    });
  }

  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}
