import { Component, EventEmitter, inject, input, Output, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { AutoCompleteModule } from 'primeng/autocomplete';
import { HttpClient } from '@angular/common/http';
import { PosCartService } from '../../services/pos-cart.service';
import { environment } from '../../../../../environments/environment';

@Component({
  selector: 'app-cart-panel',
  standalone: true,
  imports: [CommonModule, FormsModule, TranslateModule, AutoCompleteModule],
  templateUrl: './cart-panel.component.html',
  styleUrl: './cart-panel.component.scss',
})
export class CartPanelComponent implements OnInit {
  readonly cartService = inject(PosCartService);
  private http = inject(HttpClient);
  private translate = inject(TranslateService);

  retailMode = input(false);
  currencySymbol = input('');

  @Output() paymentRequested = new EventEmitter<void>();
  @Output() holdOrder = new EventEmitter<void>();
  @Output() showHeldOrders = new EventEmitter<void>();
  @Output() showCoupon = new EventEmitter<void>();
  @Output() closeSession = new EventEmitter<void>();
  @Output() showReturn = new EventEmitter<void>();

  readonly WALK_IN_ID = 5;
  customerSuggestions = signal<any[]>([]);
  selectedCustomer = signal<any>(null);

  ngOnInit(): void {
    // Default to walk-in customer
    this.cartService.setCustomer(this.WALK_IN_ID, this.translate.instant('POS.WALK_IN'));
    this.selectedCustomer.set({
      id: this.WALK_IN_ID,
      name: this.translate.instant('POS.WALK_IN'),
    });
  }

  searchCustomers(event: any): void {
    const query = event.query?.trim();
    if (!query || query.length < 2) {
      this.customerSuggestions.set([]);
      return;
    }
    this.http
      .get<any>(`${environment.apiUrl}/core/partners`, {
        params: { search: query, partner_type: 'customer' },
      })
      .subscribe({
        next: (res) => {
          this.customerSuggestions.set(res.data || []);
        },
      });
  }

  onCustomerChange(value: any): void {
    if (value && typeof value === 'object' && value.id) {
      this.selectedCustomer.set(value);
      this.cartService.setCustomer(value.id, value.name);
    }
  }

  resetToWalkIn(): void {
    this.cartService.setCustomer(this.WALK_IN_ID, this.translate.instant('POS.WALK_IN'));
    this.selectedCustomer.set({
      id: this.WALK_IN_ID,
      name: this.translate.instant('POS.WALK_IN'),
    });
  }

  onIncrement(index: number): void {
    const item = this.cartService.items()[index];
    if (item) {
      this.cartService.updateQuantity(index, item.qty + 1);
    }
  }

  onDecrement(index: number): void {
    const item = this.cartService.items()[index];
    if (item) {
      this.cartService.updateQuantity(index, item.qty - 1);
    }
  }
}
