import { Component, Input, OnInit } from "@angular/core";
import { CommonModule } from "@angular/common";
import { SidenavService } from "../sidenav/sidenav.service";
import { NgbDropdownModule, NgbModal } from "@ng-bootstrap/ng-bootstrap";
import { ConfirmationModalComponent } from "../../components/confirmation-modal/confirmation-modal.component";
import { AuthService } from "src/app/cores/services/auth.service";
import { HelpersService } from "src/app/cores/services/helpers.service";
import { ActionComponent } from "./action/action.component";
import { Subject, takeUntil } from "rxjs";
import { ChangePasswordService } from "src/app/cores/api-services/manage/change-password.service";
import { ActivatedRoute } from "@angular/router";

@Component({
  selector: "dashboard-topbar",
  standalone: true,
  imports: [CommonModule, NgbDropdownModule],
  templateUrl: "./topbar.component.html",
  styleUrls: ["./topbar.component.scss"],
})
export class TopbarComponent implements OnInit {
  dataUpdateSubs$ = new Subject<void>();

  @Input() isMobile = false;
  fullName: string = "";
  email: string = "";

  id = this.activatedRoute.snapshot.params["id"];

  constructor(
    private api: ChangePasswordService,
    private modal: NgbModal,
    private helpers: HelpersService,
    private activatedRoute: ActivatedRoute,
    private sidenav: SidenavService,
    private auth: AuthService
  ) {}

  loggedUser = this.auth.getLoggedUser();
  ngOnInit(): void {
    if (this.loggedUser) {
      this.fullName = this.loggedUser.fullname;
      this.email = this.loggedUser.email;
    }
  }

  onTriggerMenu(): void {
    this.sidenav.triggerSideMenu();
  }

  changePassword(): void {
    const modalRef = this.modal.open(ActionComponent);
    modalRef.componentInstance.action = "update";
    modalRef.result.then(
      (result) => {
        if (result) {
          this.api
            .update(this.loggedUser.id, result)
            .pipe(takeUntil(this.dataUpdateSubs$))
            .subscribe({
              next: () => {
                this.helpers.toast("success", "Data berhasil diubah");
              },
              error: (e) => {
                this.helpers.toast("error", e.error.message);
              },
            });
        }
      },
      () => {}
    );
  }

  get2letters(name: string): string {
    const collap = name
      .toUpperCase()
      .split(" ")
      .map((word) => word.charAt(0))
      .join("");
    return collap;
  }

  onLogout(): void {
    const modalRef = this.modal.open(ConfirmationModalComponent, {
      size: "sm",
    });

    modalRef.result.then((result) => {
      if (result) {
        this.auth.logout();
      }
    });
  }
}
