import { Component, EventEmitter, input, Input, Output, signal } from "@angular/core"; import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms"; import { Error } from "@app/shared/components/error/error"; import { AddressRequest, AddressResponse } from "@app/features/checkout/services/address-service"; import { LoadingSpinner } from "@shared/components/loading-spinner/loading-spinner"; @Component({ selector: "app-address-form", imports: [ReactiveFormsModule, Error, LoadingSpinner], templateUrl: "./address-form.html", styleUrl: "./address-form.css", }) export class AddressForm { @Output() submitAddress: EventEmitter = new EventEmitter(); @Output() updateAddress: EventEmitter = new EventEmitter(); @Output() editingCanceled: EventEmitter = new EventEmitter(); isProcessing = input(false); addressForm = new FormGroup({ firstName: new FormControl("", { validators: [Validators.required, Validators.pattern("^[a-zA-Z]\\S+$")], }), lastName: new FormControl("", { validators: [Validators.required, Validators.pattern("^[a-zA-Z]\\S+$")], }), street: new FormControl("", { validators: Validators.required }), city: new FormControl("", { validators: Validators.required }), state: new FormControl("", { validators: Validators.required }), pinCode: new FormControl("", { validators: [Validators.required, Validators.pattern("^[0-9]{6}$")], }), }); protected isEditing = signal(false); protected address = signal(null); @Input() set initialData(address: AddressResponse) { if (address) { this.addressForm.patchValue(address); this.address.set(address); this.isEditing.set(true); } } submitForm() { if (this.addressForm.invalid) { this.addressForm.markAllAsTouched(); return; } const emittedData = this.addressForm.getRawValue() as AddressRequest; if (this.isEditing()) { const mergedData = { ...this.address(), ...emittedData }; this.updateAddress.emit(mergedData as unknown as AddressResponse); } else { this.submitAddress.emit(emittedData); } } cancelEditing() { this.addressForm.reset(); this.editingCanceled.emit(); } }