import { Maybe } from '@/core';
import { PageLoadingComponent } from '@/shared/components/page-loading.component';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, EventEmitter, inject, Output, signal } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { ButtonDirective } from 'primeng/button';
import { Card } from 'primeng/card';
import { Message } from 'primeng/message';
import { catchError, finalize } from 'rxjs';
import { COOKIE_KEYS } from 'src/assets/constants';
import { IPosAccessibleResponse } from '../../models/pos.io';
import { PosService } from '../../modules/landing/services/main.service';

@Component({
  selector: 'pos-choose-cards',
  templateUrl: './choose-pos.component.html',
  imports: [PageLoadingComponent, Card, ButtonDirective, Message],
})
export class PosChooseCardsComponent {
  @Output() onChoose = new EventEmitter();

  private readonly service = inject(PosService);
  private readonly cookieService = inject(CookieService);

  loading = signal(true);
  items = signal<IPosAccessibleResponse[]>([]);
  error = signal<Maybe<HttpErrorResponse>>(null);

  getData() {
    this.loading.set(true);
    this.service
      .getAccessible()
      .pipe(
        finalize(() => this.loading.set(false)),
        catchError((err) => {
          this.error.set(err);
          throw err;
        }),
      )
      .subscribe((res) => {
        this.items.set(res?.data || []);
      });
  }

  ngOnInit() {
    this.getData();
  }

  selectPos(pos: IPosAccessibleResponse) {
    this.cookieService.set(COOKIE_KEYS.POS_ID, pos.id, {
      sameSite: 'Lax', // or 'Strict' for same-site requests only
      secure: false,
      path: '/',
      domain: 'localhost',
    });

    this.onChoose.emit();
  }
}
