import { Component, OnInit, Input, ElementRef } from "@angular/core"
import { FormGroup } from "@angular/forms"
import { Agreement } from "../agreement.model"
import { CurrencyFormatterService } from "../currency-formatter.service"

@Component({
  selector: "app-investment-amount",
  templateUrl: "./investment-amount.component.html",
  styleUrls: ["./investment-amount.component.scss"]
})
export class InvestmentAmountComponent implements OnInit {
  @Input() agreements: Record<number, Agreement>
  @Input() form: FormGroup

  constructor(public formatter: CurrencyFormatterService, private myElement: ElementRef) {}

  ngOnInit(): void {
    const element = this.myElement.nativeElement as Element
    const select = element.querySelector("duet-select") as HTMLDuetSelectElement
    const input = element.querySelector("duet-input") as HTMLDuetInputElement
    select.addEventListener("duetChange", (e: CustomEvent<{value: number}>) => {
      this.form.controls['agreement'].setValue(e.detail.value)
    })
    input.addEventListener("duetChange", (e: CustomEvent<{value: string}>) => {
      this.form.controls['additionalInvestment'].setValue(Number(e.detail.value))
    })
  }

  get selectedAgreement() {
    return this.agreements[this.form.value.agreement]
  }

  get agreementOptions() {
    return Object.entries(this.agreements).map(([value, { label, price }]) => {
      return {
        value,
        label: `${label} - ${this.formatter.format(price)}`
      }
    })
  }
}
