import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Input,
  Renderer2,
  ViewChild,
} from '@angular/core';
import { uuid } from '@utils/uuid.util';
import { OverlayTriggerForDirective } from '@ui/overlay/overlay-trigger-for.directive';
import { ConnectedPosition } from '@angular/cdk/overlay';
import { UiIconType } from '@ui/icon/icon-type.enum';
import { UiIconSize } from '@ui/icon/icon-size.enum';

export enum UiPopoverPosition {
  Top,
  Bottom,
}

@Component({
  selector: 'ui-popover',
  templateUrl: './ui-popover.component.html',
  styleUrls: ['./ui-popover.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiPopoverComponent implements AfterViewInit {
  UiIconType = UiIconType;
  UiIconSize = UiIconSize;
  @ViewChild(OverlayTriggerForDirective) overlayRef: OverlayTriggerForDirective;
  panelId = `panel-${uuid()}`;
  @Input() uiAriaLabel: string;
  @Input() uiButtonText?: string = 'Info';
  @Input() buttonElementId: string = uuid();
  @Input() uiPopoverPosition: UiPopoverPosition = UiPopoverPosition.Top;
  @ViewChild('triggerButton') triggerButton: ElementRef;
  @ViewChild('content') content: ElementRef;
  @ViewChild('arrow') arrow: ElementRef;
  readonly offsetPixels = -30;

  @ViewChild('popoverButton') popoverButton: ElementRef;

  get overlayPositions(): ConnectedPosition[] {
    switch (this.uiPopoverPosition) {
      case UiPopoverPosition.Top:
        return [
          {
            originX: 'center',
            originY: 'top',
            overlayX: 'center',
            overlayY: 'bottom',
            offsetY: this.offsetPixels,
          },
        ];
      case UiPopoverPosition.Bottom:
        return [
          {
            originX: 'center',
            originY: 'bottom',
            overlayX: 'center',
            overlayY: 'top',
            offsetY: -this.offsetPixels,
          },
        ];
    }
  }

  constructor(private renderer: Renderer2) {}

  closePopover(): void {
    this.overlayRef.closeOverlay();
  }

  ngAfterViewInit(): void {
    switch (this.uiPopoverPosition) {
      case UiPopoverPosition.Top:
        this.moveArrowBottom();
        break;
      case UiPopoverPosition.Bottom:
        this.moveArrowTop();
        break;
      default:
        throw new Error('uiPopoverPosition is mandatory');
    }
  }

  moveArrowBottom() {
    this.renderer.setStyle(this.arrow.nativeElement, 'transform', 'rotate(90deg)');
    this.renderer.setStyle(this.arrow.nativeElement, 'bottom', `${this.offsetPixels + 6}px `);
  }

  moveArrowTop() {
    this.renderer.setStyle(this.arrow.nativeElement, 'transform', 'rotate(-90deg)');
    this.renderer.setStyle(this.arrow.nativeElement, 'top', `${this.offsetPixels + 7}px `);
  }
}
