import {
  Component,
  DestroyRef,
  effect,
  inject,
  input,
  signal,
} from '@angular/core';
import {
  Anomaly,
  AttendanceRegistration,
  Employee,
  GetAnomaliesAssociatedEntitiesGQL,
  GetAnomalyGQL,
  PlannedTime,
  Tour,
  WorkTime,
} from '../../../core/data-access/graphql/generated/generated';
import { map, tap } from 'rxjs';
import { KeyValuePipe } from '@angular/common';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-anomaly-view',
  imports: [KeyValuePipe],
  templateUrl: './anomaly-view.component.html',
  styles: ``,
})
export class AnomalyViewComponent {
  anomalyId = input.required<string>();

  anomalyByIdGql = inject(GetAnomalyGQL);
  associatedEntitiesGql = inject(GetAnomaliesAssociatedEntitiesGQL);
  destroyRef = inject(DestroyRef);

  anomaly = signal<Anomaly | undefined>(undefined);
  tours = signal<Partial<Tour>[]>([]);
  plannedTimes = signal<PlannedTime[]>([]);
  workTimes = signal<WorkTime[]>([]);
  attendanceRegistrations = signal<AttendanceRegistration[]>([]);
  employees = signal<Employee[]>([]);

  constructor() {
    effect(() => {
      this.anomalyByIdGql
        .fetch({ id: this.anomalyId() })
        .pipe(
          takeUntilDestroyed(this.destroyRef),
          tap((res) => this.anomaly.set(res.data.anomaly))
        )
        .subscribe();
      this.associatedEntitiesGql
        .fetch({ id: this.anomalyId() })
        .pipe(
          takeUntilDestroyed(this.destroyRef),
          map((res) => res.data.associatedEntities),
          tap(
            ({
              tour,
              attendanceRegistration,
              plannedTime,
              workTime,
              employee,
            }) => {
              if (tour) this.tours.set(tour as Tour[]);
              if (attendanceRegistration)
                this.attendanceRegistrations.set(attendanceRegistration);
              if (plannedTime) this.plannedTimes.set(plannedTime);
              if (workTime) this.workTimes.set(workTime);
              if (employee) this.employees.set(employee);
            }
          )
        )
        .subscribe();
    });
  }

  ngOnInit() {
    console.log(this.anomalyId());
  }
}
