import { Component, inject, OnInit, 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 {
  SequencesActions,
  selectAllSequences,
  selectSequencesLoading,
  selectSequencesSaving,
  selectSequencesError,
} from '../../core/store';
import { Sequence } from '../../core/models/sequence.model';

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

  readonly columns: TableColumn[] = [
    { field: 'name_ar', header: 'SEQUENCES.NAME', sortable: true },
    { field: 'module', header: 'SEQUENCES.MODULE', sortable: true },
    { field: 'entity', header: 'SEQUENCES.ENTITY', sortable: true },
    { field: 'prefix', header: 'SEQUENCES.PREFIX' },
    { field: 'digits', header: 'SEQUENCES.DIGITS' },
    { field: 'reset_frequency', header: 'SEQUENCES.RESET' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  sequences$ = this.store.select(selectAllSequences);
  loading$ = this.store.select(selectSequencesLoading);
  saving$ = this.store.select(selectSequencesSaving);
  error$ = this.store.select(selectSequencesError);

  dialogVisible = signal(false);
  editingSequence = signal<Sequence | null>(null);
  sequenceForm!: FormGroup;

  moduleOptions = [
    { label: 'Core', value: 'core' },
    { label: 'Accounting', value: 'accounting' },
    { label: 'Sales', value: 'sales' },
    { label: 'Purchases', value: 'purchases' },
    { label: 'Inventory', value: 'inventory' },
    { label: 'Manufacturing', value: 'manufacturing' },
  ];

  entityOptions = [
    { label: 'Business Partner', value: 'business_partner' },
    { label: 'Product', value: 'product' },
    { label: 'Journal Entry', value: 'journal_entry' },
    { label: 'Quotation', value: 'quotation' },
    { label: 'Sales Order', value: 'sales_order' },
    { label: 'Invoice', value: 'invoice' },
    { label: 'Sales Return', value: 'sales_return' },
    { label: 'Credit Note', value: 'credit_note' },
    { label: 'Receipt Voucher', value: 'receipt_voucher' },
    { label: 'Purchase Order', value: 'purchase_order' },
    { label: 'Bill', value: 'bill' },
    { label: 'Payment Voucher', value: 'payment_voucher' },
    { label: 'Stock Movement', value: 'stock_movement' },
    { label: 'Production Order', value: 'production_order' },
  ];

  resetFrequencyOptions = [
    { label: 'Never', value: 'never' },
    { label: 'Yearly', value: 'yearly' },
    { label: 'Monthly', value: 'monthly' },
  ];

  ngOnInit(): void {
    this.initForm();
    this.store.dispatch(SequencesActions.loadSequences({}));
  }

  private initForm(): void {
    this.sequenceForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      module: ['accounting', Validators.required],
      entity: ['journal_entry', Validators.required],
      prefix: [''],
      suffix: [''],
      include_year: [false],
      include_month: [false],
      digits: [4, [Validators.required, Validators.min(1), Validators.max(10)]],
      reset_frequency: ['never', Validators.required],
      per_branch: [false],
      is_active: [true],
    });
  }

  openNew(): void {
    this.editingSequence.set(null);
    this.sequenceForm.reset({
      module: 'accounting',
      entity: 'journal_entry',
      digits: 4,
      reset_frequency: 'never',
      include_year: false,
      include_month: false,
      per_branch: false,
      is_active: true,
    });
    this.dialogVisible.set(true);
  }

  editSequence(seq: Sequence): void {
    this.editingSequence.set(seq);
    this.sequenceForm.patchValue({
      name_ar: seq.name_ar,
      name_en: seq.name_en,
      module: seq.module,
      entity: seq.entity,
      prefix: seq.prefix,
      suffix: seq.suffix,
      include_year: seq.include_year,
      include_month: seq.include_month,
      digits: seq.digits,
      reset_frequency: seq.reset_frequency,
      per_branch: seq.per_branch,
      is_active: seq.is_active,
    });
    this.dialogVisible.set(true);
  }

  deleteSequence(seq: Sequence): void {
    this.confirmationService.confirm({
      message: `Delete sequence "${seq.name}"?`,
      header: 'Confirm Delete',
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.store.dispatch(SequencesActions.deleteSequence({ id: seq.id }));
        const sub = this.store.select(selectSequencesSaving).subscribe((saving) => {
          if (!saving) {
            sub.unsubscribe();
            this.store.select(selectSequencesError).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: 'Sequence deleted' });
              }
            }).unsubscribe();
          }
        });
      },
    });
  }

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

      if (this.editingSequence()) {
        this.store.dispatch(SequencesActions.updateSequence({ id: this.editingSequence()!.id, sequence: data }));
      } else {
        this.store.dispatch(SequencesActions.createSequence({ sequence: data }));
      }

      const sub = this.store.select(selectSequencesSaving).subscribe((saving) => {
        if (!saving) {
          sub.unsubscribe();
          this.store.select(selectSequencesError).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: 'Sequence saved' });
            }
          }).unsubscribe();
        }
      });
    } else {
      this.sequenceForm.markAllAsTouched();
    }
  }

  retry(): void {
    this.store.dispatch(SequencesActions.loadSequences({ forceReload: true }));
  }

  getPreview(): string {
    const f = this.sequenceForm.value;
    let result = f.prefix || '';
    if (f.include_year) result += '2026-';
    if (f.include_month) result += '02-';
    result += '0'.repeat(Math.max(0, (f.digits || 4) - 1)) + '1';
    if (f.suffix) result += f.suffix;
    return result;
  }
}
