import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} 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 { User } from '../../../member/user/models/user';
import { CustomerTemplate } from '../models/ customer-template';
import { CustomerTemplatePagination } from '../models/customer-template-pagination';
import { CustomerTemplateService } from '../services/customer-template.service';
import { Router } from '@angular/router';

@Component({
  selector: 'customer-template-list',
  templateUrl: './list.component.html',
  styles: [
    /* language=SCSS */
    `
      .customer-template-grid {
        /*                     번호   제목  순서   수정   삭제 */
        grid-template-columns: 60px auto 80px 80px 80px;

        @screen sm {
          /*                     번호   제목  순서   수정   삭제 */
          grid-template-columns: 60px auto 80px 80px 80px;
        }

        @screen md {
          /*                     번호   제목  순서   수정   삭제 */
          grid-template-columns: 60px auto 80px 80px 80px;
        }

        @screen lg {
          /*                     번호   제목  순서   수정   삭제 */
          grid-template-columns: 60px auto 80px 80px 80px;
        }
      }
    `,
  ],
  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;

  customerTemplates$!: Observable<CustomerTemplate[] | undefined>;
  users$!: Observable<User[] | undefined>;

  isLoading = false;
  searchInputControl = new FormControl();
  selectedCustomerTemplate?: CustomerTemplate;
  pagination?: CustomerTemplatePagination;
  configForm!: FormGroup;

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

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

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

  /**
   * On init
   */
  ngOnInit(): void {
    // Build the config form
    this.configForm = this._formBuilder.group({
      title: '알림',
      message:
        '정말로 삭제하시겠습니까? <span class="font-medium">삭제!</span>',
      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,
    });
    // Get the pagination
    this._customerTemplateService.pagination$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((pagination: CustomerTemplatePagination | undefined) => {
        // Update the pagination
        this.pagination = pagination;

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

    // Get the products
    this.customerTemplates$ = this._customerTemplateService.customerTemplates$;
  }

  /**
   * After view init
   */
  ngAfterViewInit(): void {
    if (this._sort && this._paginator) {
      // Set the initial sort
      this._sort.sort({
        id: 'name',
        start: 'asc',
        disableClear: true,
      });

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

      // If the customerTemplate changes the sort order...
      this._sort.sortChange
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe(() => {
          // Reset back to the first page
          this._paginator.pageIndex = 0;
        });

      // Get products if sort or page changes
      merge(this._sort.sortChange, this._paginator.page)
        .pipe(
          switchMap(() => {
            this.isLoading = true;
            return this._customerTemplateService.getCustomerTemplates(
              this._paginator.pageIndex,
              this._paginator.pageSize,
              this._sort.active,
              this._sort.direction
            );
          }),
          map(() => {
            this.isLoading = false;
          })
        )
        .subscribe();
    }
  }

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

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

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

  /**
   * Create product
   */
  __createProduct(): void {}

  /**
   * Toggle product details
   *
   * @param productId
   */
  __onClickReditBtn(event: MouseEvent, id: string): void {
    const param = id === '0' ? '' : id;
    let url: string = 'board/customer-template/redit/' + param;
    this.router.navigateByUrl(url);
  }

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

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

  /**
   * Track by function for ngFor loops
   *
   * @param index
   * @param item
   */
  __trackByFn(index: number, item: any): any {
    return item.id || index;
  }
}
