import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { UserService, UserInfo, DoctorProfile, DoctorUpdateRequest, UserUpdateRequest } from '../../../../services/user.service';

@Component({
  selector: 'app-profile',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './profile.component.html',
  styleUrl: './profile.component.scss'
})
export class ProfileComponent implements OnChanges {
  @Input() currentUser: UserInfo | null = null;
  @Input() doctorProfile: DoctorProfile | null = null;
  @Input() showEditProfile = false;
  @Output() editProfileClick = new EventEmitter<void>();
  @Output() updateProfile = new EventEmitter<{userData: UserUpdateRequest, doctorData: DoctorUpdateRequest}>();
  @Output() fileSelected = new EventEmitter<Event>();
  
  constructor(public userService: UserService) {}

  editUserData: UserUpdateRequest = {
    firstName: '',
    lastName: '',
    phoneNumber: ''
  };
  
  editDoctorData: DoctorUpdateRequest = {
    medicalLicenseNumber: '',
    specialization: '',
    yearsOfExperience: undefined,
    biography: '',
    consultationFee: undefined,
    defaultDurationMinutes: undefined,
    // Enterprise fields
    streetAddress: '',
    city: '',
    state: '',
    zipCode: '',
    country: '',
    educationDegree: '',
    educationUniversity: '',
    educationGraduationYear: undefined,
    certifications: [],
    languagesSpoken: [],
    hospitalAffiliations: [],
    insuranceAccepted: [],
    professionalMemberships: []
  };
  
  newCertification: string = '';
  newLanguage: string = '';
  newHospitalAffiliation: string = '';
  newInsuranceAccepted: string = '';
  newProfessionalMembership: string = '';

  ngOnChanges(changes: SimpleChanges) {
    // When showEditProfile changes to true, initialize form data
    if (changes['showEditProfile'] && this.showEditProfile) {
      this.initializeFormData();
    }
    // When currentUser or doctorProfile changes and we're in edit mode, update form data
    if (this.showEditProfile && (changes['currentUser'] || changes['doctorProfile'])) {
      this.initializeFormData();
    }
  }

  initializeFormData() {
    // Initialize form data with current values
    if (this.currentUser) {
      this.editUserData = {
        firstName: this.currentUser.firstName || '',
        lastName: this.currentUser.lastName || '',
        phoneNumber: this.currentUser.phoneNumber || ''
      };
    }
    if (this.doctorProfile) {
      this.editDoctorData = {
        medicalLicenseNumber: this.doctorProfile.medicalLicenseNumber || '',
        specialization: this.doctorProfile.specialization || '',
        yearsOfExperience: this.doctorProfile.yearsOfExperience,
        biography: this.doctorProfile.biography || '',
        consultationFee: this.doctorProfile.consultationFee,
        defaultDurationMinutes: this.doctorProfile.defaultDurationMinutes,
        // Enterprise fields
        streetAddress: this.doctorProfile.streetAddress || '',
        city: this.doctorProfile.city || '',
        state: this.doctorProfile.state || '',
        zipCode: this.doctorProfile.zipCode || '',
        country: this.doctorProfile.country || '',
        educationDegree: this.doctorProfile.educationDegree || '',
        educationUniversity: this.doctorProfile.educationUniversity || '',
        educationGraduationYear: this.doctorProfile.educationGraduationYear,
        certifications: [...(this.doctorProfile.certifications || [])],
        languagesSpoken: [...(this.doctorProfile.languagesSpoken || [])],
        hospitalAffiliations: [...(this.doctorProfile.hospitalAffiliations || [])],
        insuranceAccepted: [...(this.doctorProfile.insuranceAccepted || [])],
        professionalMemberships: [...(this.doctorProfile.professionalMemberships || [])]
      };
    }
  }

  onEditProfile() {
    // Initialize form data with current values when editing starts
    this.initializeFormData();
    this.editProfileClick.emit();
  }

  cancelEdit() {
    // Reset form data to original values
    this.initializeFormData();
    this.editProfileClick.emit(); // Emit to close edit mode
  }

  onUpdateProfile() {
    this.updateProfile.emit({
      userData: this.editUserData,
      doctorData: this.editDoctorData
    });
  }

  onFileSelected(event: Event) {
    this.fileSelected.emit(event);
  }

  // Array management methods
  addCertification() {
    if (this.newCertification && this.newCertification.trim()) {
      if (!this.editDoctorData.certifications) {
        this.editDoctorData.certifications = [];
      }
      this.editDoctorData.certifications.push(this.newCertification.trim());
      this.newCertification = '';
    }
  }

  removeCertification(index: number) {
    if (this.editDoctorData.certifications) {
      this.editDoctorData.certifications.splice(index, 1);
    }
  }

  addLanguage() {
    if (this.newLanguage && this.newLanguage.trim()) {
      if (!this.editDoctorData.languagesSpoken) {
        this.editDoctorData.languagesSpoken = [];
      }
      this.editDoctorData.languagesSpoken.push(this.newLanguage.trim());
      this.newLanguage = '';
    }
  }

  removeLanguage(index: number) {
    if (this.editDoctorData.languagesSpoken) {
      this.editDoctorData.languagesSpoken.splice(index, 1);
    }
  }

  addHospitalAffiliation() {
    if (this.newHospitalAffiliation && this.newHospitalAffiliation.trim()) {
      if (!this.editDoctorData.hospitalAffiliations) {
        this.editDoctorData.hospitalAffiliations = [];
      }
      this.editDoctorData.hospitalAffiliations.push(this.newHospitalAffiliation.trim());
      this.newHospitalAffiliation = '';
    }
  }

  removeHospitalAffiliation(index: number) {
    if (this.editDoctorData.hospitalAffiliations) {
      this.editDoctorData.hospitalAffiliations.splice(index, 1);
    }
  }

  addInsuranceAccepted() {
    if (this.newInsuranceAccepted && this.newInsuranceAccepted.trim()) {
      if (!this.editDoctorData.insuranceAccepted) {
        this.editDoctorData.insuranceAccepted = [];
      }
      this.editDoctorData.insuranceAccepted.push(this.newInsuranceAccepted.trim());
      this.newInsuranceAccepted = '';
    }
  }

  removeInsuranceAccepted(index: number) {
    if (this.editDoctorData.insuranceAccepted) {
      this.editDoctorData.insuranceAccepted.splice(index, 1);
    }
  }

  addProfessionalMembership() {
    if (this.newProfessionalMembership && this.newProfessionalMembership.trim()) {
      if (!this.editDoctorData.professionalMemberships) {
        this.editDoctorData.professionalMemberships = [];
      }
      this.editDoctorData.professionalMemberships.push(this.newProfessionalMembership.trim());
      this.newProfessionalMembership = '';
    }
  }

  removeProfessionalMembership(index: number) {
    if (this.editDoctorData.professionalMemberships) {
      this.editDoctorData.professionalMemberships.splice(index, 1);
    }
  }
}