import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BreadcrumbService } from '@core/breadcrumb';
import { Config } from '@core/config';
import { DateAdapter } from '@ui/common';
import { TaskCalendarStore } from '../../task-calendar.store';

@Component({
  selector: 'page-calendar',
  templateUrl: 'calendar.component.html',
  styleUrls: ['calendar.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CalendarComponent implements OnInit {
  readonly selectedDate$ = this.taskCalendarStore.selectSelectedDate;

  readonly displayedDate$ = this.taskCalendarStore.selectDisplayedDate;

  readonly indicators$ = this.taskCalendarStore.selectCalendarIndicators;

  readonly minDate = this.dateAdapter.addCalendarMonths(this.dateAdapter.today(), -6);

  readonly maxDate = this.dateAdapter.addCalendarMonths(this.dateAdapter.today(), 6);

  constructor(
    private taskCalendarStore: TaskCalendarStore,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private dateAdapter: DateAdapter,
    private breadcrumb: BreadcrumbService,
    private readonly _config: Config
  ) {}

  ngOnInit() {
    if (this.activatedRoute.snapshot.queryParams.displayDate) {
      this.setDisplayedDate(new Date(this.activatedRoute.snapshot.queryParams.displayDate));
    }

    this.updateBreadcrumb();

    this.taskCalendarStore.setMode({ mode: 'month' });
    this.taskCalendarStore.loadItems();
  }

  setSelectedDate = (date: Date) => {
    this.taskCalendarStore.setSelectedDate({ date });
    this.taskCalendarStore.setDisplayedDate({ date });
    this.router.navigate(['../tasks'], {
      queryParams: { selectedDate: date },
      relativeTo: this.activatedRoute,
    });
  };

  setDisplayedDate = (date: Date) => {
    this.taskCalendarStore.setDisplayedDate({ date });
    this.taskCalendarStore.loadItems();
    this.router.navigate([], {
      queryParams: { displayDate: date?.toJSON() },
    });

    this.updateBreadcrumb(date);
  };

  updateBreadcrumb(date?: Date) {
    this.breadcrumb.addOrUpdateBreadcrumbIfNotExists({
      key: this._config.get('process.ids.taskCalendar'),
      name: 'Tätigkeitskalender',
      path: '/filiale/task-calendar/calendar',
      tags: ['task-calendar'],
      section: 'branch',
      params: {
        displayDate: date?.toISOString(),
      },
    });
  }
}
