import { BreadcrumbService } from '@/core/services';
import { AppCardComponent, KeyValueComponent } from '@/shared/components';
import pageParamsUtils from '@/utils/page-params.utils';
import { Component, computed, effect, inject, signal } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Button } from 'primeng/button';
import { COOKIE_KEYS } from 'src/assets/constants';
import { ConsumerPosFormComponent } from '../../components/poses/form.component';
import { ConsumerSalesInvoicesComponent } from '../../components/salesInvoices/list.component';
import { BusinessActivityStore } from '../../store/businessActivity.store';
import { ConsumerComplexStore } from '../../store/complex.store';
import { PosStore } from '../../store/pos.store';

@Component({
  selector: 'consumer--complex-pos-page',
  templateUrl: './single.component.html',
  imports: [
    AppCardComponent,
    KeyValueComponent,
    ConsumerPosFormComponent,
    Button,
    ConsumerSalesInvoicesComponent,
  ],
})
export class ConsumerComplexPosPageComponent {
  private readonly businessStore = inject(BusinessActivityStore);
  private readonly complexStore = inject(ConsumerComplexStore);
  private readonly store = inject(PosStore);
  private readonly route = inject(ActivatedRoute);
  private readonly breadcrumbService = inject(BreadcrumbService);
  private readonly cookieService = inject(CookieService);

  pageParams = computed(() => pageParamsUtils(this.route));

  readonly businessId = signal<string>(this.pageParams()['businessActivityId']!);
  readonly complexId = signal<string>(this.pageParams()['complexId']!);
  readonly posId = signal<string>(this.pageParams()['posId']!);
  editMode = signal<boolean>(false);

  constructor() {
    effect(() => {
      if (this.pos()?.id) {
        this.setBreadcrumb();
      }
    });
  }

  readonly loading = computed(() => this.store.loading());
  readonly pos = computed(() => this.store.entity());

  getData() {
    this.store.getData(this.businessId(), this.complexId(), this.posId());
  }

  toPosLanding() {
    this.cookieService.set(COOKIE_KEYS.POS_ID, '', new Date());
    this.cookieService.set(COOKIE_KEYS.POS_ID, this.posId(), {
      sameSite: 'Lax', // or 'Strict' for same-site requests only
      secure: false,
      path: '/',
      domain: 'localhost',
    });
    window.open('/pos', '_blank');
  }

  setBreadcrumb() {
    this.breadcrumbService.setItems([
      ...this.businessStore.breadcrumbItems(),
      ...this.complexStore.breadcrumbItems(),
      ...this.store.breadcrumbItems(),
    ]);
  }
}
