import {ChangeDetectorRef, Component, Input, ViewChild} from "@angular/core";
import {FormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {SdgSelectionComponent} from "../../../sdg/sdg-selection/sdg-selection.component";
import {FosSelectionComponent} from "../../../fos/fos-selection/fos-selection.component";
import {properties} from "../../../../../environments/environment";
import {EnvProperties} from "../../../utils/properties/env-properties";
import {EmailService} from "../../../utils/email/email.service";
import {Subscription} from "rxjs";
import {Composer} from "../../../utils/email/composer";
import {AlertModal} from "../../../utils/modal/alert";
import {StringUtils} from "../../../utils/string-utils.class";

@Component({
	selector: 'sdg-fos-suggest',
	template: `
    <modal-alert #selectionModal [large]="true" (alertOutput)="modalOutput()" (cancelOutput)="modalCancel()"
                 [okDisabled]="!sent && !selectionStep1 && (form.invalid || sending)">
      <ng-container *ngIf="isOpen">
        <sdg-selection *ngIf="subjects && subjectType == 'sdg'" #selection [class.uk-hidden]="!selectionStep1"
                       [subjects]="subjects" [entityType]="entityType"></sdg-selection>
        <fos-selection *ngIf="subjects && subjectType == 'fos'" #selection [class.uk-hidden]="!selectionStep1"
                       [subjects]="subjects" [contentHeight]="selectionModal.bodyHeight" [inModal]="true"></fos-selection>
        <div [class.uk-hidden]="selectionStep1">
          <div class="uk-flex uk-flex-column uk-flex-middle">
            <ng-container *ngIf="!sent && !error">
              <div>Thank you for your feedback.</div>
              <div>Before sending us your options, would you like to leave us your e-mail to notify you about the reporting status?</div>
              <div input class="uk-width-1-2 uk-margin-medium-top uk-margin-medium-bottom"
                   [formInput]="form.get('email')" placeholder="E-mail">
                <span note>(Optional)</span>
              </div>
              <div>
                <re-captcha (resolved)="handleRecaptcha($event)" [siteKey]="properties.reCaptchaSiteKey" 
                            [ngClass]="sending ? 'uk-hidden':''"></re-captcha>
                <loading [ngClass]="sending ? '':'uk-hidden'"></loading>
              </div>
            </ng-container>
            <ng-container *ngIf="sent">
              <p>Your feedback is successfully received and it will soon be reviewed by our graph experts!</p>
              <icon customClass="uk-text-background" name="check" [ratio]="4"></icon>
            </ng-container>
            <div *ngIf="error" class="uk-alert uk-alert-danger uk-text-center uk-width-large ng-star-inserted"
                 role="alert">Email sent failed! Please try again.
            </div>
          </div>
        </div>
      </ng-container>
    </modal-alert>
  `
})
export class SdgFosSuggestComponent {
  @Input() entityType: string;
	@Input() title;
  public subjectType: "fos" | "sdg" = "sdg";
  public subjects;
	public properties: EnvProperties = properties;
	public selectionStep1: boolean = true;
  @ViewChild("selectionModal") selectionModal: AlertModal;
	@ViewChild("selection") selection: SdgSelectionComponent | FosSelectionComponent;
	public form: UntypedFormGroup;
  public url: string = null;

  public sending: boolean = false;
  public sent: boolean = false;
  public error: boolean = false;
	subscriptions: Subscription[] = [];
  isOpen: boolean = false;

	constructor(private emailService: EmailService, private fb: FormBuilder, private cdr: ChangeDetectorRef) {}

	ngOnInit() {
		if (typeof window !== "undefined") {
      this.url = window.location.href;
    }
		this.init();
	}

	ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscription) {
        subscription.unsubscribe();
      }
    });
  }

  init() {
    this.form = this.fb.group({
      name: this.fb.control(this.title),
      url: this.fb.control(this.url),
      email: this.fb.control('', Validators.email),
      subjects: this.fb.control([]),
      recaptcha: this.fb.control('', Validators.required),
    });
  }

  public openSelectionModal() {
    this.sent = false;
    this.sending = false;
    this.error = false;
    this.selectionStep1 = true;
    this.init();

    this.selectionModal.cancelButton = false;
    if(this.subjectType == "sdg") {
      this.selectionModal.alertTitle = "Please select SDGs that are the most relevant for this "+this.getEntityName(this.entityType)+".";
    } else {
      this.selectionModal.alertTitle = "Please select Fields of Science that are the most relevant for this "+this.getEntityName(this.entityType)+".";
    }
    this.selectionModal.okButtonText = "Next";
    this.selectionModal.stayOpen = true;
    this.cdr.detectChanges();
    this.selectionModal.open();
  }

	public modalOutput() {
    this.selectionModal.previousButton = true;
    this.selectionModal.okButtonText = "Send feedback";

		if(this.selectionStep1) {
			this.selectionStep1 = false;
      if(this.subjectType == "sdg") {
        this.selectionModal.alertTitle = "Please send your feedback on most relevant SDGs for this "+this.getEntityName(this.entityType)+".";
      } else {
        this.selectionModal.alertTitle = "Please send your feedback on most relevant Fields of Science for this "+this.getEntityName(this.entityType)+".";
      }
    } else {
      this.sending = true;
			// email functionality
      this.form.get("subjects").setValue(this.selection.getSelectedSubjects().map(subject => subject.id));
			this.subscriptions.push(this.emailService.contact(this.properties,
				Composer.composeEmailForSdgsSuggestion(this.form.value, [this.properties.feedbackmail],  this.subjectType), this.form.get('recaptcha').value).subscribe(sent => {
				this.error = !sent;
				if (sent) {
					if (this.form.get('email').value !== '') {
						this.subscriptions.push(this.emailService.contact(this.properties,
							Composer.composeEmailForUserAfterFeedback([this.form.get('email').value])).subscribe(sent => {
							if (sent) {
								//console.log('An email has been sent to user ' + this.form.get('email').value);
							}
						}));
					}
					this.init();
					this.sent = true;

          this.selectionModal.alertTitle = "Thank you for your feedback";
          this.selectionModal.okButtonText = "OK";
          this.selectionModal.previousButton = false;
          this.selectionModal.stayOpen = false;
				}
				this.sending = false;
			}, error => {
				console.log(error);
				this.error = true;
				this.sending = false;
			}));
		}
	}

  public modalCancel() {
    if(this.subjectType == "sdg") {
      this.selectionModal.alertTitle = "Please select SDGs that are the most relevant for this "+this.getEntityName(this.entityType)+".";
    } else {
      this.selectionModal.alertTitle = "Please select Fields of Science that are the most relevant for this "+this.getEntityName(this.entityType)+".";
    }
    this.selectionStep1 = true;
    this.selectionModal.previousButton = false;
    this.selectionModal.okButtonText = "Next";
    this.selectionModal.stayOpen = true;
    this.error = false;
  }

	public handleRecaptcha(captchaResponse: string) {
    this.form.get('recaptcha').setValue(captchaResponse);
  }

  private getEntityName (entityType:string) {
    return StringUtils.getEntityName(entityType, false);
  }
}