import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ModalService } from '@libs/ui';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';

@Component({
  selector: 'app-add-product-review',
  templateUrl: './add-product-review.component.html',
  styleUrls: ['./add-product-review.component.scss'],
})
export class AddProductReviewComponent implements OnInit {
  id = 'add-product-review-modal';
  stars = [
    { id: 1, selected: false },
    { id: 2, selected: false },
    { id: 3, selected: false },
    { id: 4, selected: false },
    { id: 5, selected: false },
  ];
  submitted = false;
  reviewForm: FormGroup;
  constructor(private modalService: ModalService, private fb: FormBuilder) {}

  get f() {
    return this.reviewForm.controls;
  }

  valueChanges(control: AbstractControl, value: string) {
    control.setValue(value);
  }

  setComment(comment: string) {
    this.reviewForm.patchValue({
      comment: comment,
    });
  }

  ngOnInit() {
    this.reviewForm = this.buildForm(this.fb);
  }

  openDialog() {
    this.modalService.open(this.id);
  }

  closeDialog() {
    this.clearForm();
    this.modalService.close(this.id);
  }

  setStars(id: number) {
    this.stars = this.stars.map((star: any) => {
      if (star.id <= id) {
        return { id: star.id, selected: true };
      }
      return { id: star.id, selected: false };
    });
    const selectedStars = this.stars.filter((t) => t.selected === true).length;
    if (selectedStars > 0) {
      this.reviewForm.patchValue({
        stars: selectedStars,
      });
    }
  }

  submitReview() {
    if (this.reviewForm.valid) {
      this.closeDialog();
    } else {
      this.submitted = true;
    }
  }

  buildForm(fb: FormBuilder): FormGroup {
    return fb.group({
      heading: ['', Validators.required],
      stars: ['', Validators.required],
      comment: ['', Validators.required],
    });
  }

  clearForm() {
    this.stars = this.stars.map((s) => {
      return { id: s.id, selected: false };
    });
    this.submitted = false;
    this.reviewForm.reset();
  }
}
