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 { DatePickerModule } from 'primeng/datepicker';
import { TooltipModule } from 'primeng/tooltip';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrEosService } from '../../../core/services/hr-eos.service';
import { HrEmployeeService } from '../../../core/services/hr-employee.service';

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

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

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

  employees: any[] = [];

  form!: FormGroup;

  terminationReasonOptions = [
    { label: 'Resignation', value: 'resignation' },
    { label: 'Termination', value: 'termination' },
    { label: 'Retirement', value: 'retirement' },
    { label: 'Contract Expiry', value: 'contract_expiry' },
  ];

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

  private initForm(): void {
    this.form = this.fb.group({
      employee_id: [null, Validators.required],
      termination_date: [null, Validators.required],
      termination_reason: ['resignation', Validators.required],
      last_working_day: [null],
      other_entitlements: [0],
      deductions: [0],
      notes: [''],
    });
  }

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

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.eosService.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({ termination_reason: 'resignation', other_entitlements: 0, deductions: 0 });
    this.dialogVisible.set(true);
  }

  editItem(item: any): void {
    this.editingItem.set(item);
    this.form.patchValue({
      ...item,
      termination_date: item.termination_date ? new Date(item.termination_date) : null,
      last_working_day: item.last_working_day ? new Date(item.last_working_day) : null,
    });
    this.dialogVisible.set(true);
  }

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

    const data = { ...this.form.value };
    if (data.termination_date instanceof Date) {
      data.termination_date = this.formatDate(data.termination_date);
    }
    if (data.last_working_day instanceof Date) {
      data.last_working_day = this.formatDate(data.last_working_day);
    }

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

  calculateEos(item: any): void {
    this.processing.set(true);
    this.eosService.calculate(item.id).subscribe({
      next: () => {
        this.processing.set(false);
        this.loadPage();
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('HR.EOS.CALCULATED'),
        });
      },
      error: (err) => {
        this.processing.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Calculate failed',
        });
      },
    });
  }

  approveEos(item: any): void {
    this.processing.set(true);
    this.eosService.approve(item.id).subscribe({
      next: () => {
        this.processing.set(false);
        this.loadPage();
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('HR.EOS.APPROVED'),
        });
      },
      error: (err) => {
        this.processing.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Approve failed',
        });
      },
    });
  }

  payEos(item: any): void {
    this.processing.set(true);
    this.eosService.pay(item.id).subscribe({
      next: () => {
        this.processing.set(false);
        this.loadPage();
        this.messageService.add({
          severity: 'success',
          summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant('HR.EOS.PAID'),
        });
      },
      error: (err) => {
        this.processing.set(false);
        this.messageService.add({
          severity: 'error',
          summary: this.translate.instant('COMMON.ERROR'),
          detail: err.error?.message || 'Pay failed',
        });
      },
    });
  }

  getStatusSeverity(status: string): 'success' | 'info' | 'warn' | 'secondary' | 'contrast' | 'danger' {
    switch (status) {
      case 'draft': return 'secondary';
      case 'calculated': return 'info';
      case 'approved': return 'success';
      case 'paid': return 'contrast';
      default: return 'secondary';
    }
  }

  private formatDate(date: Date): string {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
}
