import { customElement } from 'lit/decorators.js'
import Element from './internals/DomainAutoFieldsDialog.js'
import styles from './internals/styles/DomainAutoFieldsDialog.js'
import typography from '../styles/m3/typography.module.js'
import { DialogBuilder } from '../builders/DialogBuilder.js'
import { AutoFieldsSelectionResult } from './types.js'

import '../md/button/ui-button.js'
import '../md/checkbox/ui-checkbox.js'
import '../md/list/ui-list.js'
import '../md/list/ui-list-item.js'

@customElement('domain-auto-fields-dialog')
export class DomainAutoFieldsDialog extends Element {
  static override styles = [styles, typography]
}

declare global {
  interface HTMLElementTagNameMap {
    'domain-auto-fields-dialog': DomainAutoFieldsDialog
  }
}

/**
 * Creates and opens an auto fields selection dialog
 * @param parent The parent activity or fragment (optional)
 * @param onSelect Callback when fields are selected
 * @returns The dialog builder instance
 */
export function openAutoFieldsDialog(onSelect: (selectedFields: string[]) => void): DialogBuilder {
  // Create the content component
  const content = new DomainAutoFieldsDialog()

  // Create the dialog using DialogBuilder
  const dialog = new DialogBuilder().setTitle('Add Auto Fields').setBody(content).setRenderAs('picker').setModal(true)

  // Listen for selection events
  content.addEventListener('select', (event) => {
    const { selectedFields } = (event as CustomEvent<AutoFieldsSelectionResult>).detail
    onSelect(selectedFields)
    dialog.close()
  })

  // Listen for cancel events
  content.addEventListener('cancel', () => {
    dialog.close()
  })

  // Open the dialog
  dialog.open()

  return dialog
}

export { AutoFieldCategory, AutoFieldDefinition, AutoFieldsSelectionResult } from './types.js'
