import { Component, inject, OnInit, OnDestroy, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { InputTextModule } from 'primeng/inputtext';
import { SelectModule } from 'primeng/select';
import { TagModule } from 'primeng/tag';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent, DataTableComponent, FormDialogComponent, TableColumn } from '../../shared';
import {
  CostCentersActions,
  selectAllCostCenters,
  selectCostCentersLoading,
  selectCostCentersSaving,
  selectCostCentersError,
} from '../../core/store';
import { CostCenter } from '../../core/models/cost-center.model';

@Component({
  selector: 'app-cost-centers',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    InputTextModule,
    SelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    PageHeaderComponent,
    DataTableComponent,
    FormDialogComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './cost-centers.component.html',
  styleUrl: './cost-centers.component.scss',
})
export class CostCentersComponent implements OnInit, OnDestroy {
  private fb = inject(FormBuilder);
  private store = inject(Store);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private langSub!: Subscription;

  readonly columns: TableColumn[] = [
    { field: 'code', header: 'COST_CENTERS.CODE', sortable: true },
    { field: 'name_ar', header: 'COST_CENTERS.NAME_AR', sortable: true },
    { field: 'level', header: 'COST_CENTERS.LEVEL' },
    { field: 'parent', header: 'COST_CENTERS.PARENT' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  costCenters$ = this.store.select(selectAllCostCenters);
  loading$ = this.store.select(selectCostCentersLoading);
  saving$ = this.store.select(selectCostCentersSaving);
  error$ = this.store.select(selectCostCentersError);

  dialogVisible = signal(false);
  editingCostCenter = signal<CostCenter | null>(null);
  costCenterForm!: FormGroup;

  statusOptions: any[] = [];
  parentCostCenters: CostCenter[] = [];

  ngOnInit(): void {
    this.initForm();
    this.buildOptions();
    this.langSub = this.translate.onLangChange.subscribe(() => this.buildOptions());
    this.store.dispatch(CostCentersActions.loadCostCenters({}));
    this.costCenters$.subscribe((centers) => {
      this.parentCostCenters = centers;
    });
  }

  ngOnDestroy(): void {
    this.langSub?.unsubscribe();
  }

  private buildOptions(): void {
    this.statusOptions = [
      { label: this.translate.instant('COMMON.ACTIVE'), value: 'active' },
      { label: this.translate.instant('COMMON.INACTIVE'), value: 'inactive' },
    ];
  }

  private initForm(): void {
    this.costCenterForm = this.fb.group({
      code: ['', Validators.required],
      name_ar: ['', Validators.required],
      name_en: [''],
      parent_id: [null],
      description: [''],
      status: ['active'],
    });
  }

  openNew(): void {
    this.editingCostCenter.set(null);
    this.costCenterForm.reset({ status: 'active' });
    this.dialogVisible.set(true);
  }

  editCostCenter(cc: CostCenter): void {
    this.editingCostCenter.set(cc);
    this.costCenterForm.patchValue({
      code: cc.code,
      name_ar: cc.name_ar,
      name_en: cc.name_en,
      parent_id: cc.parent_id,
      description: cc.description,
      status: cc.status || 'active',
    });
    this.dialogVisible.set(true);
  }

  deleteCostCenter(cc: CostCenter): void {
    if (cc.has_children) return;
    this.confirmationService.confirm({
      message: this.translate.instant('COST_CENTERS.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.store.dispatch(CostCentersActions.deleteCostCenter({ id: cc.id }));
        const sub = this.store.select(selectCostCentersSaving).subscribe((saving) => {
          if (!saving) {
            sub.unsubscribe();
            this.store.select(selectCostCentersError).pipe(take(1)).subscribe((error) => {
              if (error) {
                this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: error });
              } else {
                this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('COST_CENTERS.DELETE_SUCCESS') });
              }
            });
          }
        });
      },
    });
  }

  onSave(): void {
    if (this.costCenterForm.valid) {
      const formValue = this.costCenterForm.value;
      const data = { ...formValue, name: formValue.name_ar };

      if (this.editingCostCenter()) {
        this.store.dispatch(CostCentersActions.updateCostCenter({ id: this.editingCostCenter()!.id, costCenter: data }));
      } else {
        this.store.dispatch(CostCentersActions.createCostCenter({ costCenter: data }));
      }

      const sub = this.store.select(selectCostCentersSaving).subscribe((saving) => {
        if (!saving) {
          sub.unsubscribe();
          this.store.select(selectCostCentersError).pipe(take(1)).subscribe((error) => {
            if (error) {
              this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: error });
            } else {
              this.dialogVisible.set(false);
              this.messageService.add({
                severity: 'success',
                summary: this.translate.instant('COMMON.SUCCESS'),
                detail: this.editingCostCenter()
                  ? this.translate.instant('COST_CENTERS.UPDATE_SUCCESS')
                  : this.translate.instant('COST_CENTERS.CREATE_SUCCESS'),
              });
            }
          });
        }
      });
    } else {
      this.costCenterForm.markAllAsTouched();
    }
  }

  retry(): void {
    this.store.dispatch(CostCentersActions.loadCostCenters({ forceReload: true }));
  }
}
