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 { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
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, DataTableComponent, FormDialogComponent, TableColumn } from '../../shared';
import { Subscription } from 'rxjs';
import { AssetCategoryService } from '../../core/services/asset-category.service';
import { AssetCategory } from '../../core/models/asset-category.model';
import { AccountsActions, selectAllAccounts } from '../../core/store';

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

  readonly columns: TableColumn[] = [
    { field: 'code', header: 'ASSET_CATEGORIES.CODE' },
    { field: 'name', header: 'ASSET_CATEGORIES.NAME' },
    { field: 'depreciation_method', header: 'ASSET_CATEGORIES.METHOD' },
    { field: 'useful_life_months', header: 'ASSET_CATEGORIES.USEFUL_LIFE' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  items = signal<AssetCategory[]>([]);
  loading = signal(true);
  dialogVisible = signal(false);
  editing = signal<AssetCategory | null>(null);
  saving = signal(false);

  accounts$ = this.store.select(selectAllAccounts);
  depMethodOptions: any[] = [];
  private langSub!: Subscription;

  ngOnInit(): void {
    this.initForm();
    this.buildOptions();
    this.langSub = this.translate.onLangChange.subscribe(() => this.buildOptions());
    this.loadData();
    this.store.dispatch(AccountsActions.loadAccounts({}));
  }

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

  form!: FormGroup;

  private buildOptions(): void {
    this.depMethodOptions = [
      { label: this.translate.instant('ASSET_CATEGORIES.METHOD_STRAIGHT_LINE'), value: 'straight_line' },
      { label: this.translate.instant('ASSET_CATEGORIES.METHOD_DECLINING_BALANCE'), value: 'declining_balance' },
    ];
  }

  private initForm(): void {
    this.form = this.fb.group({
      name_ar: ['', Validators.required],
      name: [''],
      code: ['', Validators.required],
      depreciation_method: ['straight_line', Validators.required],
      useful_life_months: [60, Validators.required],
      asset_account_id: [null, Validators.required],
      depreciation_account_id: [null, Validators.required],
      accumulated_depreciation_account_id: [null, Validators.required],
      is_active: [true],
    });
  }

  private loadData(): void {
    this.loading.set(true);
    this.service.list(1, 100).subscribe({
      next: (res) => { this.items.set(res.data || []); this.loading.set(false); },
      error: () => this.loading.set(false),
    });
  }

  openNew(): void {
    this.editing.set(null);
    this.form.reset({ depreciation_method: 'straight_line', useful_life_months: 60, is_active: true });
    this.dialogVisible.set(true);
  }

  edit(item: AssetCategory): void {
    this.editing.set(item);
    this.form.patchValue(item);
    this.dialogVisible.set(true);
  }

  delete(item: AssetCategory): void {
    this.confirmationService.confirm({
      message: this.translate.instant('ASSET_CATEGORIES.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.CONFIRM'),
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.service.delete(item.id).subscribe({
          next: () => {
            this.loadData();
            this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('ASSET_CATEGORIES.DELETE_SUCCESS') });
          },
          error: (err) => this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed' }),
        });
      },
    });
  }

  onSave(): void {
    if (!this.form.valid) { this.form.markAllAsTouched(); return; }
    this.saving.set(true);
    const val = this.form.value;
    const data = { ...val, name: val.name || val.name_ar };

    const obs = this.editing()
      ? this.service.update(this.editing()!.id, data)
      : this.service.create(data);

    obs.subscribe({
      next: () => {
        this.saving.set(false);
        this.dialogVisible.set(false);
        this.loadData();
        this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'),
          detail: this.translate.instant(this.editing() ? 'ASSET_CATEGORIES.UPDATE_SUCCESS' : 'ASSET_CATEGORIES.CREATE_SUCCESS') });
      },
      error: (err) => {
        this.saving.set(false);
        this.messageService.add({ severity: 'error', summary: this.translate.instant('COMMON.ERROR'), detail: err.error?.message || 'Failed' });
      },
    });
  }

  retry(): void { this.loadData(); }
}
