import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map, merge, Observable, Subject, switchMap, takeUntil } from 'rxjs';
import { fuseAnimations } from '@fuse/animations';
import { FuseConfirmationService } from '@fuse/services/confirmation';

import { Loosing } from '../models/loosing';

import { LoosingService } from '../services/loosing.service';
import {
  NavigationBehaviorOptions,
  NavigationExtras,
  Router,
} from '@angular/router';
import { MatTableDataSource } from '@angular/material/table';

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

        @screen sm {
          grid-template-columns: 40px 70px 70px 70px 70px 100px;
        }

        @screen md {
          grid-template-columns: 40px 70px 70px 70px 70px 100px;
        }

        @screen lg {
          grid-template-columns: 40px 70px 70px 70px 70px 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;

  loosings$!: Observable<Loosing[] | undefined>;

  isLoading = false;

  loosingDataSource: MatTableDataSource<Loosing> = new MatTableDataSource();

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

  headerTableColumns: string[] = [
    'index',
    'startDate',
    'endDate',
    'defaultDataTotalCount',
    'loosingDataTotalCount',
    'removeBtn',
  ];

  displayedTableColumns: string[] = [
    'index',
    'startDate',
    'endDate',
    'defaultDataTotalCount',
    'defaultDataViewBtn',
    'loosingDataTotalCount',
    'loosingDataViewBtn',
    'removeBtn',
  ];

  configForm!: FormGroup;

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

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

  /**
   * On init
   */
  ngOnInit(): void {
    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 products
    this._loosingService.loosings$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((loosings: Loosing[] | undefined) => {
        if (!loosings) {
          return;
        }

        this.loosingDataSource.data = loosings;
        // Mark for check
        this._changeDetectorRef.markForCheck();
      });
  }

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

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

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

  /* viewUserDetail(id: string): void {
    let url: string = 'member/user/' + id;
    this.router.navigateByUrl(url);
  } */
  // -----------------------------------------------------------------------------------------------------
  // @ Private methods
  // -----------------------------------------------------------------------------------------------------

  __viewLoosingDetail(loosing: Loosing, type: string): void {
    let url: string = '';

    if (type === '1') {
      url = 'report/loosing/01/' + loosing.id + `?type=${type}`;
    } else {
      url = 'report/loosing/02/' + loosing.id + `?type=${type}`;
    }

    let extras: NavigationBehaviorOptions = {
      state: {
        viewType: type,
        startDate: loosing.startDate,
        endDate: loosing.endDate,
      },
    };
    this.router.navigateByUrl(url, extras);
  }

  __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);
    });
  }
  /**
   * 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;
  }
}
