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

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

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

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

  form!: FormGroup;

  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: [''],
      start_time: ['', Validators.required],
      end_time: ['', Validators.required],
      working_hours: [8],
      break_duration: [0],
      grace_period: [0],
      is_night_shift: [false],
      status: ['active'],
    });
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.shiftService.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',
      working_hours: 8,
      break_duration: 0,
      grace_period: 0,
      is_night_shift: false,
    });
    this.dialogVisible.set(true);
  }

  editItem(item: HrShift): 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 };

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