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 { Subscription } from 'rxjs';
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 { TooltipModule } from 'primeng/tooltip';
import { ToggleSwitchModule } from 'primeng/toggleswitch';
import { TabsModule } from 'primeng/tabs';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent } from '../../../shared';
import {
  UsersActions,
  selectAllUsers,
} from '../../../core/store';
import {
  ApprovalWorkflow,
  ApprovalLog,
} from '../../../core/models/approval-workflow.model';
import { ApprovalWorkflowService } from '../../../core/services/approval-workflow.service';

@Component({
  selector: 'app-approval-workflows',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    InputNumberModule,
    SelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    TooltipModule,
    ToggleSwitchModule,
    TabsModule,
    PageHeaderComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './approval-workflows.component.html',
  styleUrl: './approval-workflows.component.scss',
})
export class ApprovalWorkflowsComponent implements OnInit, OnDestroy {
  private fb = inject(FormBuilder);
  private store = inject(Store);
  private messageService = inject(MessageService);
  private confirmationService = inject(ConfirmationService);
  private translate = inject(TranslateService);
  private service = inject(ApprovalWorkflowService);
  private langSub!: Subscription;

  users$ = this.store.select(selectAllUsers);

  activeTab = signal('workflows');

  // Workflows
  workflows = signal<ApprovalWorkflow[]>([]);
  workflowsLoading = signal(false);
  dialogVisible = signal(false);
  editingWorkflow = signal<ApprovalWorkflow | null>(null);
  workflowForm!: FormGroup;
  saving = signal(false);

  documentTypes = [
    { label: 'SALES.QUOTATION', value: 'sales_quotation' },
    { label: 'SALES.ORDER', value: 'sales_order' },
    { label: 'SALES.INVOICE', value: 'sales_invoice' },
    { label: 'SALES.RETURN', value: 'sales_return' },
    { label: 'SALES.PAYMENT', value: 'sales_payment' },
  ];

  approverTypes = [
    { label: 'SALES.USER', value: 'user' },
    { label: 'SALES.ROLE', value: 'role' },
  ];

  // Pending Approvals
  pendingApprovals = signal<ApprovalLog[]>([]);
  pendingLoading = signal(false);

  ngOnInit(): void {
    this.workflowForm = this.fb.group({
      name: ['', Validators.required],
      name_ar: [''],
      document_type: ['sales_quotation', Validators.required],
      is_active: [true],
      levels: this.fb.array([]),
    });

    this.langSub = this.translate.onLangChange.subscribe(() => {});
    this.loadWorkflows();
    this.loadPendingApprovals();
    this.store.dispatch(UsersActions.loadUsers({}));
  }

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

  get levelsArray(): FormArray {
    return this.workflowForm.get('levels') as FormArray;
  }

  // ─── Workflows ──────────────────────────────────────────

  loadWorkflows(): void {
    this.workflowsLoading.set(true);
    this.service.listAll().subscribe({
      next: (res) => {
        this.workflows.set(res.data);
        this.workflowsLoading.set(false);
      },
      error: () => this.workflowsLoading.set(false),
    });
  }

  openNewWorkflow(): void {
    this.editingWorkflow.set(null);
    this.workflowForm.reset({ name: '', name_ar: '', document_type: 'sales_quotation', is_active: true });
    this.levelsArray.clear();
    this.addLevel();
    this.dialogVisible.set(true);
  }

  editWorkflow(wf: ApprovalWorkflow): void {
    this.editingWorkflow.set(wf);
    this.workflowForm.patchValue({
      name: wf.name,
      name_ar: wf.name_ar || '',
      document_type: wf.document_type,
      is_active: wf.is_active,
    });
    this.levelsArray.clear();
    (wf.levels || []).forEach((lvl) => {
      this.levelsArray.push(
        this.fb.group({
          level: [lvl.level],
          approver_type: [lvl.approver_type, Validators.required],
          user_id: [lvl.user_id],
          role_id: [lvl.role_id],
          min_amount: [parseFloat(lvl.min_amount) || 0],
          max_amount: [parseFloat(lvl.max_amount) || 0],
          auto_approve: [lvl.auto_approve],
        })
      );
    });
    if (this.levelsArray.length === 0) this.addLevel();
    this.dialogVisible.set(true);
  }

  addLevel(): void {
    this.levelsArray.push(
      this.fb.group({
        level: [this.levelsArray.length + 1],
        approver_type: ['user', Validators.required],
        user_id: [null],
        role_id: [null],
        min_amount: [0],
        max_amount: [0],
        auto_approve: [false],
      })
    );
  }

  removeLevel(i: number): void {
    this.levelsArray.removeAt(i);
    this.levelsArray.controls.forEach((ctrl, idx) => {
      ctrl.get('level')?.setValue(idx + 1);
    });
  }

  deleteWorkflow(wf: ApprovalWorkflow): void {
    this.confirmationService.confirm({
      message: this.translate.instant('COMMON.CONFIRM_DELETE_MSG'),
      header: this.translate.instant('COMMON.CONFIRM'),
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.service.delete(wf.id).subscribe({
          next: () => {
            this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('COMMON.DELETED') });
            this.loadWorkflows();
          },
          error: (err) => this.showError(err),
        });
      },
    });
  }

  onSaveWorkflow(): void {
    if (!this.workflowForm.valid) {
      this.workflowForm.markAllAsTouched();
      return;
    }
    this.saving.set(true);
    const fv = this.workflowForm.value;
    const data: any = {
      name: fv.name,
      name_ar: fv.name_ar || null,
      document_type: fv.document_type,
      is_active: fv.is_active,
      levels: (fv.levels || []).map((lvl: any, idx: number) => ({
        level: idx + 1,
        approver_type: lvl.approver_type,
        user_id: lvl.approver_type === 'user' ? lvl.user_id : null,
        role_id: lvl.approver_type === 'role' ? lvl.role_id : null,
        min_amount: lvl.min_amount || 0,
        max_amount: lvl.max_amount || 0,
        auto_approve: lvl.auto_approve || false,
      })),
    };

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

    obs$.subscribe({
      next: () => {
        this.saving.set(false);
        this.dialogVisible.set(false);
        this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant(this.editingWorkflow() ? 'COMMON.UPDATED' : 'COMMON.CREATED') });
        this.loadWorkflows();
      },
      error: (err) => {
        this.saving.set(false);
        this.showError(err);
      },
    });
  }

  // ─── Pending Approvals ─────────────────────────────────

  loadPendingApprovals(): void {
    this.pendingLoading.set(true);
    this.service.getPendingApprovals().subscribe({
      next: (res) => {
        this.pendingApprovals.set(res.data || []);
        this.pendingLoading.set(false);
      },
      error: () => this.pendingLoading.set(false),
    });
  }

  approveLog(log: ApprovalLog): void {
    this.service.approveLog(log.id, {}).subscribe({
      next: () => {
        this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('SALES.APPROVED') });
        this.loadPendingApprovals();
      },
      error: (err) => this.showError(err),
    });
  }

  rejectLog(log: ApprovalLog): void {
    this.service.rejectLog(log.id, {}).subscribe({
      next: () => {
        this.messageService.add({ severity: 'success', summary: this.translate.instant('COMMON.SUCCESS'), detail: this.translate.instant('SALES.REJECTED') });
        this.loadPendingApprovals();
      },
      error: (err) => this.showError(err),
    });
  }

  // ─── Helpers ───────────────────────────────────────────

  retry(): void {
    this.loadWorkflows();
    this.loadPendingApprovals();
  }

  getDocTypeLabel(docType: string): string {
    const found = this.documentTypes.find((d) => d.value === docType);
    if (found) {
      const translated = this.translate.instant(found.label);
      return translated !== found.label ? translated : docType.replace(/_/g, ' ');
    }
    return docType.replace(/_/g, ' ');
  }

  private showError(err: any): void {
    this.messageService.add({
      severity: 'error',
      summary: this.translate.instant('COMMON.ERROR'),
      detail: err.error?.message || 'Operation failed',
    });
  }
}
