import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { of } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { API } from 'src/app/core/services/api.service';
@Component({
  selector: 'app-activity-add-on-search',
  templateUrl: './activity-add-on-search.component.html',
})
export class ActivityAddOnSearchComponent {
  Result;
  cols: any[];
  searchForm: FormGroup;

  constructor(
    public fb: FormBuilder,
    private apiserv: API,
    public commonMasterSer: CommonFunctionService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.cols = [
      { field: 'addOn', header: 'Add-On' },
      { field: 'description', header: 'Description' },
      { field: 'applyRateOn', header: 'Rate Type' },
      { field: 'currency', header: 'Currency' },
      { field: 'activityAddonId', header: 'Add-On Id' },
      { field: 'activityAddonVendor', header: 'Vendor' },
      { field: 'status', header: 'Status' },
      { field: 'updatedBy', header: 'Updated By' },
      { field: 'Custom_updated_on', header: 'Updated On' },
    ];

    this.initForm();
  }

  initForm() {
    this.searchForm = this.fb.group({
      addOn: ''
    });
  }

  Search() {
    const formVal = this.searchForm.getRawValue();
    const reqObj = {
      addOn: formVal.addOn ? formVal.addOn.trim() : ''
    };

    this.apiserv.Post('/ActivityAddon/GetAll', reqObj).subscribe(res => {
      if (res && res.status) {
        this.Result = res.data ? res.data : [];
        if (this.Result.length > 0) {
          this.Result.forEach(item => {
            item['status'] = item.isActive ? 'Active' : 'Deactive';
            item['Custom_updated_on'] = this.commonMasterSer.convertDateWithTimeToShow(item.updatedOn);
          });
        }
      } else {
        this.Result = [];
        // this.commonMasterSer.showMessage(false, res?.message || 'Failed to load data');
      }
    });
  }

  Reset() {
    this.searchForm.reset();
    this.Result = [];
  }

  Edit(id: string) {
    this.router.navigateByUrl(`/ActivityConfiguration/ActivityAddOn/Edit/${id}`);
  }

  ManageLang(id: string) {
    this.router.navigateByUrl(`/ActivityConfiguration/ActivityAddOn/Language/${id}`);
  }

  updateStatus(id: string, currentStatus: boolean) {
    const obj = {
      id: id,
      status: !currentStatus
    };

    this.apiserv.Post('/ActivityAddon/UpdateStatus', obj).subscribe(res => {
      if (res && res.status) {
        this.commonMasterSer.showMessage(true, res.message || 'Status updated successfully');
        this.Search(); // Refresh list
      } else {
        this.commonMasterSer.showMessage(false, res?.message || 'Failed to update status');
      }
    });
  }
}
