import { ChangeDetectorRef, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ColumnModel } from '@syncfusion/ej2-grids';
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';

@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

  page = Array.from({ length: 1 }, (_, i) => i + 1);
  pageSize = 10

  indicatorsCoursesList: CompetencytopicModel[] = []
  indicatorsCourses: CompetencytopicModel = new MyCompetencytopicModel({})
  dataLoading = false
  currentModal: 'add' | 'edit' | 'delete' = 'add'
  selectedFile: File | null = null;
  selectedFileName: string = 'กรุณาเลือกไฟล์';

  columns: ColumnModel[] = [{
    field: "competencyTopicId",
    headerText: "CompetencyCode",
    type: "string",
    isPrimaryKey: true,
  },
  {
    field: "tdesc",
    headerText: "CompetencyName",
    type: "string"
  },
  {
    field: "competencyType.tdesc",
    headerText: "CompetencyType",
    type: "string"
  }]
  searchSettings = {
    fields: ['competencyTopicId', 'tdesc', 'competencyType.tdesc'],
    operator: 'contains',
    ignoreCase: false
  };
  search = ''
  selectedItems: { key: string, count: number, data: Map<string, boolean> } = { key: '', count: 0, data: new Map<string, boolean>() };


  constructor(private toastr: ToastrService,
    private cdr: ChangeDetectorRef,
    private competencytopicService: CompetencytopicService,
    private fileService: FileService
  ) {
    this.pathTitleChange()
  }

  ngOnInit(): void {
    this.getIndicatorsCoursesList()
  }

  downloadExam(data: CompetencytopicModel) {
    this.fileService.downloadFiles(data.competencyFiles).subscribe({
      next: response => {
        const url = window.URL.createObjectURL(response);
        const a = document.createElement("a");
        a.href = url;
        a.download = data.competencyFiles;
        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.getIndicatorsCoursesList()
        } 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')
      }
    })

  }

  getIndicatorsCoursesList() {
    this.dataLoading = true
    this.selectedItems.data.clear()
    this.competencytopicService.getList().subscribe({
      next: response => {
        this.indicatorsCoursesList = response.map(x => {
          this.selectedItems.data.set(x.competencyTopicId, false)
          return new MyCompetencytopicModel(x)
        })
        this.indicatorsCoursesList = response
        this.dataLoading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.dataLoading = false
        this.cdr.detectChanges()
      }
    })
  }
  selectIndicatorsCourses(data: CompetencytopicModel) {
    const indicatorsCourses = this.indicatorsCoursesList.find(x => x.competencyTopicId == data.competencyTopicId)
    this.indicatorsCourses = new MyCompetencytopicModel(indicatorsCourses || {})
  }

  onSelectAction(event: { data: any, action: 'view' | 'edit' }) {
    this.selectIndicatorsCourses(event.data);
    if (event.action === 'view') {
      this.editTab = false;
      this.seeTab = true;
    } else if (event.action === 'edit') {
      this.editTab = true;
      this.seeTab = false;
    }
  }

  onViewClicked(item: any) {
    this.selectIndicatorsCourses(item);
    this.editTab = false;
    this.seeTab = true;
  }

  onEditClicked(item: any) {
    this.selectIndicatorsCourses(item);
    this.editTab = true;
    this.seeTab = false;
  }

  pathTitleChange() {
    this.sendPathTitle.emit(this.editTab ? ['CompetencySystem', 'CompetencyManage', 'BIsAndCDR', 'การจัดการตัวชี้วัดเเละหลักสูตร'] : ['CompetencySystem', 'CompetencyManage', 'BIsAndCDR'])
  }

  checkPrimary() {
    return this.indicatorsCoursesList.find(x => x.competencyTopicId == this.indicatorsCourses.competencyTopicId)
  }


}

