import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { ConfirmDialogComponent, ConfirmDialogModel } from 'src/app/shared/confirm-dialog/confirm-dialog.component';

// Services
import { NotificationService } from 'src/app/core/services/notification.service';
import { apiUserService } from 'src/app/core/services/api/api.user.service';

function passwordMatchValidator(g: FormGroup) {
  const password = g.get('password')?.value;
  const confirmPassword = g.get('confirmPassword')?.value;
  if (password){
    if (password.length < 8) {
      g.get('password')?.setErrors({ passwordLength: true });
      return { passwordLength: true };
    } 
    if (password !== confirmPassword) {      
      g.get('confirmPassword')?.setErrors({ mismatch: true });
      return { mismatch: true };
    }

  }
  return null;
}

@Component({
  selector: 'app-favorites-page',
  templateUrl: './user-edit-page.component.html',
  styleUrls: ['./user-edit-page.component.css']
})

export class UserEditPageComponent implements OnInit {
  
  id: any = '';  
  
  userForm: FormGroup;

  constructor(
    private route: ActivatedRoute,
    private notificationService: NotificationService,
    private router: Router,
    public dialog: MatDialog,
    private apiUserService: apiUserService,
    private fb: FormBuilder
    ) {
        
        this.userForm = this.fb.group({
          username: ['', Validators.required],
          email: ['', [Validators.required, Validators.email]],
          password: [''],
          confirmPassword: [''],
          isAdmin: [false],
          isAgent: [false]
        }, { validator: passwordMatchValidator });

    }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {      
      this.id = params.get('id');
      
      if(this.id) {
        this.apiUserService.getUser(this.id).subscribe((data: any) => {
          console.log(data);
          
          // Update form values
          this.userForm.patchValue({
            username: data.username,
            email: data.email,
            isAdmin: data.isAdmin,
            isAgent: data.isAgent
          });
        });
      }
    });
  }

  save(): void {
    if (this.userForm.valid) {      
      let userData = this.userForm.value
      console.log(userData);
      if(this.id) {
        userData._id = this.id;
        // Edit User
        this.apiUserService.updateUser(userData).subscribe((data: any) => {
          this.notificationService.openSnackBar("User updated successfully");
          this.router.navigate(['/users']);
        });
      } else {
        // New User
        this.apiUserService.saveUser(userData).subscribe((data: any) => {
          this.notificationService.openSnackBar("User created successfully");
          this.router.navigate(['/users']);
        });
      }
    }  
  }

  deleteUser(): void {
    if (this.id) {
      const dialogRef = this.dialog.open(ConfirmDialogComponent, {
        width: '250px',
        data: {title: 'Delete User ?', message: 'Are you sure you want to delete this user?'}
      });

      dialogRef.afterClosed().subscribe(result => {
        if (result) {
          // User clicked Yes

          this.apiUserService.deleteUser(this.id).subscribe((data: any) => {
            this.notificationService.openSnackBar("User deleted successfully");
            this.router.navigate(['/users']);
          });
        }
      });
    }
  }

}

