import { CurrencyPipe } from '@angular/common';
import { Component, computed, effect, OnInit, signal } from '@angular/core';
import { MatDividerModule } from '@angular/material/divider';
import { tap } from 'rxjs';
import { InfoCardModule } from '../../core/components/info-card/info-card.component';
import {
  HomeDashboardGQL,
  HomeDashboardQuery,
  TicketValidationState,
} from '../../core/data-access/graphql/generated/generated';
import { ManagerInfoCardComponent } from '../manager/components/manager-info-card/manager-info-card.component';
import { TicketStateInfoCardComponent } from '../ticket-system/ticket-state-info-card/ticket-state-info-card.component';
import { LinkCardComponent } from './link-card/link-card.component';
import { SkeletonDirective } from '../../core/components/skeleton-rect/skeleton.directive';

@Component({
  selector: 'app-home',
  imports: [
    ManagerInfoCardComponent,
    TicketStateInfoCardComponent,
    InfoCardModule,
    LinkCardComponent,
    MatDividerModule,
    CurrencyPipe,
    SkeletonDirective,
  ],
  template: `
    <div class="flex flex-col m-0 md:m-4">
      @if (kpis() !== undefined) {
      <div
        class="mb-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-9 gap-2 lg:gap-4"
      >
        <div class="col-span-9 text-lg">Übersicht</div>
        <app-link-card [target]="'/control-center'" class="col-span-3">
          <div class="flex justify-between">
            <div
              class="p-2 basis-1/2 flex flex-col justify-center items-center"
            >
              <div class="text-xl" style="color: var(--mat-sys-primary)">
                {{ kpis()?.anomalyCount }}
              </div>
              <div class="text-sm text-center">Aktuelle<br />Anomalien</div>
            </div>
            <div
              class="p-2 basis-1/2 flex flex-col justify-center items-center"
            >
              <div class="text-xl" style="color: var(--mat-sys-primary)">
                {{ kpis()?.employeesWithoutTourCount }}
              </div>
              <div class="text-sm text-center">Mitarbeiter ohne Tour</div>
            </div>
          </div>
        </app-link-card>
        <app-link-card
          [target]="'/managers/dayview'"
          class="row-span-1 col-span-3"
        >
          <div class="h-full flex flex-col justify-between">
            <div class="flex justify-between">
              @for (revenueItem of revenueByOrdinanceType(); track $index) {
              <div
                class="p-2 basis-1/2 flex flex-col justify-center items-center"
              >
                <div class="text-lg" style="color: var(--mat-sys-primary)">
                  {{
                    revenueItem.value
                      | currency : 'EUR' : 'symbol-narrow' : '.2' : 'de'
                  }}
                </div>
                <div class="text-sm">{{ revenueItem.label }}</div>
              </div>
              }
            </div>
            <!-- <div class="flex flex-col">
              <div class="text-small pb-2">Umsatzverlauf 10 Tage</div>
              <app-trend-graph [data]="kpis()?.revenueTrend"></app-trend-graph>
            </div> -->
          </div>
        </app-link-card>
        <app-link-card [target]="'/accounting'" class="col-span-3 row-span-2">
          <div class="h-full flex justify-around">
            <div class="flex flex-col h-full justify-around items-center">
              <div>Abrechenbar</div>
              <div
                class="p-2 basis-1/2 flex flex-col justify-center items-center"
              >
                <div class="text-xl" style="color: var(--mat-sys-primary)">
                  {{ kpis()?.billableTourCount }}
                </div>
                <div class="text-sm text-center">Touren</div>
              </div>
              <div
                class="p-2 basis-1/2 flex flex-col justify-center items-center"
              >
                <div class="text-xl" style="color: var(--mat-sys-primary)">
                  {{
                    kpis()?.billableTourRevenueSum
                      | currency : 'EUR' : 'symbol-narrow' : '.2' : 'de'
                  }}
                </div>
                <div class="text-sm text-center">Umsatz</div>
              </div>
            </div>
            <div class="flex flex-col h-full justify-around items-center">
              <div>Falsch abgerechnet</div>
              <div
                class="p-2 basis-1/2 flex flex-col justify-center items-center"
              >
                <div class="text-xl" style="color: var(--mat-sys-primary)">
                  {{ kpis()?.billedTourCount }}
                </div>
                <div class="text-sm text-center">Touren</div>
              </div>
              <div
                class="p-2 basis-1/2 flex flex-col justify-center items-center"
              >
                <div class="text-xl text-green-700">
                  +{{
                    kpis()?.billedTourPositiveRevenueDeviation
                      | currency : 'EUR' : 'symbol-narrow' : '.2' : 'de'
                  }}
                </div>
                <div class="text-xl" style="color: var(--mat-sys-error)">
                  {{
                    kpis()?.billedTourNegativeRevenueDeviation
                      | currency : 'EUR' : 'symbol-narrow' : '.2' : 'de'
                  }}
                </div>
                <div class="text-sm text-center">Umsatz</div>
              </div>
            </div>
          </div>
        </app-link-card>
        <app-link-card [target]="'/tickets'" class="col-span-3">
          <div class="w-full h-full flex flex-col justify-center items-center">
            <div class="text-large text-center">
              <span class="font-bold" style="color: var(--mat-sys-error);">{{
                kpis()?.employeesWithoutTourCount
              }}</span>
              Touren starten in 3 Tagen ohne Genehmigung
            </div>
          </div>
        </app-link-card>
      </div>

      }
      <div
        class="my-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 lg:gap-4"
      >
        <div class="col-span-4 text-lg">Manager System - Tagespotenzial</div>
        <app-manager-info-card ordinanceType="BTW"></app-manager-info-card>
        <app-manager-info-card ordinanceType="TSW"></app-manager-info-card>
        <app-manager-info-card ordinanceType="KTW"></app-manager-info-card>
        <!-- <app-manager-info-card ordinanceType="ALL"></app-manager-info-card> -->
      </div>
      <div
        class="my-4 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2 lg:gap-4"
      >
        <div class="col-span-4 text-lg">Ticket System - Bearbeitungsstatus</div>
        <app-ticket-state-info-card
          [ticketState]="TicketState.Created"
        ></app-ticket-state-info-card>
        <app-ticket-state-info-card
          [ticketState]="TicketState.UserInteractionRequired"
        ></app-ticket-state-info-card>
        <app-ticket-state-info-card
          [ticketState]="TicketState.TdUncertain"
        ></app-ticket-state-info-card>
        <app-ticket-state-info-card
          [ticketState]="TicketState.DocumentsMissing"
        ></app-ticket-state-info-card>
      </div>
    </div>
  `,
  styles: ``,
})
export class HomeComponent implements OnInit {
  TicketState = TicketValidationState;

  kpis = signal<HomeDashboardQuery['homeDashboardKpis'] | undefined>(undefined);

  public readonly revenueByOrdinanceType = computed(() => {
    const currentData = this.kpis()?.revenueTrend;
    if (!currentData) return;

    const groupedByOrdinanceType = [...currentData]
      .sort(
        ({ date: aDate }, { date: bDate }) =>
          new Date(aDate).getTime() - new Date(bDate).getTime()
      )
      .reduce((sum, { ordinanceType, revenueSum }) => {
        return {
          ...sum,
          [ordinanceType]: [
            ...(sum[ordinanceType] ? sum[ordinanceType] : []),
            revenueSum,
          ],
        };
      }, {} as Record<string, number[]>);

    return Object.entries(groupedByOrdinanceType)
      .sort(([ot1], [ot2]) => ot1.localeCompare(ot2))
      .map(([ot, revenues]) => {
        return {
          label: ot,
          value: revenues.at(-1), //.reduce((sum, cur) => (sum += cur), 0),
        };
      });
  });

  constructor(private readonly homeDashboardGql: HomeDashboardGQL) {
    effect(() => {
      this.homeDashboardGql
        .fetch()
        .pipe(tap((res) => this.kpis.set(res.data.homeDashboardKpis)))
        .subscribe();
    });
  }

  ngOnInit() {}
}
