import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { catchError, EMPTY, from, tap } from 'rxjs';
import { horizontalInOutReverse300ms } from '../../../../common.animation';
import { CommonNzModule } from '../../../../common.nz.module';
import { CustomDrawerComponent } from '../../../../shared/custom-drawer/custom-drawer.component';
import { SearchParams } from '../hazard.utils';
import { ApiService } from './../../../../services/api.service';
import { SettingService } from './../../../../services/setting.service';
import { DataEmptyComponent } from './../../../../shared/data-empty/data-empty.component';
import { HazardCardComponent } from './card/card.component';
import { HazardDetailComponent } from './detail/detail.component';
import { HazardFormComponent, HazardFormComponentProps } from './hazard-form/hazard-form.component';
import { HazardSearchComponent } from './hazard-search/hazard-search.component';

export interface HazardDetailConfig {
  visible: boolean;
  data: Hazard.HazardDto;
}

@Component({
  selector: 'app-hazard-tracking',
  standalone: true,
  imports: [
    CommonNzModule,
    HazardCardComponent,
    HazardDetailComponent,
    CustomDrawerComponent,
    HazardFormComponent,
    HazardSearchComponent,
    DataEmptyComponent,
  ],
  templateUrl: './hazard-tracking.component.html',
  styleUrl: './hazard-tracking.component.less',
  animations: [horizontalInOutReverse300ms],
})
export class HazardTrackingComponent {
  @ViewChild('search') search!: HazardSearchComponent;
  @ViewChild('hazardForm') hazardForm!: HazardFormComponent;

  hazards: Hazard.HazardDto[] = [];
  loading = false;
  detailConfig: HazardDetailConfig = {
    visible: false,
    data: {} as Hazard.HazardDto,
  };
  pageConfig: IPageConfig = {
    page: 0,
    total: 0,
    size: 12,
  };
  formConfig: HazardFormComponentProps = {
    visible: false,
    data: undefined,
    isEdit: false,
  };
  ids?: number[];
  isTaskRelative = false;
  constructor(
    private api: ApiService,
    private setting: SettingService,
    private route: ActivatedRoute
  ) {
    this.route.queryParams.subscribe(params => {
      if (params['ids']) {
        this.isTaskRelative = true;
        if (Array.isArray(params['ids'])) {
          this.ids = params['ids'].map(Number);
        } else {
          this.ids = [params['ids']];
        }
      }
    });
  }
  ngOnInit() {
    this.fetchHazards();
  }
  getParams(): Hazard.GetHazardsParams {
    const { finalStatus, level, onlyMine } = this.search?.getParams() || {};
    const params: Hazard.GetHazardsParams = this.isTaskRelative
      ? {
          idList: this.ids,
          page: this.pageConfig.page,
          size: this.pageConfig.size,
          company: this.setting.userCompany,
        }
      : {
          page: this.pageConfig.page,
          size: this.pageConfig.size,
          company: this.setting.userCompany,
          level,
          finalStatus,
          showMyList: onlyMine ? 1 : undefined,
        };
    if (!level) {
      delete params.level;
    }
    if (!finalStatus) {
      delete params.finalStatus;
    }
    if (!onlyMine) {
      delete params.showMyList;
    }
    return params;
  }
  fetchHazards(callback?: () => void) {
    this.loading = true;
    from(this.api.hazard.getHazards(this.getParams()))
      .pipe(
        tap(res => {
          this.hazards = res.items;
          this.pageConfig.total = res.total;
          callback?.();
          this.loading = false;
        }),
        catchError(() => {
          this.loading = false;
          return EMPTY;
        })
      )
      .subscribe();
  }
  handleFetch() {
    this.pageConfig.page = 0;
    this.fetchHazards();
  }
  handleExitTaskRelative() {
    this.isTaskRelative = false;
    this.ids = undefined;
    this.handleFetch();
  }
  onPageChange(page: number) {
    this.pageConfig.page = page;
    this.fetchHazards();
  }
  onSearchParamsChange(p: SearchParams) {
    this.handleFetch();
  }
  handleViewDetail(data: Hazard.HazardDto) {
    this.detailConfig.visible = true;
    this.detailConfig.data = data;
  }
  handleCloseDetail() {
    this.detailConfig.visible = false;
  }
  async handleUpdate(id: number) {
    this.fetchHazards(() => {
      const hazard = this.hazards.find(h => h.id === id);
      if (hazard) {
        this.detailConfig = {
          ...this.detailConfig,
          data: hazard,
        };
      }
    });
  }
  handleAddHazard() {
    this.formConfig.visible = true;
    this.formConfig.isEdit = false;
  }
  handleEditHazard(data: Hazard.HazardDto) {
    this.formConfig.visible = true;
    this.formConfig.data = data;
    this.formConfig.isEdit = true;
  }
  closeFormDrawer() {
    this.hazardForm.reset();
    this.formConfig.visible = false;
  }
}
