import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { PagingSortPatientResultDto } from '@proxy/dto';
import { Gender, Status } from '@proxy/global-enum';
import { PatientService } from '@proxy/patients';
import { CreateUpdatePatientRecordDto, PatientDto, PatientRecordDto } from '@proxy/patients/dto';
import { MessageService } from 'primeng/api';
import { PermissionService } from '@abp/ng.core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-patient-record',
  templateUrl: './patient-record.component.html',
  styleUrl: './patient-record.component.scss',
  providers: [PatientService, MessageService, PermissionService],
})
export class PatientRecordComponent implements OnInit {
  globalFilter: string = '';
  patientrecords: PatientRecordDto[];
  totalRecords: number = 0;
  loading: boolean = false;
  patientDialog: boolean = false;
  selectedPatient: CreateUpdatePatientRecordDto;
  patientdto: PatientDto;
  isEditMode: boolean = false;
  patientDialogTitle: string = '';
  params: PagingSortPatientResultDto;
  status: any;
  gender: any;
  statuslist: any;
  selectdateOfAdmission: Date = new Date();
  selectnextFollowUp: Date = new Date();
  uploadfile: {
    file: File[];
    name: string;
  }[] = [];
  createpermission: boolean;
  editpermission: boolean;
  deletepermission: boolean;
  userid: any;
  patientImageUrl: string;

  constructor(
    private patientService: PatientService,
    private messageService: MessageService,
    private permissionChecker: PermissionService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.userid = this.route.snapshot.paramMap.get('id');
    console.log(this.userid);

    this.createpermission = this.permissionChecker.getGrantedPolicy(
      'HospitalManagementSystem.Patient.Create'
    );
    this.editpermission = this.permissionChecker.getGrantedPolicy(
      'HospitalManagementSystem.Patient.Edit'
    );
    this.deletepermission = this.permissionChecker.getGrantedPolicy(
      'HospitalManagementSystem.Patient.Delete'
    );
    this.status = Status;
    this.gender = Gender;
    this.patientService.getStatusDropdown().subscribe(result => {
      this.statuslist = result;
    });

    this.resetselectpatient();
  }

  resetselectpatient() {
    this.selectedPatient = {
      patientId: this.userid,
      dateOfAdmission: '',
      labReportUrl: '',
      medicationUrl: '',
      medicationHistoryUrl: '',
      nextFollowUp: '',
      diagnosis: '',
      treatmentPlan: '',
      doctorNotes: '',
      insuranceProvider: '',
      status: Status.InTreatment,
    };
  }

  loadPatient(event: any, id: any) {
    this.selectedPatient.patientId = this.userid;
    this.loading = true;
    let order = event.sortOrder == 1 ? ' asc' : ' desc';
    event.sortField = event.sortField == undefined ? 'id' : event.sortField;
    this.params = {
      skipCount: event.first,
      maxResultCount: event.rows,
      sorting: event.sortField + order,
      search: event.globalFilter == null ? '' : event.globalFilter,
    };
    this.patientService.getPatientById(this.userid).subscribe(result => {
      this.patientdto = result;
    });
    this.patientService.getPatientRecordList(this.params, id).subscribe(data => {
      this.patientrecords = data.items;
      this.totalRecords = data.totalCount;
      this.loading = false;
    });
  }

  exportPatient() {
    this.patientService.getExportPatientRecord().subscribe(result => {
      const binary = atob(result.fileContent);
      const len = binary.length;
      const bytes = new Uint8Array(len);

      for (let i = 0; i < len; i++) {
        bytes[i] = binary.charCodeAt(i);
      }

      const blob = new Blob([bytes], { type: 'application/xlsx' });

      const url = window.URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.href = url;
      link.download = result.fileName;

      document.body.appendChild(link);
      link.click();

      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    });
  }

  openNewPatientDialog() {
    this.patientDialogTitle = 'New Patient Record';
    this.resetselectpatient();
    this.patientDialog = true;
    this.isEditMode = false;
  }

  editPatient(Patient: any) {
    this.patientDialogTitle = 'Edit Patient';
    this.selectedPatient = { ...Patient };
    this.selectedPatient.patientId = this.userid;
    this.selectdateOfAdmission = new Date(this.selectedPatient.dateOfAdmission);
    this.selectnextFollowUp = new Date(this.selectedPatient.nextFollowUp);
    this.patientDialog = true;
    this.isEditMode = true;
    console.log(this.selectedPatient);
  }

  deletePatient(id: any) {
    this.patientService.deletePatientRecord(id).subscribe(() => {
      this.messageService.add({
        severity: 'success',
        summary: 'Success',
        detail: 'Patient deleted successfully',
      });
      this.loadPatient(this.params, this.userid);
    });
  }

  // handleLabReportUpload(event: any): void {
  //   const input = event.target as HTMLInputElement;
  //   console.log(input);
  //   const files: File[] = event.files; // Files uploaded
  //   this.addToUploadList(files, 'Lab-Report');
  // }
  handleLabReportUpload(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input && input.files) {
      const files: File[] = Array.from(input.files); // Convert FileList to an array of File
      this.addToUploadList(files, 'Lab-Report');
    } else {
      console.error('No files selected');
    }
  }

  handleMedicationsUpload(event: any): void {
    const files: File[] = event.files; // Files uploaded
    this.addToUploadList(files, 'Medications');
  }

  handleMedicationHistoryUpload(event: any): void {
    const files: File[] = event.files; // Files uploaded
    this.addToUploadList(files, 'Medication-History');
  }

  private addToUploadList(files: File[], name: string): void {
    const existingIndex = this.uploadfile.findIndex(item => item.name === name);

    if (existingIndex > -1) {
      this.uploadfile[existingIndex].file = files;
    } else {
      this.uploadfile.push({ file: files, name });
    }
    console.log(this.uploadfile);
  }

  savePatient(form: NgForm) {
    // console.log(form);
    this.selectedPatient.patientId = this.userid;
    this.selectedPatient.status = this.patientdto.status;
    this.selectedPatient.dateOfAdmission = this.selectdateOfAdmission.toDateString();
    this.selectedPatient.nextFollowUp = this.selectnextFollowUp.toDateString();

    if (this.isEditMode) {
      this.patientService
        .updatePatientRecord(this.selectedPatient.id, this.selectedPatient)
        .subscribe(() => {
          this.messageService.add({
            severity: 'success',
            summary: 'Success',
            detail: 'Patient updated successfully',
          });
          this.patientDialog = false;
          this.loadPatient(
            {
              first: 0,
              rows: 10,
              sortField: 'id',
              sortOrder: 1,
              globalFilter: null,
            },
            this.userid
          );
        });
    } else {
      this.patientService.createPatientRecord(this.selectedPatient).subscribe(() => {
        this.messageService.add({
          severity: 'success',
          summary: 'Success',
          detail: 'Patient created successfully',
        });
        this.patientDialog = false;
        this.loadPatient(
          {
            first: 0,
            rows: 10,
            sortField: 'id',
            sortOrder: 1,
            globalFilter: null,
          },
          this.userid
        );
      });
    }
  }

  closeDialog() {
    this.patientDialog = false;
  }
}
