import { ChangeDetectorRef, Component, EventEmitter, Output, Renderer2 } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { EvaluationCycleModel, MyEvaluationCycleModel } from 'src/app/shared/model/evaluation-cycle.model';
import { EvaluationCycleService } from 'src/app/shared/services/evaluation-cycle.service';
import { MyStatusCodeModel, StatusCodeModel } from 'src/app/shared/model/status-code.model';
import { EvaluationAssessmentService } from 'src/app/shared/services/evaluation-assessment.service';
import { PLService } from 'src/app/shared/services/pl.service';
import { PLModel, MyPLModel } from 'src/app/shared/model/pl.model';
export interface DataModal {
  search: string,
  currentPage: number,
  page: number[]
}
@Component({
  selector: 'app-evaluation-cycle',
  templateUrl: './evaluation-cycle.component.html',
  styleUrls: ['./evaluation-cycle.component.scss']
})
export class EvaluationCycleComponent {
  @Output() evaluationRoundIdChange = new EventEmitter<string>();
  apsPeriodStart: string = '';
  apsPeriodEnd: string = '';

  currentPage = 1
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  search = ""
  modalStatus = 'add'
  evaluation_cyclelist: { check: boolean, data: EvaluationCycleModel }[] = []
  evaluation_cycle: EvaluationCycleModel = new MyEvaluationCycleModel({})
  dataLoading = false
  itemToDelete: EvaluationCycleModel | null = null;
  isDataListChecked = false
  isDataListCheckedAll = false
  numDataListChecked = 0
  evaluationRoundId = ''
  private unlisten!: () => void;

  modal: DataModal = {
    search: "",
    currentPage: 1,
    page: Array.from({ length: 1 }, (_, i) => i + 1)
  }
  pl: { loading: boolean, selectIndex: number, dataList: PLModel[] } = { loading: false, selectIndex: -1, dataList: [] }


  constructor(private evaluationCycleService: EvaluationCycleService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private renderer: Renderer2,
    private pLService: PLService
  ) { }

  ngOnInit(): void {
    this.getEvaluationCycleList()
    this.unlisten = this.renderer.listen('document', 'keydown', (event) => {
      if (event.key === 'Escape') {
        this.evaluationRoundId = ''
      }
    });
    this.getPlList()
  }
  ngOnDestroy() {
    if (this.unlisten) {
      this.unlisten(); // เรียกใช้งานจริง ๆ เพื่อลบ event listener
    }
  }

  getPlList() {
    this.pl.loading = false
    this.pLService.getList().subscribe({
      next: response => {
        this.pl.dataList = response.map((x: any) => new MyPLModel(x))
        this.pl.loading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.pl.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  plListFilter() {
    return this.pl.dataList.filter(x =>
      (x.plId.toLowerCase().includes(this.modal.search.toLowerCase()) ||
        x.tdesc.toLowerCase().includes(this.modal.search.toLowerCase()) ||
        x.edesc.toLowerCase().includes(this.modal.search.toLowerCase())) &&
      !this.evaluation_cycle.personalLevel.some(y => y.plId == x.plId)
    );

  }
  selectPl(data?: PLModel) {
    if (!data) {
      this.evaluation_cycle.personalLevel.splice(this.pl.selectIndex, 1);
      return;
    }
    this.evaluation_cycle.personalLevel.push(new MyPLModel(data))
  }

  getEvaluationCycleList() {
    this.dataLoading = true
    this.evaluationCycleService.getList().subscribe({
      next: response => {
        this.evaluation_cyclelist = response.map(x => ({
          check: false,
          data: new MyEvaluationCycleModel(x)
        }));
        this.dataLoading = false
        this.isDataListCheckedAll = false
        this.dataListCheckAll()
        this.searchChange();
        this.cdr.detectChanges();
      },
      error: err => {
        this.dataLoading = false
        this.cdr.detectChanges();
      }
    });
  }
  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.evaluation_cycleListFilter().forEach(x => x.check = selectAll);
    this.dataListCheck();
  }

  dataListCheck() {
    const dataCheck = this.evaluation_cycleListFilter();
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
    this.numDataListChecked = this.evaluation_cyclelist.filter(x => x.check).length;
    this.isDataListChecked = Boolean(this.numDataListChecked)
  }
  searchChange() {
    this.currentPage = 1
    this.page = Array.from({ length: Math.ceil(this.evaluation_cycleListFilter().length / 10) }, (_, i) => i + 1);
    this.dataListCheck()
  }
  evaluation_cycleListFilter() {
    return this.evaluation_cyclelist.filter(x => {
      const data = x.data
      const match = data.evaluationRoundId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
      return match;
    });
  }
  setData(data?: EvaluationCycleModel) {
    this.evaluation_cycle = new MyEvaluationCycleModel(data)
  }
  addevaluation_cycle() {
    this.evaluation_cycle.personalLevel.pop()
    const body = new MyEvaluationCycleModel(this.evaluation_cycle)
    this.dataLoading = true
    this.evaluationCycleService.post(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getEvaluationCycleList()
        } else {
          this.dataLoading = false
          this.showAlert(response.message, 'error')
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  deleteevaluation_cycle() {
    let body: EvaluationCycleModel | EvaluationCycleModel[] = []
    if (this.evaluation_cycle.evaluationRoundId) {
      this.evaluation_cycle.personalLevel.pop()
      body = new MyEvaluationCycleModel(this.evaluation_cycle)
    } else {
      body = this.evaluation_cyclelist.filter(x => x.check).map(x => new MyEvaluationCycleModel(x.data))
    }
    this.dataLoading = true
    this.evaluationCycleService.delete(body).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getEvaluationCycleList()
        } else {
          this.dataLoading = false
          this.showAlert(response.message, 'error')
          this.dataLoading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

  clear() {
    if (this.modalStatus == 'add') {
      this.setData()
    } else if (this.modalStatus == 'edit') {
      this.setData(new MyEvaluationCycleModel({ evaluationRoundId: this.evaluation_cycle.evaluationRoundId }))
    }
  }

  openModal(id: string, evaluationRoundId: string) {
    this.evaluationRoundId = ''
    if (id == 'evaluation-cycle-person-modal') {
      this.evaluationRoundId = evaluationRoundId
      this.evaluationRoundIdChange.emit(evaluationRoundId)
      setTimeout(() => {
        document.getElementById(id)?.classList.add('open');
        document.getElementById(id)?.classList.remove('hidden');
        document.getElementById(id)?.setAttribute('aria-overlay', 'false');
      }, 10);
    }
  }

  searchModalChange(dataList: any[]) {
    this.modal.currentPage = 1
    this.modal.page = Array.from({ length: Math.ceil(dataList.length / 10) }, (_, i) => i + 1);
  }

}