import { Component, OnInit } from '@angular/core';
import { environment } from 'src/environments/environment';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { UserService } from 'src/app/services/user.service';
import { UserProfileModel } from 'src/app/models/user.model';

@Component({
  selector: 'app-user-management',
  templateUrl: './user-management.component.html',
  styleUrls: ['./user-management.component.scss']
})

export class UserManagementComponent {
  memberlist: UserProfileModel[] = []
  selectedUser?: UserProfileModel
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.getUser()
  }

  getUser() {
    this.userService.getLists().subscribe(result => {
      this.memberlist = result
    })
  }

  getUserId() {
    this.userService.getById("73079f3b-b58a-46e6-a779-20a64911e505").subscribe(result => {
      console.log(result)
    })
  }

  saveUser() {
    if (this.selectedUser) {
      this.userService.save(this.selectedUser).subscribe(result => {
        console.log(result)
      })
    }
  }

  deleteUser() {
    if (this.selectedUser) {
      this.userService.delete(this.selectedUser).subscribe(result => {
        console.log(result)
      })
    }
  }

  updateUser() {
    if (this.selectedUser) {
      this.userService.update(this.selectedUser).subscribe(result => {
        console.log(result)
      })
    }
  }

  // memberlist: any[] = [];


  // ngOnInit(): void {
  //   // จำลองข้อมูลตัวอย่าง
  //   this.memberlist = [
  //     { id: 1, member_firstname: 'Alice', member_lastname: 'Smith', role: 'Admin' },
  //     { id: 2, member_firstname: 'Bob', member_lastname: 'Johnson', role: 'User' },
  //     { id: 3, member_firstname: 'Charlie', member_lastname: 'Brown', role: 'Manager' }
  //   ];
  // }
  // constructor(private http: HttpClient) {}

  // ngOnInit() {
  //   this.http.get<any[]>(environment.api + '/users')
  //     .subscribe(
  //       (data) => {
  //         this.memberlist = data;
  //         console.log('Data loaded:', this.memberlist);
  //       },
  //       (error) => {
  //         console.error('Error fetching data', error);
  //       }
  //     );
  //   }
  //   deleteMember(userId: number): void {
  //     if (confirm('Are you sure you want to delete this member?')) {
  //     this.http.delete(`${environment.api}/users/${userId}`).subscribe(
  //       (result: any) => {
  //         const index = this.memberlist.findIndex(user => user.user_id === userId);
  //       if (index !== -1) {
  //         this.memberlist.splice(index, 1);
  //       }
  //         console.log(result);

  //       },
  //       (error: HttpErrorResponse) => {
  //         alert(error.message);
  //       }
  //     );
  //   }}}
}
