import { POS_ROUTES } from '@/domains/pos/routes';
import { InnerPagesHeaderComponent } from '@/shared/components/innerPagesHeader/inner-pages-header.component';
import { gregorianToJalali } from '@/utils';
import { Component, computed, inject, signal } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Button, ButtonDirective } from 'primeng/button';
import { Chip } from 'primeng/chip';
import { Skeleton } from 'primeng/skeleton';
import { finalize } from 'rxjs';
import { posSaleInvoicesNamedRoutes } from '../constants/routes';
import {
  IPosSaleInvoicesFilterDto,
  IPosSaleInvoicesResponse,
  IPosSaleInvoicesSummaryResponse,
} from '../models';
import { PosSaleInvoicesService } from '../services/main.service';
import { PosSaleInvoicesFilterDrawerComponent } from './filter-drawer.component';
import { SaleInvoiceCardComponent } from './sale-invoice-card.component';

@Component({
  selector: 'pos-saleInvoice-list',
  templateUrl: './list.component.html',
  imports: [
    InnerPagesHeaderComponent,
    ButtonDirective,
    Skeleton,
    PosSaleInvoicesFilterDrawerComponent,
    Button,
    Chip,
    SaleInvoiceCardComponent,
  ],
})
export class PosSaleInvoiceListComponent {
  private readonly service = inject(PosSaleInvoicesService);
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);

  loading = signal(true);
  items = signal<IPosSaleInvoicesSummaryResponse[]>([]);
  filterVisible = signal(false);
  filters = signal<IPosSaleInvoicesFilterDto>({});
  activeFilters = computed(() => {
    const labels: Partial<Record<keyof IPosSaleInvoicesFilterDto, string>> = {
      invoice_date_from: 'از تاریخ فاکتور',
      invoice_date_to: 'تا تاریخ فاکتور',
      created_at_from: 'از تاریخ ایجاد',
      created_at_to: 'تا تاریخ ایجاد',
      code: 'کد',
      customer_name: 'نام مشتری',
      customer_mobile: 'موبایل',
      customer_national_id: 'کد ملی',
      customer_economic_code: 'شناسه اقتصادی',
      status: 'وضعیت',
      total_amount_from: 'از مبلغ',
      total_amount_to: 'تا مبلغ',
    };

    return Object.entries(this.filters())
      .filter(([, value]) => value !== undefined && value !== null && value !== '')
      .map(([key, value]) => {
        const typedKey = key as keyof IPosSaleInvoicesFilterDto;
        let formattedValue = '';
        if (typedKey === 'status') {
          formattedValue =
            value === 'NOT_SEND'
              ? 'ارسال نشده'
              : value === 'SUCCESS'
                ? 'موفق'
                : value === 'FAILURE'
                  ? 'ناموفق'
                  : value === 'QUEUED'
                    ? 'در انتظار ارسال'
                    : String(value);
        } else if (
          key === 'invoice_date_from' ||
          key === 'invoice_date_to' ||
          key === 'created_at_from' ||
          key === 'created_at_to'
        ) {
          formattedValue = gregorianToJalali(value);
        } else {
          formattedValue = String(value);
        }
        return { key: typedKey, label: labels[typedKey] ?? typedKey, value: formattedValue };
      });
  });
  activeFilterCount = computed(() => this.activeFilters().length);
  backRoute = POS_ROUTES.path || '/';

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

  getData() {
    this.loading.set(true);
    this.service
      .getAll(this.filters())
      .pipe(finalize(() => this.loading.set(false)))
      .subscribe((res) => {
        this.items.set(res.data ?? []);
      });
  }

  refresh() {
    this.getData();
  }
  toggleFilterVisible() {
    this.filterVisible.update((v) => !v);
  }

  onFilterApply(query: IPosSaleInvoicesFilterDto) {
    this.filters.set(query);
    this.syncFiltersToQueryParams();
    this.getData();
  }

  removeFilter(key: keyof IPosSaleInvoicesFilterDto) {
    const next = { ...this.filters() };
    delete next[key];
    this.filters.set(next);
    this.syncFiltersToQueryParams();
    this.getData();
  }

  toSinglePage(item: IPosSaleInvoicesResponse) {
    this.router.navigateByUrl(posSaleInvoicesNamedRoutes.saleInvoice.meta.pagePath!(item.id));
  }

  private hydrateFiltersFromQueryParams() {
    const queryParams = this.route.snapshot.queryParams;
    const keys: (keyof IPosSaleInvoicesFilterDto)[] = [
      'invoice_date_from',
      'invoice_date_to',
      'created_at_from',
      'created_at_to',
      'code',
      'customer_name',
      'customer_mobile',
      'customer_national_id',
      'customer_economic_code',
      'status',
      'total_amount_from',
      'total_amount_to',
    ];

    const parsed = keys.reduce<IPosSaleInvoicesFilterDto>((acc, key) => {
      const value = queryParams[key];
      if (value !== undefined && value !== null && value !== '') {
        acc[key] = value;
      }
      return acc;
    }, {});

    this.filters.set(parsed);
  }

  private syncFiltersToQueryParams() {
    const queryParams = Object.entries(this.filters()).reduce<Record<string, string>>(
      (acc, [key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          acc[key] = String(value);
        }
        return acc;
      },
      {}
    );

    this.router.navigate([], {
      relativeTo: this.route,
      queryParams,
      replaceUrl: true,
    });
  }
}
