import { Component, OnInit, OnDestroy } from '@angular/core';
import { AbstractControl, FormsModule, ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators, ValidatorFn, ValidationErrors } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { MatButtonModule } from '@angular/material/button';
import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';

import { Observable, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';

import { Errors, User } from 'src/app/core/models';
import { UserService } from 'src/app/core/services';
import { ListErrorsComponent } from 'src/app/components/shared';

@Component({
    selector: 'huapp-settings-page',
    styleUrls: ['settings.component.scss'],
    templateUrl: './settings.component.html',
    standalone: true,
    imports: [
        RouterLink, FormsModule, ReactiveFormsModule,
        MatButtonModule, MatIconModule, MatFormFieldModule, MatInputModule, MatDividerModule,
        ListErrorsComponent
    ]
})
export class SettingsComponent implements OnInit, OnDestroy {
    private _user: Subscription = new Subscription();
    title = 'Vos paramètres';
    bannerTitle = '';
    btnUpdateTitle = 'Mettre à jour';
    btnLogoutTitle = 'Se déconnecter';
    user: User = {} as User;
    settingsForm: UntypedFormGroup;
    errors: Errors = { errors: {} };
    isSubmitting = false;

    constructor(
        private router: Router,
        private titleService: Title,
        private userService: UserService,
        private fb: UntypedFormBuilder
    ) {
        // create form group using the form builder
        this.settingsForm = this.fb.group({
            username: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            firstname: ['', Validators.required],
            lastname: ['', Validators.required],
            phone: ['', Validators.required],
            password: ['', Validators.required],
            confirmPassword: ['', Validators.required],
            licence: '',
            poids: '',
            image: '',
            bg_image: ''
        }, { validators: this.checkPasswords });
        // Optional: subscribe to changes on the form :
        // this.settingsForm.valueChanges.pipe(this._scavenger.collect()).subscribe(values => this.updateUser(values));
    }

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

    ngOnInit() {
        this.titleService.setTitle(`Head Up - ${this.title}`);
        // Make a fresh copy of the current user's object to place in editable form fields
        Object.assign(this.user, this.userService.getCurrentUser());
        // Fill the form
        this.settingsForm.patchValue(this.user);
        if (this.user.username) {
            this.bannerTitle = `@${this.user.username}`;
        } else {
            this.bannerTitle = `${this.user.firstname} ${this.user.lastname}`;
        }
    }

    ngOnDestroy() {
        this._user.unsubscribe();
    }

    logout() {
        this.userService.purgeAuth();
        this.router.navigateByUrl('/login');
    }

    submitForm() {
        this.isSubmitting = true;

        // update the model
        this.updateUser(this.settingsForm.value);

        const user$: Observable<User> = this.userService.update(this.user).pipe(take(1));
        this._user = user$.subscribe({
            next: (updatedUser) => this.router.navigateByUrl('/profile/' + updatedUser.username),
            error: (err) => {
                this.errors = err;
                this.isSubmitting = false;
            }
        });
    }

    updateUser(values: NonNullable<unknown>) {
        Object.assign(this.user, values);
    }

    checkPasswords: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
        const pass = group.get('password')!.value;
        const confirmPass = group.get('confirmPassword')!.value
        return pass === confirmPass ? null : { notSame: true }
    }

}
