import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { CompetencytopicModel, MyCompetencytopicModel } from 'src/app/shared/model/competencytopic.model';
import { CompetencytopicService } from 'src/app/shared/services/competencytopic.service';
import { FileService } from 'src/app/shared/services/file.service';
export interface DataModel {
  code: string,
  name: string,
  type: string
  file: string
}
@Component({
  selector: 'app-indicators-and-curriculum',
  templateUrl: './indicators-and-curriculum.component.html',
  styleUrls: ['./indicators-and-curriculum.component.scss']
})
export class IndicatorsAndCurriculumComponent {
  @Output() sendPathTitle: EventEmitter<string[]> = new EventEmitter<string[]>();
  editTab = false
  seeTab = false
  currentPage = 1
  search = ""
  page = Array.from({ length: 1 }, (_, i) => i + 1);

  dataList: DataModel[] = []
  indicatorsCoursesList: CompetencytopicModel[] = []
  indicatorsCourses: CompetencytopicModel = new MyCompetencytopicModel({})
  dataLoading = false

  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';
  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private competencytopicService: CompetencytopicService,
    private fileService: FileService
  ) {
    this.pathTitleChange()
  }

  dowloadExam(fileName: string) {
    this.fileService.dowloadFiles(fileName).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.cdr.detectChanges()
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.cdr.detectChanges()
      }
    })
  }

  onFileSelected(event: any) {
    this.selectedFile = event.target.files.length > 0 ? event.target.files[0] : null;
    this.selectedFileName = this.selectedFile?.name || "กรุณาเลือกไฟล์"
  }

  uploadFile() {
    if (!this.selectedFile) {
      alert('กรุณาเลือกไฟล์ก่อนอัปโหลด')
      return
    }
    const formData = new FormData();
    formData.append('file', this.selectedFile);
    this.dataLoading = true
    this.fileService.uploadExcel(formData, 'COMPETENCY_INDICATORS_COURSES').subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getList()
        } else {
          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',
    })
  }

  downloadFile() {
    const fileName = 'IMPORT_COMPETENCY_INDICATORS.xlsx'
    this.fileService.downloadTemplate(fileName).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, error: error => {
        this.showAlert(error.message, 'error')
      }
    })

  }
  ngOnInit(): void {
    this.getList()
  }
  getList() {
    this.dataLoading = true
    this.competencytopicService.getList().subscribe({
      next: response => {
        this.dataList = response.map(x => ({ code: x.competencyTopicId || "", name: x.tdesc || "", type: x.competencyType.tdesc || "", file: x.competencyFiles || "" }))
        this.indicatorsCoursesList = response
        this.dataLoading = false
        this.searchChange()
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  selectIndicatorsCourses(data: DataModel) {
    const indicatorsCourses = this.indicatorsCoursesList.find(x => x.competencyTopicId == data.code)
    this.indicatorsCourses = new MyCompetencytopicModel(indicatorsCourses || {})
  }
  pathTitleChange() {
    this.sendPathTitle.emit(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 => {
      return x.code.toLowerCase().includes(this.search.toLowerCase()) || x.name.toLowerCase().includes(this.search.toLowerCase()) || x.type.toLowerCase().includes(this.search.toLowerCase())
    });
  }

}