import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, 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 { InputNumberModule } from 'primeng/inputnumber';
import { SelectModule } from 'primeng/select';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { TextareaModule } from 'primeng/textarea';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrPositionService } from '../../../core/services/hr-position.service';
import { HrPosition } from '../../../core/models/hr-position.model';
import { HrDepartmentService } from '../../../core/services/hr-department.service';

@Component({
  selector: 'app-hr-positions',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    InputNumberModule,
    SelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    TextareaModule,
    PageHeaderComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './hr-positions.component.html',
  styleUrl: './hr-positions.component.scss',
})
export class HrPositionsComponent implements OnInit {
  private fb = inject(FormBuilder);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private positionService = inject(HrPositionService);
  private departmentService = inject(HrDepartmentService);

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

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

  departments: any[] = [];

  form!: FormGroup;

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

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

  private initForm(): void {
    this.form = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      department_id: [null],
      grade: [''],
      min_salary: [null],
      max_salary: [null],
      description: [''],
      status: ['active'],
    });
  }

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

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.positionService.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: HrPosition): 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 };
    if (!data.department_id) delete data.department_id;

    const isEdit = !!this.editingItem();
    const obs = isEdit
      ? this.positionService.update(this.editingItem()!.id, data)
      : this.positionService.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: HrPosition): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.POSITIONS.DELETE_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.positionService.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',
            });
          },
        });
      },
    });
  }

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