import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { forkJoin, 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';
@Component({
  selector: 'app-activity-add-on-language',
  templateUrl: './activity-add-on-language.component.html',
})
export class ActivityAddOnLanguageComponent {
Edit_Id: string;
  AddOnLangForm: FormGroup;
  AllLang: any[] = [];
  editResp: any;

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

  ngOnInit(): void {
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.initForm();
    this.loadInitialData();
  }

  initForm() {
    this.AddOnLangForm = this.fb.group({
      defaultLanguageCode: [''],
      languageCode: this.validServ.required,
      defaultAddOn: [''],
      defaultDescription: [''],
      addOn: this.validServ.required,
      description: [''],
      activityAddonDetailId: ['']
    });
  }

  loadInitialData() {
    forkJoin({
      languages: this.apiserv.AdminGet('/LanguageMapping/GetLanguagesByOrgId'),
      addonData: this.Edit_Id ? this.apiserv.Get(`/ActivityAddon/GetById/${this.Edit_Id}`) : of(null)
    }).subscribe(res => {
      if (res.languages) {
        this.AllLang = [...res.languages];
      }

      if (res.addonData?.status) {
        this.editResp = res.addonData.data;
        const defaultLangCode = this.editResp.defaultLanguageCode;

        // Set default language name
        const defaultLang = this.AllLang.find(lang => lang.LanguageCode === defaultLangCode);
        this.AddOnLangForm.get('defaultLanguageCode').setValue(defaultLang?.LanguageName || defaultLangCode);

        // Set default content
        this.AddOnLangForm.get('defaultAddOn').setValue(this.editResp.activityAddonDetails.addOn);
        this.AddOnLangForm.get('defaultDescription').setValue(this.editResp.activityAddonDetails.description);

        // Remove default language from dropdown
        this.AllLang = this.AllLang.filter(lang => lang.LanguageCode !== defaultLangCode);
      }
    });
  }

  getDataByLang() {
    const langCode = this.AddOnLangForm.get('languageCode').value;
    if (!langCode || !this.Edit_Id) return;

    this.apiserv.Get(`/ActivityAddon/GetActivityAddonDetailsByIdAndLangCode/${this.Edit_Id}/${langCode}`).subscribe(res => {
      if (res && res.status && res.data) {
        this.AddOnLangForm.patchValue({
          addOn: res.data.addOn,
          description: res.data.description,
          activityAddonDetailId: res.data.activityAddonDetailId
        });
      } else {
        // Reset for new translation
        this.AddOnLangForm.patchValue({
          addOn: '',
          description: '',
          activityAddonDetailId: ''
        });
      }
    });
  }

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

    const formVal = this.AddOnLangForm.getRawValue();

    const postData = {
      activityAddonDetailId: formVal.activityAddonDetailId || '',
      activityAddonId: this.Edit_Id,
      languageCode: formVal.languageCode,
      addOn: formVal.addOn,
      description: formVal.description || '',
    };

    this.apiserv.Post('/ActivityAddon/ManageTranslationActivityAddonDetail', postData).subscribe(resp => {
      if (resp?.status) {
        this.commonMasterSer.showMessage(true, resp.message || 'Translation saved successfully');
        this.BackButton();
      } else {
        this.commonMasterSer.showMessage(false, resp?.message || 'Save failed');
      }
    });
  }

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

}
