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 { 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 { ToggleSwitchModule } from 'primeng/toggleswitch';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrSalaryComponentService } from '../../../core/services/hr-salary-component.service';

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

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

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

  form!: FormGroup;

  typeOptions = [
    { label: 'Earning', value: 'earning' },
    { label: 'Deduction', value: 'deduction' },
  ];

  calculationTypeOptions = [
    { label: 'Fixed', value: 'fixed' },
    { label: 'Percentage', value: 'percentage' },
  ];

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

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

  private initForm(): void {
    this.form = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      type: ['earning'],
      is_taxable: [false],
      is_fixed: [false],
      calculation_type: ['fixed'],
      amount: [null],
      percentage: [null],
      percentage_of: [''],
      description: [''],
      status: ['active'],
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.salaryComponentService.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({ type: 'earning', calculation_type: 'fixed', status: 'active', is_taxable: false, is_fixed: false });
    this.dialogVisible.set(true);
  }

  editItem(item: any): 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.calculation_type === 'fixed') {
      delete data.percentage;
      delete data.percentage_of;
    } else {
      delete data.amount;
    }

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

  getTypeSeverity(type: string): 'success' | 'danger' {
    return type === 'earning' ? 'success' : 'danger';
  }

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