import { AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, inject, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CommonDialogService } from '@core/common-dialog/common-dialog.service';
import { ManagePageComponent } from '../manage-page/manage-page.component';
import { TranslationService } from '@core/services/translation.service';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { PageStore } from '../page-store';
import { MatSort } from '@angular/material/sort';
import { PageResource } from '@core/domain-classes/page-resource';
import { Page } from '@core/domain-classes/page';

@Component({
  templateUrl: './page-list-presentation.component.html',
  styleUrls: ['./page-list-presentation.component.scss']

})
export class PageListPresentationComponent implements OnInit, AfterViewInit {
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  displayedColumns: string[] = ['action', 'name', 'url'];
  pageStore = inject(PageStore);
  loading = this.pageStore.isLoading;
  translationService = inject(TranslationService);
  pageResource = new PageResource();
  dialog: MatDialog = inject(MatDialog);
  commonDialogService = inject(CommonDialogService);
  nameFilterCtl: FormControl<string> = new FormControl<string>('');
  urlFilterCtl: FormControl<string> = new FormControl<string>('');

  ngOnInit(): void {
    this.nameFilterCtl.valueChanges
      .pipe(
        debounceTime(400),
        distinctUntilChanged()
      )
      .subscribe(c => {
        this.pageStore.sortFilterPages(this.sort.direction, this.sort.active ?? 'name', this.urlFilterCtl.value, this.nameFilterCtl.value);
      });
    this.urlFilterCtl.valueChanges
      .pipe(
        debounceTime(400),
        distinctUntilChanged()
      )
      .subscribe(c => {
        this.pageStore.sortFilterPages(this.sort.direction, this.sort.active ?? 'name', this.urlFilterCtl.value, this.nameFilterCtl.value);
      })
  }
  ngAfterViewInit(): void {
    this.sort.sortChange
      .subscribe(() => {
        this.pageStore.sortFilterPages(this.sort.direction, this.sort.active ?? 'name', this.urlFilterCtl.value, this.nameFilterCtl.value);
      });
  }

  deletePage(page: Page): void {
    this.commonDialogService
      .deleteConformationDialog(`${this.translationService.getValue('ARE_YOU_SURE_YOU_WANT_TO_DELETE')} ${page.name}`)
      .subscribe(isTrue => {
        if (isTrue) {
          this.pageStore.deletePageById(page.id);
        }
      });
  }
  managePage(page?: Page): void {
    this.dialog.open(ManagePageComponent, {
      width: '320px',
      data: Object.assign({}, page)
    });
  }
}
