/* eslint-disable @typescript-eslint/member-ordering */
import {
  AfterViewInit,
  Component,
  ElementRef,
  HostListener,
  inject,
  input,
  output
} from '@angular/core';
import { ThemeNodeDirective } from '../../../domains/theme';
import { ViewportService } from '../../../core/platform';
import { AppI18nService, APP_TRANSLATE_IMPORTS } from '../../../core/i18n';
import {
  findPrimaryDialogField,
  shouldSelectOnFocus,
  shouldSubmitOnEnter
} from '../../directives/form-field-focus.rules';
import { BottomSheetComponent } from '../bottom-sheet/bottom-sheet.component';
import { ModalBackdropComponent } from '../modal-backdrop/modal-backdrop.component';

@Component({
  selector: 'app-confirm-dialog',
  standalone: true,
  imports: [
    ThemeNodeDirective,
    BottomSheetComponent,
    ModalBackdropComponent,
    ...APP_TRANSLATE_IMPORTS
  ],
  templateUrl: './confirm-dialog.component.html',
  host: {
    style: 'display: contents;'
  }
})
export class ConfirmDialogComponent implements AfterViewInit {
  private readonly appI18n = inject(AppI18nService);

  title = input.required<string>();
  confirmLabel = input<string>(this.appI18n.instant('shared.dialog.confirm'));
  cancelLabel = input<string>(this.appI18n.instant('shared.dialog.cancel'));
  variant = input<'primary' | 'danger'>('primary');
  widthClass = input<string>('w-[320px]');
  confirmed = output<undefined>();
  cancelled = output<undefined>();

  readonly isMobile = inject(ViewportService).isMobile;

  @HostListener('document:keydown.escape')
  onEscape(): void {
    this.cancelled.emit(undefined);
  }

  @HostListener('keydown.enter', ['$event'])
  onEnter(event: Event): void {
    if (!(event instanceof KeyboardEvent) || !shouldSubmitOnEnter(event)) {
      return;
    }

    event.preventDefault();
    this.confirmed.emit(undefined);
  }

  ngAfterViewInit(): void {
    requestAnimationFrame(() => this.focusPrimaryField());
  }

  private readonly hostRef = inject<ElementRef<HTMLElement>>(ElementRef);

  private focusPrimaryField(): void {
    const field = findPrimaryDialogField(this.hostRef.nativeElement);

    if (!field) {
      return;
    }

    field.focus();

    if (shouldSelectOnFocus({
      type: field instanceof HTMLInputElement ? field.type : 'textarea',
      value: field.value
    })) {
      field.select();
    }
  }
}
