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 { 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 {
  ProductCategoriesActions,
  selectAllProductCategories,
  selectProductCategoriesLoading,
  selectProductCategoriesSaving,
  selectProductCategoriesError,
  UnitsActions,
  selectAllUnits,
} from '../../core/store';
import { ProductCategory } from '../../core/models/product-category.model';

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

  categories$ = this.store.select(selectAllProductCategories);
  loading$ = this.store.select(selectProductCategoriesLoading);
  saving$ = this.store.select(selectProductCategoriesSaving);
  error$ = this.store.select(selectProductCategoriesError);
  units$ = this.store.select(selectAllUnits);

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

  ngOnInit(): void {
    this.initForm();
    this.store.dispatch(ProductCategoriesActions.loadProductCategories({}));
    this.store.dispatch(UnitsActions.loadUnits({}));
  }

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

  private generateCategoryCode(): string {
    const num = Date.now().toString().slice(-6);
    return 'CAT-' + num;
  }

  openNew(): void {
    this.editingCategory.set(null);
    this.categoryForm.reset({ is_active: true, code: this.generateCategoryCode() });
    this.dialogVisible.set(true);
  }

  editCategory(category: ProductCategory): void {
    this.editingCategory.set(category);
    this.categoryForm.patchValue({
      code: category.code,
      name_ar: category.name_ar,
      name_en: category.name_en,
      parent_id: category.parent_id,
      description: category.description,
      is_active: category.is_active,
      default_unit_id: category.default_unit_id || null,
    });
    this.dialogVisible.set(true);
  }

  deleteCategory(category: ProductCategory): 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(ProductCategoriesActions.deleteProductCategory({ id: category.id }));
        const sub = this.store.select(selectProductCategoriesSaving).subscribe((saving) => {
          if (!saving) {
            sub.unsubscribe();
            this.store.select(selectProductCategoriesError).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' });
              }
            }).unsubscribe();
          }
        });
      },
    });
  }

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

      if (this.editingCategory()) {
        this.store.dispatch(ProductCategoriesActions.updateProductCategory({ id: this.editingCategory()!.id, category: data }));
      } else {
        this.store.dispatch(ProductCategoriesActions.createProductCategory({ category: data }));
      }

      const sub = this.store.select(selectProductCategoriesSaving).subscribe((saving) => {
        if (!saving) {
          sub.unsubscribe();
          this.store.select(selectProductCategoriesError).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',
              });
            }
          }).unsubscribe();
        }
      });
    } else {
      this.categoryForm.markAllAsTouched();
    }
  }

  retry(): void {
    this.store.dispatch(ProductCategoriesActions.loadProductCategories({ forceReload: true }));
  }
}
