import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { DialogModule } from 'primeng/dialog';
import { InputTextModule } from 'primeng/inputtext';
import { SelectModule } from 'primeng/select';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { DatePickerModule } from 'primeng/datepicker';
import { InputNumberModule } from 'primeng/inputnumber';
import { TextareaModule } from 'primeng/textarea';
import { TooltipModule } from 'primeng/tooltip';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrCandidateService } from '../../../core/services/hr-candidate.service';
import { HrApplicationService } from '../../../core/services/hr-application.service';
import { HrJobOpeningService } from '../../../core/services/hr-job-opening.service';
import { HrCandidate, HrApplication } from '../../../core/models/hr-recruitment.model';

@Component({
  selector: 'app-hr-candidates',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    SelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    DatePickerModule,
    InputNumberModule,
    TextareaModule,
    TooltipModule,
    PageHeaderComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './hr-candidates.component.html',
  styleUrl: './hr-candidates.component.scss',
})
export class HrCandidatesComponent implements OnInit {
  private fb = inject(FormBuilder);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private candidateService = inject(HrCandidateService);
  private applicationService = inject(HrApplicationService);
  private jobOpeningService = inject(HrJobOpeningService);

  dialogVisible = signal(false);
  editingItem = signal<HrCandidate | null>(null);
  tableLoading = signal(false);
  saving = signal(false);

  // Applications sub-dialog state
  applicationsDialogVisible = signal(false);
  applicationDialogVisible = signal(false);
  editingApplication = signal<HrApplication | null>(null);
  selectedCandidate = signal<HrCandidate | null>(null);
  applications = signal<HrApplication[]>([]);
  applicationsLoading = signal(false);
  savingApplication = signal(false);

  tableData = signal<HrCandidate[]>([]);
  totalRecords = signal(0);
  first = 0;
  rows = 25;

  jobOpenings: any[] = [];

  form!: FormGroup;
  applicationForm!: FormGroup;

  statusOptions = [
    { label: 'Active', value: 'active' },
    { label: 'Inactive', value: 'inactive' },
  ];

  applicationStatusOptions = [
    { label: 'Pending', value: 'pending' },
    { label: 'Shortlisted', value: 'shortlisted' },
    { label: 'Interviewed', value: 'interviewed' },
    { label: 'Offered', value: 'offered' },
    { label: 'Hired', value: 'hired' },
    { label: 'Rejected', value: 'rejected' },
  ];

  applicationStageOptions = [
    { label: 'Applied', value: 'applied' },
    { label: 'Screening', value: 'screening' },
    { label: 'Interview', value: 'interview' },
    { label: 'Assessment', value: 'assessment' },
    { label: 'Final Review', value: 'final_review' },
    { label: 'Decision', value: 'decision' },
  ];

  ngOnInit(): void {
    this.initForm();
    this.initApplicationForm();
    this.loadPage();
    this.loadDependencies();
  }

  private initForm(): void {
    this.form = this.fb.group({
      first_name_ar: ['', Validators.required],
      first_name_en: [''],
      last_name_ar: ['', Validators.required],
      last_name_en: [''],
      email: [''],
      phone: [''],
      experience_years: [null],
      current_salary: [null],
      expected_salary: [null],
      source: [''],
      notes: [''],
      status: ['active'],
    });
  }

  private initApplicationForm(): void {
    this.applicationForm = this.fb.group({
      job_opening_id: [null, Validators.required],
      status: ['pending'],
      stage: ['applied'],
      notes: [''],
    });
  }

  private loadDependencies(): void {
    this.jobOpeningService.listAll().subscribe({
      next: (res) => (this.jobOpenings = res.data),
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.candidateService.list(page, perPage).subscribe({
      next: (res) => {
        this.tableData.set(res.data);
        this.totalRecords.set(res.meta.total);
        this.tableLoading.set(false);
      },
      error: () => this.tableLoading.set(false),
    });
  }

  onPageChange(event: any): void {
    this.first = event.first;
    this.rows = event.rows;
    const page = Math.floor(event.first / event.rows) + 1;
    this.loadPage(page, event.rows);
  }

  openNew(): void {
    this.editingItem.set(null);
    this.form.reset({ status: 'active' });
    this.dialogVisible.set(true);
  }

  editItem(item: HrCandidate): void {
    this.editingItem.set(item);
    this.form.patchValue(item);
    this.dialogVisible.set(true);
  }

  onSave(): void {
    if (!this.form.valid) {
      this.form.markAllAsTouched();
      return;
    }

    const data = { ...this.form.value };

    const isEdit = !!this.editingItem();
    const obs = isEdit
      ? this.candidateService.update(this.editingItem()!.id, data)
      : this.candidateService.create(data);

    this.saving.set(true);
    obs.subscribe({
      next: () => {
        this.saving.set(false);
        this.dialogVisible.set(false);
        this.loadPage();
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: isEdit
            ? this.translate.instant('COMMON.UPDATED')
            : this.translate.instant('COMMON.CREATED'),
        });
      },
      error: (err) => {
        this.saving.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Operation failed',
        });
      },
    });
  }

  deleteItem(item: HrCandidate): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.CANDIDATES.DELETE_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.candidateService.delete(item.id).subscribe({
          next: () => {
            this.loadPage();
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('COMMON.DELETED'),
            });
          },
          error: (err) => {
            this.messageService.add({
              severity: 'error',
              summary: this.translate.instant('COMMON.ERROR'),
              detail: err.error?.message || 'Delete failed',
            });
          },
        });
      },
    });
  }

  // Applications sub-dialog methods
  viewApplications(candidate: HrCandidate): void {
    this.selectedCandidate.set(candidate);
    this.applicationsDialogVisible.set(true);
    this.loadApplications(candidate.id);
  }

  private loadApplications(candidateId: number): void {
    this.applicationsLoading.set(true);
    this.applicationService.listAll({ candidate_id: candidateId }).subscribe({
      next: (res) => {
        this.applications.set(res.data);
        this.applicationsLoading.set(false);
      },
      error: () => this.applicationsLoading.set(false),
    });
  }

  openNewApplication(): void {
    this.editingApplication.set(null);
    this.applicationForm.reset({ status: 'pending', stage: 'applied' });
    this.applicationDialogVisible.set(true);
  }

  editApplication(app: HrApplication): void {
    this.editingApplication.set(app);
    this.applicationForm.patchValue(app);
    this.applicationDialogVisible.set(true);
  }

  onSaveApplication(): void {
    if (!this.applicationForm.valid) {
      this.applicationForm.markAllAsTouched();
      return;
    }

    const data = {
      ...this.applicationForm.value,
      candidate_id: this.selectedCandidate()!.id,
    };

    const isEdit = !!this.editingApplication();
    const obs = isEdit
      ? this.applicationService.update(this.editingApplication()!.id, data)
      : this.applicationService.create(data);

    this.savingApplication.set(true);
    obs.subscribe({
      next: () => {
        this.savingApplication.set(false);
        this.applicationDialogVisible.set(false);
        this.loadApplications(this.selectedCandidate()!.id);
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: isEdit
            ? this.translate.instant('COMMON.UPDATED')
            : this.translate.instant('COMMON.CREATED'),
        });
      },
      error: (err) => {
        this.savingApplication.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Operation failed',
        });
      },
    });
  }

  deleteApplication(app: HrApplication): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.CANDIDATES.DELETE_APPLICATION_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.applicationService.delete(app.id).subscribe({
          next: () => {
            this.loadApplications(this.selectedCandidate()!.id);
            this.messageService.add({
              severity: 'success',
              summary: this.translate.instant('COMMON.SUCCESS'),
              detail: this.translate.instant('COMMON.DELETED'),
            });
          },
          error: (err) => {
            this.messageService.add({
              severity: 'error',
              summary: this.translate.instant('COMMON.ERROR'),
              detail: err.error?.message || 'Delete failed',
            });
          },
        });
      },
    });
  }

  getStatusSeverity(status: string): 'success' | 'info' | 'warn' | 'secondary' | 'contrast' | 'danger' {
    return status === 'active' ? 'success' : 'danger';
  }

  getApplicationStatusSeverity(status: string): 'success' | 'info' | 'warn' | 'secondary' | 'contrast' | 'danger' {
    switch (status) {
      case 'pending':
        return 'info';
      case 'shortlisted':
        return 'warn';
      case 'interviewed':
        return 'info';
      case 'offered':
        return 'warn';
      case 'hired':
        return 'success';
      case 'rejected':
        return 'danger';
      default:
        return 'info';
    }
  }
}
