import { Component, inject } from '@angular/core'
import { FormBuilder, Validators } from '@angular/forms'
import { EmailTemplate } from '@api-client/angular'
import { DialogRef } from '@ngneat/dialog'
import { AsyncPipe } from '@angular/common'
import { EmailTemplateDataParserPipe } from '../email-template-data-parser.pipe'
import { SanitizePipe } from '../sanitize.pipe'

@Component({
	selector: 'kadi-email-template-preview',
	templateUrl: './email-template-preview.component.html',
	styles: [
		`
			:host {
				height: 100%;
			}
		`,
	],
	imports: [AsyncPipe, EmailTemplateDataParserPipe, SanitizePipe],
})
export class EmailTemplatePreviewComponent {
	private readonly _dialogRef = inject(DialogRef)
	private readonly _formBuilder = inject(FormBuilder)

	form = this._formBuilder.group({
		subject: this._formBuilder.control('', { validators: Validators.required, nonNullable: true }),
		body: this._formBuilder.control('', { validators: Validators.required, nonNullable: true }),
	})
	template: EmailTemplate

	constructor() {
		this.template = this._dialogRef.data['template']
		this.form.controls.subject.setValue(this.template.subject)
		this.form.controls.body.setValue(this.template.body)
	}

	save(): void {
		if (this.form.invalid || !this.form.value.subject || !this.form.value.body) return

		this.template = {
			...this.template,
			subject: this.form.value.subject,
			body: this.form.value.body,
		}

		this._dialogRef.close(this.template)
	}
}
