import { animate, animateChild, group, query, style, transition, trigger } from '@angular/animations';
import { inject } from '@angular/core';
import { Router, RouterOutlet } from '@angular/router';

const commonStyles = [style({ position: 'absolute', top: 0, left: 0, width: '100%' })];

const enterLeaveQueries = [
  query(':enter', [style({ left: '-100%' })], { optional: true }),
  query(':leave', animateChild(), { optional: true }),
];

const groupAnimations = (leaveDuration: string, enterDuration: string) =>
  group([
    query(':leave', [animate(leaveDuration, style({ left: '100%', opacity: 0 }))], { optional: true }),
    query(':enter', [animate(enterDuration, style({ left: '0%' }))], { optional: true }),
    query('@*', animateChild(), { optional: true }),
  ]);

export const slideInAnimation = trigger('routeAnimations', [
  transition('AuthPage <=> TaskPage', [
    style({ position: 'relative' }),
    query(':enter, :leave', commonStyles),
    ...enterLeaveQueries,
    groupAnimations('300ms ease-out', '300ms ease-out'),
  ]),
  transition('* <=> *', [
    style({ position: 'relative' }),
    query(':enter, :leave', commonStyles, { optional: true }),
    ...enterLeaveQueries,
    groupAnimations('200ms ease-out', '300ms ease-out'),
  ]),
]);

export class AnimationRouteComponent {
  private router = inject(Router);
  initialAnimationValue = '*';
  debounceTimeValue = '*';
  startTime: number = 0;

  setInitialAnimationValue() {
    const manageRoute = this.router.config.find(route => route.path === 'manager');
    if (!manageRoute) return;
    const matchSubRoute = manageRoute.children?.find(route => this.router.url.startsWith('/manager/' + route.path));
    this.initialAnimationValue = (matchSubRoute && matchSubRoute.data && matchSubRoute.data['animation']) || '*';
  }
  animationRoute(outlet: RouterOutlet) {
    const now = Date.now();
    const nowValue = (outlet && outlet.activatedRouteData && outlet.activatedRouteData['animation']) || '*';
    if (this.startTime === 0) {
      this.startTime = now;
      this.setInitialAnimationValue();
      this.debounceTimeValue = this.initialAnimationValue;
      return this.debounceTimeValue;
    }
    if (now - this.startTime < 20) {
      return this.debounceTimeValue;
    }
    this.startTime = now;
    this.debounceTimeValue = nowValue;
    return nowValue;
  }
}
