import { Component, OnInit } from '@angular/core'; // Import OnInit
import { Router, RouterModule } from '@angular/router';
import { AuthService } from '../../cores/services/auth.service';
import { FormsModule } from '@angular/forms';
import { RegistrationData } from '../../cores/interface/auth';
import { ToastrService } from 'ngx-toastr';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [FormsModule, RouterModule, CommonModule],
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
  username: string = '';
  password: string = '';
  email: string = '';
  fullname: string = '';
  loading: boolean = false;
  passwordVisible: boolean = false;

  constructor(private authService: AuthService, private router: Router, private toast: ToastrService) {}

  ngOnInit(): void {
    this.username = '';
    this.password = '';
    this.email = '';
    this.fullname = '';
  }

  togglePasswordVisibility() {
    this.passwordVisible = !this.passwordVisible;
  }

  onSubmit() {
    this.loading = true;
    if (!this.username || !this.password || !this.email || !this.fullname) {
      this.loading = false;
      this.toast.error('Please fill in all fields.');
      return;
    }

    const registrationData: RegistrationData = {
      username: this.username,
      pwd: this.password,
      email: this.email,
      google_id: '1', 
      fullname: this.fullname,
      avatar: ''
    };

    this.authService.register(registrationData).subscribe(
      (response) => {
        this.loading = false; 
        this.toast.success('Registration successful');
        this.router.navigate(['/auth']);
      },
      (error) => {
        this.loading = false;
        this.toast.error(error.error.message);
      }
    );
  }
}
