import { Component, EventEmitter, Input, Output, SimpleChanges } from '@angular/core';
import { StationD3Model } from '../../../../../classes/d3/station.class';
import { verticalInOut } from '../../../../../common.animation';
import { KnowledgeService } from '../../../../../services/knowledge.service';
import { CommonNzModule } from './../../../../../common.nz.module';
import { ScrollWrapperComponent } from './../../../../../shared/scroll-wrapper/scroll-wrapper.component';

@Component({
  selector: 'datav-risk-panel',
  standalone: true,
  imports: [CommonNzModule, ScrollWrapperComponent],
  templateUrl: './risk-panel.component.html',
  styleUrl: './risk-panel.component.less',
  animations: [verticalInOut],
})
export class RiskPanelComponent {
  @Input() currentStation?: StationD3Model;
  @Input() visible = false;
  @Input() currentRiskItems: Knowledge.RiskItem[] = [];
  @Output() close = new EventEmitter<void>();
  @Output() onChange = new EventEmitter<number>();

  constructor(private knowledge: KnowledgeService) {}

  categories: Knowledge.RiskCategoryDto[] = [];
  items: Knowledge.RiskItem[] = [];
  currentCategoryId = -1;
  currentRiskItemId = -1;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['currentRiskItems']) {
      this.setCategories();
    }
  }

  setCategories() {
    const categoryIds = this.currentRiskItems.map(item => item.category).filter(Boolean);
    this.categories = this.knowledge.categories().filter(c => categoryIds.includes(c.id));
    this.currentCategoryId = this.categories[0]?.id || -1;
    this.items = [];

    if (this.currentCategoryId !== -1) {
      this.setItems(this.currentCategoryId);
    }
  }
  setItems(categoryId: number) {
    this.items = this.currentRiskItems.filter(item => item.category === categoryId);
    if (this.items.length > 0) {
      this.currentRiskItemId = this.items[0]?.id || -1;
      this.onChange.emit(this.currentRiskItemId);
    }
  }
  onCategoryClick(categoryId: number) {
    this.currentCategoryId = categoryId;
    this.setItems(categoryId);
  }

  onRiskItemClick(riskItemId: number) {
    this.currentRiskItemId = riskItemId;
    this.onChange.emit(riskItemId);
  }

  onClose() {
    // this.closeDetail();
    this.close.emit();
  }
}
