import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { MatCheckboxChange } from '@angular/material/checkbox';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import {
  debounceTime,
  map,
  merge,
  Observable,
  Subject,
  switchMap,
  takeUntil,
} from 'rxjs';
import { fuseAnimations } from '@fuse/animations';
import { FuseConfirmationService } from '@fuse/services/confirmation';

import { AdminSession } from '../models/admin-session';
import { AdminSessionPagination } from '../models/admin-session-pagination';
import { AdminSessionService } from '../services/admin-session.service';
import { Router } from '@angular/router';

@Component({
  selector: 'admin-session-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .admin-session-grid {
        grid-template-columns: 60px 150px auto 200px 100px 100px 100px;

        @screen sm {
          grid-template-columns: 60px 150px auto 200px 100px 100px 100px;
        }

        @screen md {
          grid-template-columns: 60px 150px auto 200px 100px 100px 100px;
        }

        @screen lg {
          grid-template-columns: 60px 150px auto 200px 100px 100px 100px;
        }
      }
    `,
  ],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: fuseAnimations,
})
export class ListComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild(MatPaginator) private _paginator!: MatPaginator;
  @ViewChild(MatSort) private _sort!: MatSort;

  adminSessions$!: Observable<AdminSession[] | undefined>;

  isLoading = false;
  searchInputControl = new FormControl();
  selectedAdminSession?: AdminSession;
  pagination?: AdminSessionPagination;
  __isSearchOpened = false;

  ipBlockConfigForm!: FormGroup;
  idBlockConfigForm!: FormGroup;

  private _unsubscribeAll: Subject<any> = new Subject<any>();

  /**
   * Constructor
   */
  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _fuseConfirmationService: FuseConfirmationService,
    private _formBuilder: FormBuilder,
    private _adminSessionService: AdminSessionService,
    private router: Router
  ) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Get the pagination
    this._adminSessionService.pagination$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((pagination: AdminSessionPagination | undefined) => {
        // Update the pagination
        this.pagination = pagination;

        // Mark for check
        this._changeDetectorRef.markForCheck();
      });

    // Get the products
    this.adminSessions$ = this._adminSessionService.adminSessions$;

    // Set ip, id block config
    this.__idBlockConfirmConfig();
    this.__ipBlockConfirmConfig();
  }

  /**
   * After view init
   */
  ngAfterViewInit(): void {}

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next(null);
    this._unsubscribeAll.complete();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  // -----------------------------------------------------------------------------------------------------
  // @ Private methods
  // -----------------------------------------------------------------------------------------------------

  viewUserDetail(id: string = '00b0292f-3d50-4669-a0c4-7a9d85efc98d'): void {
    let url: string = 'member/user/' + id;
    this.router.navigateByUrl(url);
  }

  /**
   * toggle the search
   * Used in 'bar'
   */
  __onClickSearch(): void {
    this.__isSearchOpened = !this.__isSearchOpened;
  }
  /**
   * Create product
   */
  __createProduct(): void {}

  /**
   * Toggle product details
   *
   * @param productId
   */
  __toggleDetails(productId: string): void {}

  /**
   * Track by function for ngFor loops
   *
   * @param index
   * @param item
   */
  __trackByFn(index: number, item: any): any {
    return item.id || index;
  }
  __ipBlockConfirmConfig(): void {
    this.ipBlockConfigForm = this._formBuilder.group({
      title: '알림',
      message: 'IP 차단 처리하시겠습니까?',
      icon: this._formBuilder.group({
        show: true,
        name: 'heroicons_outline:exclamation',
        color: 'warn',
      }),
      actions: this._formBuilder.group({
        confirm: this._formBuilder.group({
          show: true,
          label: '확인',
          color: 'warn',
        }),
        cancel: this._formBuilder.group({
          show: true,
          label: '취소',
        }),
      }),
      dismissible: true,
    });
  }
  __onClickIpBlock(event: MouseEvent, id: string): void {
    // Open the dialog and save the reference of it
    const dialogRef = this._fuseConfirmationService.open(
      this.ipBlockConfigForm.value
    );

    // Subscribe to afterClosed from the dialog reference
    dialogRef.afterClosed().subscribe((result) => {
      console.log(result);
    });
  }
  __idBlockConfirmConfig(): void {
    this.idBlockConfigForm = this._formBuilder.group({
      title: '알림',
      message: 'ID블럭 처리하시겠습니까?',
      icon: this._formBuilder.group({
        show: true,
        name: 'heroicons_outline:exclamation',
        color: 'warn',
      }),
      actions: this._formBuilder.group({
        confirm: this._formBuilder.group({
          show: true,
          label: '확인',
          color: 'warn',
        }),
        cancel: this._formBuilder.group({
          show: true,
          label: '취소',
        }),
      }),
      dismissible: true,
    });
  }

  __onClickIdBlock(event: MouseEvent, id: string): void {
    // Open the dialog and save the reference of it
    const dialogRef = this._fuseConfirmationService.open(
      this.idBlockConfigForm.value
    );

    // Subscribe to afterClosed from the dialog reference
    dialogRef.afterClosed().subscribe((result) => {
      console.log(result);
    });
  }
}
