import { Component, inject, OnInit, OnDestroy, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, FormArray, 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 { EntryTemplateService } from '../../core/services/entry-template.service';
import { EntryTemplate } from '../../core/models/entry-template.model';
import { AccountsActions, selectAllAccounts, CostCentersActions, selectAllCostCenters } from '../../core/store';

@Component({
  selector: 'app-entry-templates',
  standalone: true,
  imports: [
    CommonModule, ReactiveFormsModule, TranslateModule,
    TableModule, ButtonModule, InputTextModule, InputNumberModule,
    SelectModule, TagModule, ToastModule, ConfirmDialogModule, ToggleSwitchModule,
    PageHeaderComponent, DataTableComponent, FormDialogComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './entry-templates.component.html',
  styleUrl: './entry-templates.component.scss',
})
export class EntryTemplatesComponent implements OnInit, OnDestroy {
  readonly columns: TableColumn[] = [
    { field: 'name', header: 'ENTRY_TEMPLATES.NAME' },
    { field: 'type', header: 'ENTRY_TEMPLATES.TYPE' },
    { field: 'lines_count', header: 'ENTRY_TEMPLATES.LINES_COUNT' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  private fb = inject(FormBuilder);
  private store = inject(Store);
  private service = inject(EntryTemplateService);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);

  templates = signal<EntryTemplate[]>([]);
  totalRecords = signal(0);
  tableLoading = signal(false);
  first = 0;
  rows = 25;
  loading = signal(true);
  dialogVisible = signal(false);
  editing = signal<EntryTemplate | null>(null);
  saving = signal(false);

  accounts$ = this.store.select(selectAllAccounts);
  costCenters$ = this.store.select(selectAllCostCenters);

  form!: FormGroup;
  entryTypeOptions: any[] = [];
  private langSub!: Subscription;

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

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

  private buildOptions(): void {
    this.entryTypeOptions = [
      { label: this.translate.instant('ENTRY_TEMPLATES.TYPE_STANDARD'), value: 'standard' },
      { label: this.translate.instant('ENTRY_TEMPLATES.TYPE_ADJUSTMENT'), value: 'adjustment' },
      { label: this.translate.instant('ENTRY_TEMPLATES.TYPE_REVERSAL'), value: 'reversal' },
    ];
  }

  private initForm(): void {
    this.form = this.fb.group({
      name_ar: ['', Validators.required],
      name: [''],
      description_ar: [''],
      description: [''],
      entry_type: ['standard', Validators.required],
      is_active: [true],
      lines: this.fb.array([]),
    });
  }

  get lines(): FormArray {
    return this.form.get('lines') as FormArray;
  }

  private createLine(data?: any): FormGroup {
    return this.fb.group({
      account_id: [data?.account_id || null, Validators.required],
      debit: [data?.debit || 0],
      credit: [data?.credit || 0],
      description: [data?.description || ''],
      description_ar: [data?.description_ar || ''],
      cost_center_id: [data?.cost_center_id || null],
    });
  }

  addLine(): void {
    this.lines.push(this.createLine());
  }

  removeLine(i: number): void {
    this.lines.removeAt(i);
  }

  loadPage(page = 1, perPage = this.rows): void {
    this.tableLoading.set(true);
    this.loading.set(true);
    this.service.list(page, perPage).subscribe({
      next: (res) => {
        this.templates.set(res.data || []);
        this.totalRecords.set(res.meta?.total || 0);
        this.tableLoading.set(false);
        this.loading.set(false);
      },
      error: () => { this.tableLoading.set(false); this.loading.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);
  }

  private loadData(): void {
    this.loadPage(Math.floor(this.first / this.rows) + 1, this.rows);
  }

  openNew(): void {
    this.editing.set(null);
    this.form.reset({ entry_type: 'standard', is_active: true });
    this.lines.clear();
    this.addLine();
    this.dialogVisible.set(true);
  }

  edit(template: EntryTemplate): void {
    this.editing.set(template);
    this.form.patchValue({
      name_ar: template.name_ar,
      name: template.name,
      description_ar: template.description_ar,
      description: template.description,
      entry_type: template.entry_type,
      is_active: template.is_active,
    });
    this.lines.clear();
    (template.lines || []).forEach(l => this.lines.push(this.createLine(l)));
    if (this.lines.length === 0) this.addLine();
    this.dialogVisible.set(true);
  }

  delete(template: EntryTemplate): void {
    this.confirmationService.confirm({
      message: this.translate.instant('ENTRY_TEMPLATES.CONFIRM_DELETE'),
      header: this.translate.instant('COMMON.CONFIRM'),
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.service.delete(template.id).subscribe({
          next: () => {
            this.loadData();
            this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('ENTRY_TEMPLATES.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() ? 'ENTRY_TEMPLATES.UPDATE_SUCCESS' : 'ENTRY_TEMPLATES.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.loadPage(Math.floor(this.first / this.rows) + 1, this.rows); }
}
