import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  HostBinding,
  HostListener,
  Input,
  Output,
} from '@angular/core';
import { DialogService } from '@ngneat/dialog';

import { AnomalySolutionDialogComponent } from '../anomaly-solution-dialog/anomaly-solution-dialog.component';
import { ConfirmDialogComponent } from '../../../../core/components/confirm-dialog/confirm-dialog.component';

interface Anomaly {
  __typename?: 'Anomaly' | undefined;
  id: string;
  type: string;
  description: string;
  sleepTimer: number;
  sleepSince?: Date;
  workedOnBy: string;
  resolvedAt?: Date;
  createdAt: Date;
  solution: {
    __typename?: 'SolutionTarget' | undefined;
    name: string;
    steps: {
      description: string;
    }[];
  }[];
}

@Component({
  selector: 'dks-anomaly-list-item',
  templateUrl: './anomaly-list-item.component.html',
  styleUrls: ['./anomaly-list-item.component.css'],
  host: {
    class: 'w-full rounded flex items-center',
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class AnomalyListItemComponent {
  isHovering = false;

  @Input() anomaly!: Anomaly;
  @Output() anomalySetToSleep = new EventEmitter<string>();
  @Output() anomalyAccepted = new EventEmitter<string>();

  @HostListener('mouseenter')
  onMouseEnter() {
    this.isHovering = true;
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.isHovering = false;
  }

  @HostBinding('class')
  private get hostClass(): string {
    return this.isHovering ? 'mat-elevation-z1' : '';
  }

  constructor(private readonly dialog: DialogService) {}

  setAnomalyToSleep(id: string) {
    this.anomalySetToSleep.emit(id);
  }

  acceptAnomaly(id: string) {
    this.dialog
      .open(ConfirmDialogComponent, {
        data: {
          title: 'Ist dies kein Fehler?',
          body: 'Sind sie sicher, dass diese Anomalie kein Fehler ist? Dann bestätigen Sie diesen Dialog',
        },
        width: 500,
      })
      .afterClosed$.subscribe(
        (confirmed) => confirmed && this.anomalyAccepted.emit(id)
      );
  }

  showSolutionDialog(): void {
    const dialogRef = this.dialog.open(AnomalySolutionDialogComponent, {
      data: {
        title: this.anomaly.description,
        solution: this.anomaly.solution,
        anomalyId: this.anomaly.id,
      },
    });
    dialogRef.afterClosed$.subscribe((result) => {
      if (result === 'sleep') {
        this.setAnomalyToSleep(this.anomaly.id);
      } else if (result === 'accept') {
        this.acceptAnomaly(this.anomaly.id);
      }
    });
  }
}
