import { SeasonPickerComponent } from '@/shared/components/seasonPicker/season-picker.component';
import { formatGregorian, gregorianToJalali, parseJalali } from '@/utils';
import { Component, computed, inject, signal } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { ButtonDirective } from 'primeng/button';
import { Skeleton } from 'primeng/skeleton';
import { posSaleInvoicesNamedRoutes } from '../../saleInvoices/constants';
import { IPosSaleInvoicesFilterDto } from '../../saleInvoices/models';
import { PosShopNamedRoutes } from '../../shop/constants/routes';
import { PosStatisticsInvoiceTypeCardComponent } from '../components';
import { PosStatisticsStore } from '../store/main.store';

@Component({
  selector: 'pos-statistics-root',
  templateUrl: './root.component.html',
  imports: [
    PosStatisticsInvoiceTypeCardComponent,
    Skeleton,
    SeasonPickerComponent,
    ButtonDirective,
    RouterLink,
  ],
})
export class PosStatisticsRootComponent {
  private readonly store = inject(PosStatisticsStore);
  private readonly router = inject(Router);

  readonly item = computed(() => this.store.entity());
  readonly loading = computed(() => this.store.loading());
  readonly shopRoute = PosShopNamedRoutes.shop.meta.pagePath!();

  selectedDate = signal(new Date());

  ngOnInit() {
    this.getData(this.selectedDate());
  }

  onDateChanged(date: Date) {
    this.selectedDate.set(date);
    this.getData(date);
  }

  getData(date?: Date) {
    this.store.getData(date);
  }

  toInvoicesPage(type: string) {
    const mainRoute = posSaleInvoicesNamedRoutes.saleInvoices.meta.pagePath!();
    const queryParams: IPosSaleInvoicesFilterDto = {
      invoice_date_from: this.selectedDate().toISOString(),
      invoice_date_to: new Date(
        formatGregorian(
          parseJalali(gregorianToJalali(this.selectedDate())).add(3, 'months').set('day', 1)
        )
      ).toISOString(),
    };

    switch (type) {
      case 'success':
        queryParams.status = 'SUCCESS';
        break;
      case 'failure':
        queryParams.status = 'FAILURE';
        break;
      case 'notSended':
        queryParams.status = 'NOT_SEND';
        break;
      case 'pending':
        queryParams.status = 'QUEUED';
        break;
    }
    const queryString = new URLSearchParams(queryParams as Record<string, string>).toString();

    this.router.navigateByUrl(`${mainRoute}?${queryString}`);
  }
}
