import { POS_ROUTES } from '@/domains/pos/routes';
import { InnerPagesHeaderComponent } from '@/shared/components/innerPagesHeader/inner-pages-header.component';
import { Component, computed, inject, signal } from '@angular/core';
import { 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);

  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;
        const formattedValue =
          typedKey === 'status' && value === 'NOT_SEND'
            ? 'ارسال نشده'
            : typedKey === 'status' && value === 'SUCCESS'
              ? 'موفق'
              : typedKey === 'status' && value === 'FAILURE'
                ? 'ناموفق'
                : typedKey === 'status' && value === 'QUEUED'
                  ? 'در انتظار ارسال'
                  : String(value);
        return { key: typedKey, label: labels[typedKey] ?? typedKey, value: formattedValue };
      });
  });
  activeFilterCount = computed(() => this.activeFilters().length);
  backRoute = POS_ROUTES.path || '/';

  ngOnInit() {
    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.getData();
  }

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

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