import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

export interface DataModel {
  check: boolean;
  code: string;
  details: string;
  grade: string;
  highscore: string;
  lowscore: string;
  weight: string;
}

@Component({
  selector: 'app-sub-grade-registration',
  templateUrl: './sub-grade-registration.component.html',
  styleUrls: ['./sub-grade-registration.component.scss'],
})
export class SubGradeRegistrationComponent {
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  modalStatus: "add" | "edit" = "add"
  addTab = false;
  editTab = false;
  currentPage = 1;
  page = Array.from({ length: 1 }, (_, i) => i + 1);
  numDataListChecked = 0;
  isDataListChecked = false;
  isDataListCheckedAll = false;
  search = '';

  dataList: DataModel[] = [
    { check: false, code: 'O1A', details: 'ระดับ A', grade: 'A', highscore: 'O1A', lowscore: 'O1A', weight: 'O1A' },
    { check: false, code: 'O2B', details: 'ระดับ B', grade: 'B', highscore: 'O1B', lowscore: 'O1B', weight: 'O1B' },
  ];

  constructor(private toastr: ToastrService) {
    this.pathTitleChange();
  }

  pathTitleChange() {
    this.sendPathTitle.emit(
      this.addTab
        ? ['การประเมินสมรรถนะ', 'ทะเบียนเกรด', 'การจัดการเกรด', 'เพิ่มกลุ่มเกรด']
        : this.editTab
          ? ['การประเมินสมรรถนะ', 'ทะเบียนเกรด', 'การจัดการเกรด', 'แก้ไขกลุ่มเกรด']
          : ['การประเมินสมรรถนะ', 'ทะเบียนเกรด', 'การจัดการเกรด']
    );
    
  }

  searchChange() {
    this.currentPage = 1;
    const filteredData = this.dataListFilter();
    this.page = Array.from({ length: Math.ceil(filteredData.length / 10) }, (_, i) => i + 1);
  }

  dataListFilter() {
    return this.dataList.filter((x) => {
      const match = x.code.includes(this.search) || x.details.includes(this.search);
      if (!match) x.check = false;
      return match;
    });
  }

  dataListCheck() {
    const dataCheck = this.dataListFilter();
    this.isDataListChecked = dataCheck.some((x) => x.check);
    this.isDataListCheckedAll = dataCheck.length ? dataCheck.every((x) => x.check) : false;
    this.numDataListChecked = dataCheck.filter((x) => x.check).length;
  }

  dataListCheckAll() {
    const selectAll = this.isDataListCheckedAll;
    this.dataList.forEach((x) => (x.check = selectAll));
    this.dataListCheck(); // อัปเดตสถานะการเช็ก
  }

  showSuccessAdd() {
    this.toastr.success('เพิ่มข้อมูลสำเร็จ!', 'เเจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }
  showSuccessEdit() {
    this.toastr.success('แก้ไขข้อมูลสำเร็จ', 'เเจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

  showSuccessDelete() {
    this.toastr.success('ลบข้อมูลสำเร็จ', 'เเจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    });
  }

  addUser() {

  }
}