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 { ToggleSwitchModule } from 'primeng/toggleswitch';
import { TextareaModule } from 'primeng/textarea';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrLeaveTypeService } from '../../../core/services/hr-leave-type.service';
import { HrLeaveType } from '../../../core/models/hr-leave.model';

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

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

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

  form!: FormGroup;

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

  genderOptions = [
    { label: 'All', value: null },
    { label: 'Male', value: 'male' },
    { label: 'Female', value: 'female' },
  ];

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

  private initForm(): void {
    this.form = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      days_allowed: [0, [Validators.required, Validators.min(0)]],
      is_paid: [true],
      requires_approval: [true],
      carry_forward: [false],
      max_carry_forward_days: [null],
      gender: [null],
      description: [''],
      status: ['active'],
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.leaveTypeService.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({
      days_allowed: 0,
      is_paid: true,
      requires_approval: true,
      carry_forward: false,
      max_carry_forward_days: null,
      gender: null,
      status: 'active',
    });
    this.dialogVisible.set(true);
  }

  editItem(item: HrLeaveType): void {
    this.editingItem.set(item);
    this.form.patchValue({
      name_ar: item.name_ar,
      name_en: item.name_en,
      days_allowed: item.days_allowed,
      is_paid: item.is_paid,
      requires_approval: item.requires_approval,
      carry_forward: item.carry_forward,
      max_carry_forward_days: item.max_carry_forward_days,
      gender: item.gender,
      description: item.description || '',
      status: item.status,
    });
    this.dialogVisible.set(true);
  }

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

    const data = { ...this.form.value };
    if (!data.carry_forward) {
      data.max_carry_forward_days = null;
    }

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

    this.saving.set(true);
    obs.subscribe({
      next: () => {
        this.saving.set(false);
        this.dialogVisible.set(false);
        this.reloadCurrentPage();
        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: HrLeaveType): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.LEAVE_TYPES.DELETE_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.leaveTypeService.delete(item.id).subscribe({
          next: () => {
            this.reloadCurrentPage();
            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';
  }

  get showCarryForwardDays(): boolean {
    return this.form.get('carry_forward')?.value === true;
  }

  private reloadCurrentPage(): void {
    const currentPage = Math.floor(this.first / this.rows) + 1;
    this.loadPage(currentPage);
  }
}
