// angular
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

// libs
import { MatDialogRef } from '@angular/material/dialog';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

// app
import { ApiRoutes } from '../../../api-routes';
import { CurrencyModel } from '../../../model/currency.model';

@Component({
	templateUrl: './rate.currency.component.html',
	styleUrls: ['./rate.currency.component.scss'],
})
export class SettingsRateCurrencyComponent {
	public addForm!: FormGroup;
	public error?: any;

	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private fb: FormBuilder,
		private httpClient: HttpClient,
		private dialogRef: MatDialogRef<SettingsRateCurrencyComponent>,
		@Inject(MAT_DIALOG_DATA) public currency: CurrencyModel
	) {
	}

	public ngOnInit(): void {
		this.addForm = this.fb.group({
			id: [
				this.currency.id,
			],
			code: [
				this.currency.code,
			],
			symbol: [
				this.currency.symbol,
			],
			name: [
				this.currency.name,
			],
			shortName: [
				this.currency.shortName,
			],
			quantity: [
				this.currency.quantity || 1,
				[Validators.required],
			],
			rate: [
				this.currency.rate || 1,
				[Validators.required],
			],
			rateDate: [
				this.currency.rateDate,
				[Validators.required],
			],
			isPrimary: [
				this.currency.isPrimary,
			],
		});
	}

	closeDialog(): void {
		this.dialogRef.close();
	}

	onSubmitClick() {
		this.error = undefined;
		if (this.addForm.valid) {
			this.httpClient
				.put<CurrencyModel>(ApiRoutes.SettingsCurrency.replace(':id', this.addForm.value.id), this.addForm.value)
				.pipe(takeUntilDestroyed(this.destroyRef))
				.subscribe({
					next: (response) => {
						this.httpClient
							.post<CurrencyModel[]>(ApiRoutes.SettingsCurrenciesRate.replace(':id', this.addForm.value.id), this.addForm.value)
							.pipe(takeUntilDestroyed(this.destroyRef))
							.subscribe({
								next: (response) => {
									this.dialogRef.close({ refresh: true });
								},
								error: (error) => {
									this.error = error;
								},
							});
					},
					error: (error) => {
						this.error = error;
					}
				});
		}
	}
}
