import { Component, DestroyRef, inject, OnInit } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, ActivatedRoute } from '@angular/router';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { GeneralErrorModel } from '../../core/models/general-error.model';
import { AuthService } from '../../core/service/auth.service';

type SignupForm = {
	email: FormControl<string | null>;
	password: FormControl<string | null>;
	cpassword: FormControl<string | null>;
};

@Component({
	selector: 'app-signup',
	templateUrl: './signup.component.html',
	styleUrls: ['./signup.component.scss'],
})
export class SignupComponent implements OnInit {
	authForm!: FormGroup<SignupForm>;
	submitted = false;
	returnUrl!: string;
	hide = true;
	chide = true;
	generalError?: GeneralErrorModel;

	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private formBuilder: FormBuilder,
		private route: ActivatedRoute,
		private router: Router,
		private authService: AuthService
	) {

	}

	ngOnInit() {
		this.authForm = this.formBuilder.group({
			email: ['', [Validators.required, Validators.email, Validators.minLength(5)]],
			password: [
				'',
				[
					Validators.required,
					Validators.minLength(8),
					Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).+$/),
				],
			],
			cpassword: ['', Validators.required],
		}, {
			validators: (group: AbstractControl) => {
				const password = group.get('password')?.value;
				const confirm = group.get('cpassword')?.value;
				return password && confirm && password !== confirm
					? { passwordMismatch: true }
					: null;
			},
		});
		// get return url from route parameters or default to '/'
		this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
	}

	get f() {
		return this.authForm.controls;
	}

	onSubmit() {
		this.submitted = true;
		// stop here if form is invalid
		if (this.authForm.invalid) {
			return;
		}

		if (this.authForm.hasError('passwordMismatch')) {
			return;
		}

		this.authService.register({
			username: this.authForm.get('email')!.value!,
			password: this.authForm.get('password')!.value!,
			confirmPassword: this.authForm.get('cpassword')!.value!,
		}).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(
			resp => {
				if (!resp.succeeded) {
					this.generalError = resp as GeneralErrorModel;
					return;
				}

				// Auto sign-in with email+password after successful register
				this.authService.login({
					username: this.authForm.get('email')!.value!,
					password: this.authForm.get('password')!.value!,
				}).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(login => {
					if (login.success) {
						this.router.navigate([this.returnUrl || '/dashboard/rests']);
					} else {
						this.router.navigate(['authentication/signin']);
					}
				});
			},
			err => {
				this.generalError = err.error as GeneralErrorModel;
			}
		);
	}

	loginAuth0() {
		this.authService.loginAuth0()
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(x => {
		});
	}
}
