
import {
  ChangeDetectionStrategy,
  Component,
  HostBinding,
  Input,
  OnInit,
} from '@angular/core';
import { MatBadgeModule } from '@angular/material/badge';
import { MatIconModule } from '@angular/material/icon';
import { differenceInBusinessDays, formatDistanceToNow } from 'date-fns';
import { de } from 'date-fns/locale';
import {
  ApprovalState,
  Ticket,
  Tour,
} from '../../../core/data-access/graphql/generated/generated';
import CategoryColors from './category-colors';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'dks-ticket-item',
  templateUrl: './ticket-item.component.html',
  host: {
    class:
      'flex flex-col rounded-sm border-l-2 border-r-8 p-2 m-2 bg-white cursor-pointer',
  },
  styles: [
    `
      :host {
        box-shadow: var(--mat-sys-level2);
      }
    `,
  ],
  imports: [MatIconModule, MatBadgeModule],
})
export class TicketItemComponent implements OnInit {
  @Input() ticket!: Ticket & { tours: Tour[] };

  @HostBinding('style.border-left-color')
  leftBorderColor = '#ffffff';
  @HostBinding('style.border-right-color')
  rightBorderColor = '#ffffff';

  @HostBinding('style.background-color')
  backgroundColor = '#ffffff';

  ApprovalState = ApprovalState;

  ngOnInit(): void {
    this.leftBorderColor = this.getColorForCategory(
      this.ticket.tours.at(0)?.category
    );

    if (
      differenceInBusinessDays(new Date(this.ticket.urgency), new Date()) <= 2
    ) {
      this.rightBorderColor = '#f44336';
    }
  }

  getToursLength() {
    return this.ticket.tours.filter(({ check }) => check === 0).length;
  }

  getDistance(date: Date): string {
    return formatDistanceToNow(new Date(date), { locale: de });
  }

  // Static implementation for now. Colors could be loaded from DispoLive in the future, if necessary
  getColorForCategory(category: string | null | undefined): string {
    const categoryColor = CategoryColors.find(({ name }) => name === category);
    return categoryColor?.color ?? '#ffffff';
  }
}
