import { SelectionModel } from '@angular/cdk/collections';
import { DatePipe, NgClass } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnInit
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatTableModule } from '@angular/material/table';
import { RoleDirective } from '../../../core/components/ms-authentication/role.directive';
import {
  Ticket,
  Tour,
} from '../../../core/data-access/graphql/generated/generated';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'dks-ticket-tours',
    template: ` <div class="max-h-96 overflow-y-auto">
    <table mat-table [dataSource]="dataSource" class="w-full">
      <ng-container matColumnDef="select">
        <th mat-header-cell *matHeaderCellDef>
          <mat-checkbox
            (change)="$event ? toggleAllRows() : null"
            [checked]="selection.hasValue() && isAllSelected()"
            [indeterminate]="selection.hasValue() && !isAllSelected()"
          >
          </mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let row">
          <mat-checkbox
            (click)="$event.stopPropagation()"
            (change)="$event ? selection.toggle(row) : null"
            [checked]="selection.isSelected(row)"
          >
          </mat-checkbox>
        </td>
      </ng-container>

      <ng-container matColumnDef="operationId">
        <th mat-header-cell *matHeaderCellDef>Einsatznummer</th>
        <td mat-cell *matCellDef="let tour">{{ tour.operationId }}</td>
      </ng-container>
      <ng-container matColumnDef="startDate">
        <th mat-header-cell *matHeaderCellDef>Anfahrt</th>
        <td mat-cell *matCellDef="let tour">
          {{ tour.startDate | date : 'HH:mm' }} Uhr<br />
          {{ tour.startDate | date : 'dd.MM.yy' }}
        </td>
      </ng-container>
      <ng-container matColumnDef="startAddress">
        <th mat-header-cell *matHeaderCellDef>Von</th>
        <td mat-cell *matCellDef="let tour">
          {{ tour.startStreet }}<br />{{ tour.startZip }} {{ tour.startCity }}
        </td>
      </ng-container>
      <ng-container matColumnDef="targetAddress">
        <th mat-header-cell *matHeaderCellDef>Nach</th>
        <td mat-cell *matCellDef="let tour">
          {{ tour.targetStreet }}<br />{{ tour.targetZip }}
          {{ tour.targetCity }}
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="columns"></tr>
      <tr
        mat-row
        *matRowDef="let row; columns: columns"
        class="border-l-8 border-white"
        [title]="getTourStateTooltip(row)"
        [ngClass]="{
          '!border-gray-400': row.check > 1,
          '!border-yellow-500': row.check === 1,
          '!border-green-700': !!row.empty && row.check < 1
        }"
      ></tr>
    </table>
  </div>`,
    imports: [
        NgClass,
        DatePipe,
        MatButtonModule,
        MatCheckboxModule,
        MatTableModule,
    ]
})
export class TicketToursComponent implements OnInit {
  @Input() ticket!: Ticket & { tours: Tour[] };

  dataSource!: Tour[];

  columns = [
    'select',
    'operationId',
    'startDate',
    'startAddress',
    'targetAddress',
  ];

  initialSelection = [];
  allowMultiSelect = true;
  selection = new SelectionModel<Tour>(
    this.allowMultiSelect,
    this.initialSelection
  );

  ngOnInit(): void {
    console.log(this.ticket.tours)
    this.dataSource = [...this.ticket.tours]
      .filter(({ check }) => check === 0)
      .sort(
        ({ startDate: aTourDate }, { startDate: bTourDate }) =>
          new Date(aTourDate).getTime() - new Date(bTourDate).getTime()
      );
  }

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.length;
    return numSelected == numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  toggleAllRows() {
    this.isAllSelected()
      ? this.selection.clear()
      : this.dataSource.forEach((row) => this.selection.select(row));
  }

  getTourStateTooltip(tour: Tour): string {
    if (tour.check > 1) {
      return 'Abgerechnet';
    }
    if (tour.check === 1) {
      return 'Für Abrechnung vorbereitet';
    }
    if (tour.empty) {
      return 'Gefahren';
    }
    return '';
  }
}
