import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges
} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalModule } from 'ng-zorro-antd/modal';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { ReactiveFormsModule } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CommonModule } from '@angular/common';
import { JobModel } from '../../../../data-access/model/jobModel.model';
import { JobService } from '../../../../data-access/services/JobService.service';
import { catchError, of, tap } from 'rxjs';

@Component({
  selector: 'app-modal-job',
  templateUrl: `Modal.component.html`,
  standalone: true,
  imports: [
    NzModalModule,
    NzFormModule,
    NzInputModule,
    NzSelectModule,
    NzButtonModule,
    ReactiveFormsModule,
    CommonModule
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ModalJobComponent implements OnChanges {
  @Input() isEdit: boolean = false;
  @Input() showModal: boolean = false;
  @Input() jobData: JobModel.Job | null = null;
  @Output() submit = new EventEmitter<void>();
  @Output() close = new EventEmitter<void>();
  JobForm: FormGroup;
  isSubmitting: boolean = false;

  constructor(
    private fb: FormBuilder,
    private jobService: JobService,
    private message: NzMessageService
  ) {
    this.JobForm = this.fb.group({
      type: [null, [Validators.required]],
      title: [null, [Validators.required]],
      company: [null, [Validators.required]],
      location: [null],
      description: [null, [Validators.required]],
      how_to_apply: [null],
      company_logo: [null],
    });
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['jobData'] && this.isEdit && this.jobData) {
      this.JobForm.patchValue({
        type: this.jobData.type,
        title: this.jobData.title,
        company: this.jobData.company,
        location: this.jobData.location,
        description: this.jobData.description,
        how_to_apply: this.jobData.how_to_apply,
        company_logo: this.jobData.company_logo,
      });
    }

    if (changes['showModal'] && !this.showModal) {
      this.JobForm.reset();
    }
  }

  getErrorTip(controlName: string): string {
    const control = this.JobForm.get(controlName);
    return control?.errors ? 'vui lòng nhập trường ' + controlName : '';
  }

  onSubmit(): void {
    this.isEdit ? this.onSubmitEditJob() : this.onSubmitAddJob();
  }

  onSubmitEditJob(): void {
    if (this.JobForm.valid && this.jobData) {
      this.isSubmitting = true;
      const jobToUpdate: JobModel.Job = {
        ...this.jobData,
        ...this.JobForm.value,
      };
      this.jobService.editJob(jobToUpdate).pipe(
          tap((res) => {
            this.isSubmitting = false;
            this.message.success(res.message || 'Cập nhật công việc thành công!', {
              nzDuration: 2500,
            });
            this.submit.emit();
            this.onCancel();
          }),
          catchError((err) => {
            this.isSubmitting = false;
            this.message.error(
              err.message || 'Đã xảy ra lỗi khi cập nhật công việc.',
              { nzDuration: 2500 }
            );
            return of(null);
          })
        )
        .subscribe();
      }
  }

  onSubmitAddJob(): void {
    if (this.JobForm.invalid) {
      Object.values(this.JobForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity();
        }
      });
      return;
    }
    const newJob: JobModel.JobRequest = this.JobForm.value;
    console.log(newJob);
    this.jobService
      .addingNewJob(newJob)
      .pipe(
        tap((res) => {
          this.message.success(res.message, { nzDuration: 2500 });
          this.submit.emit();
          this.JobForm.reset();
          this.showModal = false;
        }),
        catchError((err) => {
          this.message.error(err.message, { nzDuration: 2500 });
          return of(null);
        })
      )
      .subscribe();
  }
  onCancel(): void {
    this.close.emit();
    this.JobForm.reset();
  }
}