import {
  Component,
  ElementRef,
  EventEmitter,
  Input,
  Output,
  ViewChild,
} from '@angular/core';

@Component({
  selector: 'app-date-switcher',
  templateUrl: './date-switcher.component.html',
  styleUrls: ['./date-switcher.component.scss'],
})
export class DateSwitcherComponent {
  @Input() date: Date = new Date();
  @Input() maxDate?: Date;
  @Input() minDate?: Date;

  @Output() dateChange = new EventEmitter<Date>();

  @ViewChild('inputDate') inputDate!: ElementRef<HTMLInputElement>;

  weekDays = [
    'Domingo',
    'Segunda-feira',
    'Terça-feira',
    'Quarta-feira',
    'Quinta-feira',
    'Sexta-feira',
    'Sábado',
  ];

  getDifferenceInDays(): number {
    const today = new Date();
    const date = new Date(this.date);

    return Math.floor(
      (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) -
        Date.UTC(today.getFullYear(), today.getMonth(), today.getDate())) /
        (1000 * 60 * 60 * 24),
    );
  }

  previousDay(): void {
    const newDate = new Date(this.date);
    newDate.setDate(this.date.getDate() - 1);

    if (!this.canUpdateDate(newDate)) return;

    this.date = newDate;
    this.dateChange.emit(this.date);
  }

  getDate(date: Date) {
    return date.toISOString().split('T')[0];
  }

  nextDay(): void {
    const newDate = new Date(this.date);
    newDate.setDate(this.date.getDate() + 1);

    if (!this.canUpdateDate(newDate)) return;

    this.date = newDate;
    this.dateChange.emit(this.date);
  }

  canUpdateDate(newDate: Date): boolean {
    const newUtcDate = this.getUTCDate(newDate);

    if (this.minDate && newUtcDate < this.getUTCDate(this.minDate))
      return false;
    if (this.maxDate && newUtcDate > this.getUTCDate(this.maxDate))
      return false;

    return true;
  }

  getFormattedDate(): string {
    const dateFormatter = Intl.DateTimeFormat('pt-br', {
      weekday: 'long',
      day: '2-digit',
      month: '2-digit',
      year: '2-digit',
    });

    return dateFormatter.format(this.date);
  }

  getUTCDate(dateToFormat: Date): Date {
    const timezoneOffset = dateToFormat.getTimezoneOffset();
    return new Date(dateToFormat.getTime() + timezoneOffset * 60000);
  }

  openDateDialog() {
    if (!this.inputDate?.nativeElement) return;

    const input = this.inputDate.nativeElement;
    input.showPicker();
  }

  handleDateChange(ev: Event) {
    const date = (ev.target as HTMLInputElement).value;
    const newDate = new Date(date);

    if (!this.canUpdateDate(newDate)) return;

    this.date = this.getUTCDate(newDate);
    this.dateChange.emit(this.date);
  }
}
