import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { of } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-activity-add-on-add',
  templateUrl: './activity-add-on-add.component.html',
})
export class ActivityAddOnAddComponent {
Edit_Id: string;
  AddOnForm: FormGroup;
  AllLang: any[] = [];
  currencyList: any[] = [];
  applyRateOnList = [
    { key: 'Per Person', value: 'PERPERSON' },
    { key: 'Per Service', value: 'PERSERVICE' },
  ];
  vendorList: any[] = [];
  fileInfo = [];
  fileArr = [];
  editResp: any;

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

  ngOnInit(): void {
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.initForm();
    this.getAllLanguages();
    this.getCurrencyList();
    this.getVendorList();
    if (this.Edit_Id) {
      this.getById();
    }
  }

  getAllLanguages() {
    this.apiserv.AdminGet('/LanguageMapping/GetLanguagesByOrgId').subscribe(data => {
      if (data) {
        this.AllLang = data;
      }
    });
  }

  getCurrencyList() {
    // Replace with actual API if needed
      this.apiserv.AdminGet('/CurrencyMaster/GetAllCurrencies').subscribe(d => {
      if (d) this.currencyList = d;
    });
  }

  getVendorList() {
    this.apiserv.Get('/ActivityVehicle/GetVehicleVendor').subscribe(res => {
      if (res && res.status) {
        this.vendorList = res.data;
      }
    });
  }

  initForm() {
    this.AddOnForm = this.fb.group({
      addOn: this.validServ.required,
      defaultLanguageCode: this.validServ.required,
      description: '',
      addonImage: '',
      addonImageUrl: '',
      applyRateOn: this.validServ.required,
      currency: this.validServ.required,
      activityAddonVendorId: ''
    });
  }

  SelectImage(event: any, fileUpload: any, controlName: string) {
    const file = event.currentFiles[0];
    if (file && file.size < 1048576 && ['image/jpeg', 'image/png'].includes(file.type)) {
      const reader = new FileReader();
      reader.readAsText(file); // Check for script tags
      reader.onload = (e) => {
        const binaryString = e.target?.result as string;
        const hasScript = this.commonMasterSer.hasScriptTagInBinary(binaryString);
        if (hasScript) {
          fileUpload.clear();
          this.commonMasterSer.showMessage(false, 'Invalid file (contains script tag)');
          return;
        }

        // Set file and preview URL
        this.AddOnForm.get(controlName).setValue(file);
        const urlReader = new FileReader();
        urlReader.readAsDataURL(file);
        urlReader.onload = () => {
          this.AddOnForm.get('addonImageUrl').setValue(urlReader.result?.toString());
        };
      };
    } else {
      this.commonMasterSer.showMessage(false, 'File must be JPG/PNG under 1MB');
      fileUpload.clear();
    }
  }

  RemoveImage() {
    this.AddOnForm.get('addonImage').setValue('');
    this.AddOnForm.get('addonImageUrl').setValue('');
  }

  getById() {
    this.apiserv.Get(`/ActivityAddon/GetById/${this.Edit_Id}`).subscribe(res => {
      if (res && res.status) {
        this.editResp = res.data;
        this.HandleApplyRateOn(this.editResp.applyRateOn)
        this.AddOnForm.get('addOn').setValue(this.editResp.activityAddonDetails.addOn);
        this.AddOnForm.get('defaultLanguageCode').setValue(this.editResp.defaultLanguageCode);
        this.AddOnForm.get('description').setValue(this.editResp.activityAddonDetails.description);
        this.AddOnForm.get('applyRateOn').setValue(this.editResp.applyRateOn);
        this.AddOnForm.get('currency').setValue(this.editResp.currency);
        this.AddOnForm.get('adult')?.setValue(this.editResp.adult);
        this.AddOnForm.get('child')?.setValue(this.editResp.child);
        this.AddOnForm.get('youth')?.setValue(this.editResp.youth);
        this.AddOnForm.get('senior')?.setValue(this.editResp.senior);
        this.AddOnForm.get('amount')?.setValue(this.editResp.amount);
        this.AddOnForm.get('activityAddonVendorId').setValue(this.editResp.activityAddonVendorId || '');

        if (this.editResp.addonImage) {
          this.AddOnForm.get('addonImage').setValue(this.editResp.addonImage);
          this.AddOnForm.get('addonImageUrl').setValue(this.editResp.addonImage);
        }
      }
    });
  }

  SaveUpdateAddOn() {
    if (this.AddOnForm.invalid) {
      this.validServ.showValidationsMsg(this.AddOnForm);
      setTimeout(() => this.validServ.scrollToError(), 50);
      return;
    }

    const formVal = this.AddOnForm.getRawValue();
    const postData = {
      activityAddonId: this.Edit_Id ?? '',
      defaultLanguageCode: formVal.defaultLanguageCode,
      applyRateOn: formVal.applyRateOn,
      currency: formVal.currency,
      adult: formVal.adult,
      child: formVal.child,
      youth: formVal.youth,
      senior: formVal.senior,
      amount: formVal.amount,
      activityAddonVendorId: formVal.activityAddonVendorId,
      activityAddonDetails: {
        addOn: formVal.addOn,
        description: formVal.description,
        languageCode: formVal.defaultLanguageCode,
        activityAddonId: this.Edit_Id ?? '',
        activityAddonDetailId: this.editResp?.activityAddonDetails?.activityAddonDetailId || ''
      }
    };

    let addonImageUrl = '';
    if (formVal.addonImage && typeof formVal.addonImage === 'object') {
      const ext = formVal.addonImage.name.split('.').pop();
      this.fileArr.push(formVal.addonImage);
      this.fileInfo.push({
        fileName: `Extranet/Activity/AddOn/ActivityAddonId/addonImage.${ext}`,
        pathToSave: 'OrganizationData/ORGID'
      });
      addonImageUrl = `${environment.cdnFileUrl}OrganizationData/ORGID/Extranet/Activity/AddOn/ActivityAddonId/addonImage.${ext}?t=${moment().format('yyMMddHHmmssfffffff')}`;
    } else {
      addonImageUrl = formVal.addonImage;
    }

    postData['addonImage'] = addonImageUrl;

    const url = this.Edit_Id ? 'Update' : 'Save';
    this.apiserv.Post(`/ActivityAddon/${url}`, postData).subscribe(resp => {
      if (resp?.status) {
        if (this.fileInfo.length > 0) {
          this.saveImg(this.fileInfo, this.fileArr, resp.data).subscribe(uploadRes => {
            if (uploadRes?.resp) {
              this.BackButton();
            }
            this.commonMasterSer.showMessage(uploadRes.resp, uploadRes.respMsg || 'Saved successfully');
          });
        } else {
          this.BackButton();
        }
        this.commonMasterSer.showMessage(true, resp.message);
      } else {
        this.commonMasterSer.showMessage(false, resp?.message || 'Save failed');
      }
    });
  }

  saveImg(fileInfo: any[], fileArr: File[], edit_id: string) {
    if (!fileInfo.length || !fileArr.length) {
      return of({ resp: true, respMsg: 'No files to upload' });
    }

    const formData = new FormData();
    fileArr.forEach(file => formData.append('files', file));
    const processedFileInfo = JSON.stringify(fileInfo).replace(/ActivityAddonId/g, edit_id);
    formData.append('fileInfo', processedFileInfo);

    return this.apiserv.PostFile('/FileUpload/SaveFile', formData);
  }

  BackButton() {
    this.router.navigateByUrl('ActivityConfiguration/ActivityAddOn/Search');
  }

  HandleApplyRateOn(value){
    if(value === "PERPERSON"){
      this.AddOnForm.addControl('adult', this.fb.control('', Validators.required));
      this.AddOnForm.addControl('child', this.fb.control('', Validators.required));
      this.AddOnForm.addControl('youth', this.fb.control('', Validators.required));
      this.AddOnForm.addControl('senior', this.fb.control('', Validators.required));
      this.AddOnForm.removeControl('amount');
    }else if(value === "PERSERVICE"){
      this.AddOnForm.addControl('amount', this.fb.control('', Validators.required));
      this.AddOnForm.removeControl('child');
      this.AddOnForm.removeControl('youth');
      this.AddOnForm.removeControl('adult');
      this.AddOnForm.removeControl('senior');
    }else {
      this.AddOnForm.removeControl('child');
      this.AddOnForm.removeControl('youth');
      this.AddOnForm.removeControl('adult');
      this.AddOnForm.removeControl('amount');
      this.AddOnForm.removeControl('senior');
    }
  }
}
