import { ChangeDetectorRef, Component, EventEmitter, Input, Output, Renderer2 } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { PLModel, MyPLModel } from 'src/app/shared/model/pl.model';
import { MyPmsMasfromEvaluationModel, PmsMasfromEvaluationModel } from 'src/app/shared/model/pms-masfrom-evaluation.model';
import { PLService } from 'src/app/shared/services/pl.service';
import { PmsMasfromEvaluationCycleService } from 'src/app/shared/services/pms-masfrom-evaluation.service';
export interface DataModal {
    search: string,
    currentPage: number,
    page: number[]
}

@Component({
    selector: 'app-management-evaluation-cycle',
    templateUrl: './management-evaluation-cycle.component.html',
    styleUrls: ['./management-evaluation-cycle.component.scss']
})
export class ManagementCycleComponent {
    @Output() evaluationRoundIdChange = new EventEmitter<string>();
    apsPeriodStart: string = '';
    apsPeriodEnd: string = '';

    currentPage = 1
    page = Array.from({ length: 1 }, (_, i) => i + 1);
    search = ""
    modalStatus: 'add' | 'edit' | 'delete' | 'deleteGroup' = 'add'
    pmsMasfromEvaluationlist: { check: boolean, data: PmsMasfromEvaluationModel }[] = []
    pmsMasfromEvaluation: PmsMasfromEvaluationModel = new MyPmsMasfromEvaluationModel({})
    dataLoading = false
    itemToDelete: PmsMasfromEvaluationModel | 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 pmsMasfromEvaluationCycleService: PmsMasfromEvaluationCycleService,
        private toastr: ToastrService,
        private cdr: ChangeDetectorRef,
        private renderer: Renderer2,
        private pLService: PLService
    ) { }

    ngOnInit(): void {
        this.getPmsMasfromEvaluationCycleList()
        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.pmsMasfromEvaluation.personalLevel.some(y => y.plId == x.plId)
        );

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


    getPmsMasfromEvaluationCycleList() {
        this.dataLoading = true
        this.pmsMasfromEvaluationCycleService.getList().subscribe({
            next: response => {
                this.pmsMasfromEvaluationlist = response.map(x => ({
                    check: false,
                    data: new MyPmsMasfromEvaluationModel(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.pmsMasfromEvaluationCycleFilter().forEach(x => x.check = selectAll);
        this.dataListCheck();
    }

    dataListCheck() {
        const dataCheck = this.pmsMasfromEvaluationCycleFilter();
        this.isDataListCheckedAll = dataCheck.length ? dataCheck.every(x => x.check) : false;
        this.numDataListChecked = this.pmsMasfromEvaluationlist.filter(x => x.check).length;
        this.isDataListChecked = Boolean(this.numDataListChecked)
    }
    searchChange() {
        this.currentPage = 1
        this.page = Array.from({ length: Math.ceil(this.pmsMasfromEvaluationCycleFilter().length / 10) }, (_, i) => i + 1);
        this.dataListCheck()
    }
    pmsMasfromEvaluationCycleFilter() {
        return this.pmsMasfromEvaluationlist.filter(x => {
            const data = x.data
            const match = data.pmsEvaluationRoundId.toLowerCase().includes(this.search.toLowerCase()) || data.tdesc.toLowerCase().includes(this.search.toLowerCase()) || data.edesc.toLowerCase().includes(this.search.toLowerCase());
            return match;
        });
    }

    setData(data?: PmsMasfromEvaluationModel) {
        this.pmsMasfromEvaluation = new MyPmsMasfromEvaluationModel(data)
    }
    addPmsMasfromEvaluation() {
        const body = new MyPmsMasfromEvaluationModel(this.pmsMasfromEvaluation)
        this.dataLoading = true
        this.pmsMasfromEvaluationCycleService.post(body).subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getPmsMasfromEvaluationCycleList()
                } 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()
            }
        })
    }

    deletePmsMasfromEvaluation() {
        let body: PmsMasfromEvaluationModel[] = []
        if (this.pmsMasfromEvaluation.pmsEvaluationRoundId) {
            body = [new MyPmsMasfromEvaluationModel(this.pmsMasfromEvaluation)]
        } else {
            body = this.pmsMasfromEvaluationlist.filter(x => x.check).map(x => new MyPmsMasfromEvaluationModel(x.data))
        }
        this.dataLoading = true
        this.pmsMasfromEvaluationCycleService.delete(body).subscribe({
            next: response => {
                if (response.success) {
                    this.showAlert(response.message, 'success')
                    this.getPmsMasfromEvaluationCycleList()
                } 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 MyPmsMasfromEvaluationModel({ pmsEvaluationRoundId: this.pmsMasfromEvaluation.pmsEvaluationRoundId }))
        }
    }

    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);
    }
}