import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AdminProduct, AdminProductCategoryOption, AdminProductListFilters } from '../models/admin-product.model';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';
import { InputComponent } from '../../../../shared/ui/input/input.component';
import { BadgeComponent } from '../../../../shared/ui/badge/badge.component';
import { TableComponent } from '../../../../shared/ui/table/table.component';
import { PaginationComponent } from '../../../../shared/ui/pagination/pagination.component';
import { SkeletonComponent } from '../../../../shared/ui/skeleton/skeleton.component';
import { EmptyStateComponent } from '../../../../shared/ui/empty-state/empty-state.component';
import { CardComponent } from '../../../../shared/ui/card/card.component';
import { DialogComponent } from '../../../../shared/ui/dialog/dialog.component';
import { ProductHealthWidgetComponent, ProductHealthItem } from './product-health-widget/product-health-widget.component';
import { ProductsDashboardComponent } from './products-dashboard/products-dashboard.component';
import { AdminProductColumn, AdminProductHealth, AdminProductsDashboardStats, AdminProductsDensity, AdminProductsViewMode, ALL_PRODUCT_COLUMNS } from '../facade/admin-products.facade';

@Component({
  selector: 'app-admin-products-list',
  standalone: true,
  imports: [
    FormsModule,
    TranslatePipe,
    ButtonComponent,
    InputComponent,
    BadgeComponent,
    TableComponent,
    PaginationComponent,
    SkeletonComponent,
    EmptyStateComponent,
    CardComponent,
    DialogComponent,
    ProductHealthWidgetComponent,
    ProductsDashboardComponent,
  ],
  templateUrl: './admin-products-list.component.html',
  styleUrls: ['./admin-products-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminProductsListComponent {
  @Input() products: AdminProduct[] = [];
  @Input() categories: AdminProductCategoryOption[] = [];
  @Input() filters!: AdminProductListFilters;
  @Input() total = 0;
  @Input() selectedIds: string[] = [];
  @Input() loading = false;
  @Input() error: string | null = null;
  @Input() infiniteScroll = false;
  @Input() viewMode: AdminProductsViewMode = 'table';
  @Input() density: AdminProductsDensity = 'comfortable';
  @Input() visibleColumns: AdminProductColumn[] = [...ALL_PRODUCT_COLUMNS];
  @Input() dashboardStats: AdminProductsDashboardStats | null = null;
  @Input() health!: (product: AdminProduct) => AdminProductHealth;

  @Output() filtersChange = new EventEmitter<Partial<AdminProductListFilters>>();
  @Output() create = new EventEmitter<void>();
  @Output() edit = new EventEmitter<string>();
  @Output() duplicate = new EventEmitter<string>();
  @Output() delete = new EventEmitter<string>();
  @Output() selectionChange = new EventEmitter<{ id: string; checked: boolean }>();
  @Output() selectAll = new EventEmitter<boolean>();
  @Output() bulkVisibility = new EventEmitter<boolean>();
  @Output() bulkDelete = new EventEmitter<void>();
  @Output() bulkDuplicate = new EventEmitter<void>();
  @Output() bulkAssignCategory = new EventEmitter<string>();
  @Output() bulkAssignTags = new EventEmitter<string[]>();
  @Output() bulkExport = new EventEmitter<void>();
  @Output() archive = new EventEmitter<string>();
  @Output() restore = new EventEmitter<string>();
  @Output() loadMore = new EventEmitter<void>();
  @Output() infiniteScrollToggle = new EventEmitter<boolean>();
  @Output() viewModeChange = new EventEmitter<AdminProductsViewMode>();
  @Output() densityChange = new EventEmitter<AdminProductsDensity>();
  @Output() columnToggle = new EventEmitter<{ column: AdminProductColumn; visible: boolean }>();

  protected readonly allColumns = ALL_PRODUCT_COLUMNS;
  protected readonly columnsPanelOpen = signal(false);
  protected readonly assignCategoryOpen = signal(false);
  protected readonly assignTagsOpen = signal(false);
  protected readonly tagsInput = signal('');

  isSelected(id: string): boolean {
    return this.selectedIds.includes(id);
  }

  totalPages(): number {
    return Math.max(1, Math.ceil(this.total / this.filters.pageSize));
  }

  isColumnVisible(column: AdminProductColumn): boolean {
    return this.visibleColumns.includes(column);
  }

  healthItems(product: AdminProduct): ProductHealthItem[] {
    const health = this.health(product);
    return [
      { labelKey: 'adminProducts.healthImages', done: health.hasImages },
      { labelKey: 'adminProducts.healthSeo', done: health.hasSeo },
      { labelKey: 'adminProducts.healthPrice', done: health.hasPrice },
      { labelKey: 'adminProducts.healthCategory', done: health.hasCategory },
      { labelKey: 'adminProducts.healthDescription', done: health.hasDescription },
      { labelKey: 'adminProducts.healthInventory', done: health.hasInventory },
    ];
  }

  openAssignCategory(): void {
    this.assignCategoryOpen.set(true);
  }

  confirmAssignCategory(categoryId: string): void {
    this.bulkAssignCategory.emit(categoryId);
    this.assignCategoryOpen.set(false);
  }

  openAssignTags(): void {
    this.tagsInput.set('');
    this.assignTagsOpen.set(true);
  }

  confirmAssignTags(): void {
    const tags = this.tagsInput().split(',').map(t => t.trim()).filter(Boolean);
    if (tags.length > 0) {
      this.bulkAssignTags.emit(tags);
    }
    this.assignTagsOpen.set(false);
  }
}
