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 { DatePickerModule } from 'primeng/datepicker';
import { TabsModule } from 'primeng/tabs';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared/components/page-header/page-header.component';
import { HrEmployeeService } from '../../../core/services/hr-employee.service';
import { HrEmployee } from '../../../core/models/hr-employee.model';
import { HrDepartmentService } from '../../../core/services/hr-department.service';
import { HrPositionService } from '../../../core/services/hr-position.service';
import { BranchService } from '../../../core/services/branch.service';

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

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

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

  departments: any[] = [];
  positions: any[] = [];
  branches: any[] = [];
  employees: any[] = [];

  form!: FormGroup;

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

  maritalStatusOptions = [
    { label: 'Single', value: 'single' },
    { label: 'Married', value: 'married' },
    { label: 'Divorced', value: 'divorced' },
    { label: 'Widowed', value: 'widowed' },
  ];

  contractTypeOptions = [
    { label: 'Full-time', value: 'full_time' },
    { label: 'Part-time', value: 'part_time' },
    { label: 'Contract', value: 'contract' },
    { label: 'Temporary', value: 'temporary' },
    { label: 'Probation', value: 'probation' },
  ];

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

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

  private initForm(): void {
    this.form = this.fb.group({
      // Personal info
      first_name_ar: ['', Validators.required],
      last_name_ar: ['', Validators.required],
      first_name_en: [''],
      last_name_en: [''],
      email: ['', Validators.email],
      phone: [''],
      mobile: [''],
      national_id: [''],
      gender: ['male', Validators.required],
      date_of_birth: [null],
      nationality: [''],
      marital_status: [null],
      // Employment info
      department_id: [null],
      position_id: [null],
      branch_id: [null],
      manager_id: [null],
      hire_date: [null, Validators.required],
      contract_type: ['full_time'],
      contract_end_date: [null],
      basic_salary: [0, [Validators.required, Validators.min(0)]],
      status: ['active'],
      address: [''],
      city: [''],
      // Emergency contact
      emergency_contact_name: [''],
      emergency_contact_phone: [''],
      // Bank info
      bank_name: [''],
      bank_account_number: [''],
      iban: [''],
      // Notes
      notes: [''],
    });
  }

  private loadDependencies(): void {
    this.departmentService.listAll().subscribe({
      next: (res) => (this.departments = res.data),
    });
    this.positionService.listAll().subscribe({
      next: (res) => (this.positions = res.data),
    });
    this.branchService.listAll().subscribe({
      next: (res) => (this.branches = res.data),
    });
    this.employeeService.listAll().subscribe({
      next: (res) => (this.employees = res.data),
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.employeeService.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({ gender: 'male', contract_type: 'full_time', status: 'active', basic_salary: 0 });
    this.dialogVisible.set(true);
  }

  editItem(item: HrEmployee): void {
    this.editingItem.set(item);
    this.form.patchValue({
      ...item,
      date_of_birth: item.date_of_birth ? new Date(item.date_of_birth) : null,
      hire_date: item.hire_date ? new Date(item.hire_date) : null,
      contract_end_date: item.contract_end_date ? new Date(item.contract_end_date) : null,
    });
    this.dialogVisible.set(true);
  }

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

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

    // Format dates as YYYY-MM-DD strings
    if (formVal.date_of_birth instanceof Date) {
      formVal.date_of_birth = this.formatDate(formVal.date_of_birth);
    }
    if (formVal.hire_date instanceof Date) {
      formVal.hire_date = this.formatDate(formVal.hire_date);
    }
    if (formVal.contract_end_date instanceof Date) {
      formVal.contract_end_date = this.formatDate(formVal.contract_end_date);
    }

    // Clean null optional foreign keys
    if (!formVal.department_id) delete formVal.department_id;
    if (!formVal.position_id) delete formVal.position_id;
    if (!formVal.branch_id) delete formVal.branch_id;
    if (!formVal.manager_id) delete formVal.manager_id;

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

    this.saving.set(true);
    obs.subscribe({
      next: () => {
        this.saving.set(false);
        this.dialogVisible.set(false);
        this.loadPage();
        this.loadDependencies();
        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: HrEmployee): void {
    this.confirmationService.confirm({
      message: this.translate.instant('HR.EMPLOYEES.DELETE_CONFIRM'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.employeeService.delete(item.id).subscribe({
          next: () => {
            this.loadPage();
            this.loadDependencies();
            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' {
    switch (status) {
      case 'active':
        return 'success';
      case 'inactive':
        return 'warn';
      case 'suspended':
        return 'warn';
      case 'terminated':
        return 'danger';
      default:
        return 'info';
    }
  }

  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}`;
  }
}
