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 { ToggleSwitchModule } from 'primeng/toggleswitch';
import { MessageService, ConfirmationService } from 'primeng/api';
import { PageHeaderComponent, DataTableComponent, FormDialogComponent, TableColumn } from '../../shared';
import {
  PartnerCategoriesActions,
  selectAllPartnerCategories,
  selectPartnerCategoriesLoading,
  selectPartnerCategoriesSaving,
  selectPartnerCategoriesError,
} from '../../core/store';
import { PartnerCategory } from '../../core/models/partner-category.model';

@Component({
  selector: 'app-partner-categories',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TranslateModule,
    TableModule,
    ButtonModule,
    InputTextModule,
    SelectModule,
    TagModule,
    ToastModule,
    ConfirmDialogModule,
    ToggleSwitchModule,
    PageHeaderComponent,
    DataTableComponent,
    FormDialogComponent,
  ],
  providers: [MessageService, ConfirmationService],
  templateUrl: './partner-categories.component.html',
  styleUrl: './partner-categories.component.scss',
})
export class PartnerCategoriesComponent 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: 'name_ar', header: 'PARTNER_CATEGORIES.NAME_AR', sortable: true },
    { field: 'name_en', header: 'PARTNER_CATEGORIES.NAME_EN', sortable: true },
    { field: 'scope', header: 'PARTNER_CATEGORIES.SCOPE' },
    { field: 'status', header: 'COMMON.STATUS' },
    { field: 'actions', header: 'COMMON.ACTIONS' },
  ];

  categories$ = this.store.select(selectAllPartnerCategories);
  loading$ = this.store.select(selectPartnerCategoriesLoading);
  saving$ = this.store.select(selectPartnerCategoriesSaving);
  error$ = this.store.select(selectPartnerCategoriesError);

  dialogVisible = signal(false);
  editingCategory = signal<PartnerCategory | null>(null);
  categoryForm!: FormGroup;

  scopeOptions: any[] = [];

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

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

  private buildOptions(): void {
    this.scopeOptions = [
      { label: this.translate.instant('PARTNER_CATEGORIES.SCOPE_CUSTOMER'), value: 'customer' },
      { label: this.translate.instant('PARTNER_CATEGORIES.SCOPE_SUPPLIER'), value: 'supplier' },
      { label: this.translate.instant('PARTNER_CATEGORIES.SCOPE_BOTH'), value: 'both' },
    ];
  }

  private initForm(): void {
    this.categoryForm = this.fb.group({
      name_ar: ['', Validators.required],
      name_en: [''],
      scope: ['both'],
      description: [''],
      is_active: [true],
    });
  }

  openNew(): void {
    this.editingCategory.set(null);
    this.categoryForm.reset({ is_active: true, scope: 'both' });
    this.dialogVisible.set(true);
  }

  editCategory(category: PartnerCategory): void {
    this.editingCategory.set(category);
    this.categoryForm.patchValue({
      name_ar: category.name_ar,
      name_en: category.name_en,
      scope: category.scope || 'both',
      description: category.description,
      is_active: category.is_active,
    });
    this.dialogVisible.set(true);
  }

  deleteCategory(category: PartnerCategory): void {
    this.confirmationService.confirm({
      message: `Are you sure you want to delete "${category.name}"?`,
      header: 'Confirm Delete',
      icon: 'pi pi-exclamation-triangle',
      acceptButtonStyleClass: 'p-button-danger',
      accept: () => {
        this.store.dispatch(PartnerCategoriesActions.deletePartnerCategory({ id: category.id }));
        const sub = this.store.select(selectPartnerCategoriesSaving).subscribe((saving) => {
          if (!saving) {
            sub.unsubscribe();
            this.store.select(selectPartnerCategoriesError).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: 'Category deleted successfully' });
              }
            });
          }
        });
      },
    });
  }

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

      if (this.editingCategory()) {
        this.store.dispatch(PartnerCategoriesActions.updatePartnerCategory({ id: this.editingCategory()!.id, category: data }));
      } else {
        this.store.dispatch(PartnerCategoriesActions.createPartnerCategory({ category: data }));
      }

      const sub = this.store.select(selectPartnerCategoriesSaving).subscribe((saving) => {
        if (!saving) {
          sub.unsubscribe();
          this.store.select(selectPartnerCategoriesError).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.editingCategory() ? 'Category updated successfully' : 'Category created successfully',
              });
            }
          });
        }
      });
    } else {
      this.categoryForm.markAllAsTouched();
    }
  }

  retry(): void {
    this.store.dispatch(PartnerCategoriesActions.loadPartnerCategories({ forceReload: true }));
  }
}
