import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, FormsModule, NgForm } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { TranslatePipe } from '@ngx-translate/core';
import { ToastrService } from 'ngx-toastr';
import { takeUntil } from 'rxjs';
import { AngularEditorConfig, AngularEditorModule } from '@kolkov/angular-editor';
import { Unsub } from '../../../../shared/class/unsub.class';
import { adminToolbar } from '../../../../shared/data/editortoolbar';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { NgSelectModule } from '@ng-select/ng-select';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { ImageUploadComponent } from '../../../../shared/common/includes/image-upload/image-upload.component';
import { MaxLengthValidatorDirective } from '../../../../shared/directives/max-length-validator.directive';

@Component({
  selector: 'app-artical-edit',
  templateUrl: './artical-edit.component.html',
  styleUrls: ['./artical-edit.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, NgSelectModule, FormsModule, AngularEditorModule, RouterLink, ImageUploadComponent, MaxLengthValidatorDirective]
})
export class ArticalEditComponent extends Unsub implements OnInit {
  article: any = {};
  public sendingResponse: { [key: string]: boolean } = {};
  allcategories: any = [];
  media: any = [];
  featureimage: any[] = [];
  id!: any;
  form2: FormGroup;
  categoryId!: any[];
  subcategoryId = [];
  form: FormGroup;
  ticketName: any;
  ticketName2: any[] = [];
  hassubcategoriess = [];
  toolbar: AngularEditorConfig = adminToolbar;
  setting: any;
  constructor(
    private adminService: AdminService,
    private toastr: ToastrService,
    private translate: TranslatePipe,
    private activeRoute: ActivatedRoute,
    public fb: FormBuilder,
    public router: Router,
    loaderService: LoaderService
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);
    this.activeRoute.paramMap.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.id = params.get('id');
        this.editArticleRes();
      },
    });

    this.form = this.fb.group({
      image: null,
    });

    this.form2 = this.fb.group({
      image: null,
    });

    this.toolbar.placeholder = this.translate.transform('Enter Your Text...');
  }
  editArticleRes() {
    this.loaderService.showLoader();
    this.adminService
      .getArticalDetails(this.id)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.allcategories = res.category;
          this.hassubcategoriess = res.subcategory;
          this.categoryId = res.article.category_id;
          this.subcategoryId = res.article.subcategory;
          if (res.article.tags) {
            this.tagslist = res.article.tags.split(',').map(e => e);
          }
          this.article = res.article;
          this.media = res.media;
          this.setting = res.setting?.original;
          this.loaderService.hideLoader();
        },
        error: () => this.loaderService.hideLoader()
      });
  }

  ngOnInit(): void {
  }
  categoryStatus = false;
  categorychange(id) {
    this.categoryStatus = true;
    const data = {
      "cat_id": id,
    };
    this.adminService.getCatagoryData(data).subscribe({
      next: (res) => {
        this.categoryStatus = false;
        this.hassubcategoriess = res.subcategories;
      },
    });
  }

  editArticle(ngform: NgForm, buttonId) {
    if (ngform.valid) {
      this.sendingResponse[buttonId] = true;
      const formData: any = new FormData();

      for (const key of Object.keys(ngform.value)) {
        formData.append(key, ngform.value[key]);
      }
      formData.append('tags', ngform.value.tags && ngform.value.tags.length > 1 ? ngform.value.tags.join(',') : ngform.value.tags?.[0]);
      for (let i = 0; i < this.ticketName2?.length; i++) {
        formData.append('article[]', this.ticketName2[i]);
      }
      for (let i = 0; i < this.ticketName?.length; i++) {
        formData.append('featureimage', this.ticketName[i]);
      }
      formData.append('featureImgRemoved', this.featureImgRemoved)
      formData.append('articleRemoved', this.articleRemoved)
      this.adminService
        .EditArtical(this.activeRoute.snapshot.params['id'], formData)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.router.navigate(['/admin/knowledge/articles']);
              ngform.resetForm();
              this.article = [];
              this.tagslist = [];
              this.form.reset({});
              this.form2.reset({});
            }
          },
          error: () => {
            this.sendingResponse[buttonId] = false;
          },
        });
    }
  }

  tagslist: any[] = [];

  featureImgRemoved: string[] = [];
  articleRemoved: number[] = [];

  handleDataFromChild(value: string) {
    this.article['message'] = value;
  }
  addTagFn(name: any) {
    return name;
  }


  onImageUploaded(value) {
    this.ticketName = value.ticketName;
    if (value.mediaremoveIds) {
      value.mediaremoveIds.forEach(e => this.featureImgRemoved.push(e.id))
    }
  }
  onImageUploaded2(value) {
    this.ticketName2 = value.ticketName;
    if (value.mediaremoveIds) {
      value.mediaremoveIds.forEach(e => this.articleRemoved.push(e.id))
    }
  }
}
