import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild, HostListener } from '@angular/core';
import { SelectableSettings } from '@progress/kendo-angular-grid';
import { Subscription } from 'rxjs';
import { Customer } from 'src/app/models/customer.model';
import { CustomerService } from 'src/app/services/customer.service';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { Store } from '@ngrx/store';
import { CustomerSaleState } from '../../store/reducers/customer-sale.reducer';
import { SelectCustomerAction } from '../../store/actions/customer-sale.action';

@Component({
  selector: 'app-select-customer',
  templateUrl: './select-customer.component.html',
  styleUrls: ['./select-customer.component.scss']
})
export class SelectCustomerComponent implements OnInit, OnDestroy {

  constructor(
    private customerService: CustomerService,
    private store: Store<CustomerSaleState>
  ) { }

  customers: Customer[] = [];
  customerSubscription: Subscription;
  public selectableSettigns: SelectableSettings = {
    checkboxOnly: false
  };
  @ViewChild('searchText') searchText: TextBoxComponent;
  @Input() openedDialog = false;
  @Output() resultEvent = new EventEmitter<Customer>();
  customer: Customer;
  loading = false;
  isMobile = false;

  ngOnInit(): void {
    this.detectScreenSize();
  }

  ngOnDestroy(): void {
    if (this.customerSubscription) {
      this.customerSubscription.unsubscribe();
    }
  }

  @HostListener('window:resize', [])
  detectScreenSize(): void {
    this.isMobile = window.innerWidth <= 768;
  }

  async searchCustomer(name: string): Promise<void> {
    if (!name || name.trim() === '') {
      console.warn('O campo de pesquisa está vazio.');
      return;
    }

    try {
      this.loading = true;
      this.customerSubscription = this.customerService.getCustomer(name.toUpperCase().trim())
        .subscribe((res: Customer[]) => {
          this.customers = res;
          this.customer = this.customers[0] || null;
          this.loading = false;
        });
    } catch (e) {
      console.error('Erro ao buscar clientes:', e);
      this.loading = false;
    }
  }

  keyDownFunction(event: KeyboardEvent): void {
    if (event.key === 'Enter') {
      this.searchCustomer(this.searchText.value);
    }
  }

  selectionCustomer(event): void {
    const selCustomer = event.selectedRows[0].dataItem as Customer;
    this.store.dispatch(new SelectCustomerAction(selCustomer));
    this.customer = selCustomer;
    this.openedDialog = false;
    this.resultEvent.emit(this.customer);
    localStorage.removeItem('preCustomer');
  }

  onIconClick(searchValue: string): void {
    if (!searchValue || searchValue.trim() === '') {
      console.warn('O campo de pesquisa está vazio.');
      return;
    }
  
    this.searchCustomer(searchValue.trim());
  }

  close(): void {
    this.openedDialog = false;
    this.resultEvent.emit(null);
  }
}
