import { Component, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { User } from '../user';
import { ToastService } from 'src/app/toast/toast-service';
import { BaseService } from 'src/app/shared/service/base.service';
import { RoleService } from '../../rolelist/role.service';
import { StorageService } from 'src/app/shared/service/storage.service';

// Define the Role interface
interface Role {
  id: number;
  name: string;
}

interface Permission {
  Type: string;
  Object: string;
  Info: string;
}

@Component({
  selector: 'app-user-properties',
  templateUrl: './user-properties.component.html',
  styleUrls: ['./user-properties.component.scss']
})
export class UserPropertiesComponent implements OnInit {
  @ViewChild('scrollDataModal', { static: true }) scrollDataModal!: TemplateRef<any>;

  @Input() user: User | null = null; // Input to receive user data from parent component
  @Output() userUpdated = new EventEmitter<void>();


  userForm!: FormGroup;
  submitted = false;
  activeTab = 1;

  allRoles: any

  assignedRoles: any; // Assume this is populated with roles assigned to the user

  tenants:any

  selectedTenant:any;

  permissions: Permission[] = [
    { Type: 'Type 1', Object: 'Object 1', Info: 'Info 1' },
    { Type: 'Type 2', Object: 'Object 2', Info: 'Info 2' }
  ];

  allTypes: string[] = [
    'Type 1',
    'Type 2',
    'Type 3'
    // Add more types as needed
  ];

  newPermission: Permission = {
    Type: '',
    Object: '',
    Info: ''
  };

  constructor(private formBuilder: FormBuilder,
              private modalService: NgbModal,
              public toastService: ToastService,
              public baseService : BaseService, 
              public roleService :RoleService,
              private storrage:StorageService
            ) {
    this.userForm = this.formBuilder.group({
      username: ['', Validators.required],
      organization: [''],
      firstName: ['', Validators.required],
      lastName: [''],
      email: ['', [Validators.required, Validators.email]],
      domainId: ['', Validators.required],
      tenant: [''],
      loginDisabled: [false],
      lockedOut: [false],
      external: [''],
      created: [''],
      lastLogin: [''],
      createdBy: ['']
    });
  }

  ngOnInit(): void {
    this.getAllRole()

    this.roleService.tenant$.subscribe(data => {
      this.tenants = data;
      console.log(this.tenants);
      
    });
  }

  hasRole(role:string){
    if(role==this.storrage.getItem('role'))
    {
      return true;
    }
    else{
      return false;
    }

  }

  getAllRole() {
    this.baseService.getData('access/roles').subscribe(
      (data: any) => {
        if (data) {
          console.log(data);
          this.allRoles = data
        }
      },
      (err) => {
        console.log(err);
      }
    );
  }

  addPermission() {
    if (this.newPermission.Type && this.newPermission.Object && this.newPermission.Info) {
      this.permissions.push({ ...this.newPermission });
      this.newPermission = { Type: '', Object: '', Info: '' }; // Clear input fields
    }
  }

  deletePermission(permission: Permission) {
    const index = this.permissions.indexOf(permission);
    if (index >= 0) {
      this.permissions.splice(index, 1);
    }
  }

   // This method checks if the role is currently assigned
   isRoleAssigned(role:any): boolean {    
    return this.assignedRoles.some(r => r.role === role.role);
  }

  // This method handles the selection of a role
  selectRole(role: any): void {

    console.log(this.assignedRoles);
    console.log(role);

    this.baseService.deleteData(`user/${this.user.id}/roles/${this.assignedRoles[0].role}`).subscribe(
      response => {
        console.log('Request successful', response);
        this.toastService.show('User updated successfully!', { classname: 'bg-success text-light', delay: 3000 });
      },
      error => {
        console.error('Request failed', error);
      }
    );


    this.baseService.postData1(`user/${this.user.id}/roles/${role.role}`).subscribe(
      response => {
        console.log('Request successful', response);
        this.toastService.show('User updated successfully!', { classname: 'bg-success text-light', delay: 3000 });
      },
      error => {
        console.error('Request failed', error);
      }
    );

    
    
    
    // You can add any additional logic here, such as updating the backend
  }

  getTenantName(userid: any): string {    
    const tenant = this.tenants.find(tenant => 
      tenant.tenantUsers.some(role => role.userId ===  String(userid))
    );

    this.selectedTenant=tenant;
    return tenant ? tenant.tenantUUID : 'Tenant not found';
  }

  onTenantChange(event: Event): void {
    const SelectedTenantid = (event.target as HTMLSelectElement).value;
    console.log('Selected tenant:', SelectedTenantid);
  }

  get f() { return this.userForm.controls; }

  onSubmit() {
    this.submitted = true;

    console.log("inside submit");
    
    if (this.userForm.invalid) {
      return;
    }

    // Handle form submission
    console.log('Form Submitted', this.userForm.value);

    const formData = new URLSearchParams();
    formData.append('username', this.userForm.get('username').value);
      formData.append('name', this.userForm.get('firstName').value);
      formData.append('lastName', this.userForm.get('lastName').value);
      formData.append('email', this.userForm.get('email').value);
      formData.append('organization', this.userForm.get('organization').value);
      formData.append('isLocked', this.userForm.get('lockedOut').value);

    this.baseService.putData(`user/${this.user.id}`, formData).subscribe(
      response => {
        console.log('Request successful', response);
        this.toastService.show('User updated successfully!', { classname: 'bg-success text-light', delay: 3000 });

        this.updatetenantUser(this.userForm.get('tenant').value);
      },
      error => {
        console.error('Request failed', error);
      }
    );


    // this.activeModal.close(this.userForm.value);
  }

  updatetenantUser(tenantuuid:any){
    if(this.selectedTenant.tenantUUID!=tenantuuid)
    {
        // Handle form submission
      const tenantuser =  this.selectedTenant.tenantUsers.find(role => role.userId === String(this.user.id))

      console.log(tenantuser);
      
      const formData = new URLSearchParams();
      formData.append('tenantId', tenantuuid);
      formData.append('userId', this.user.id);

    this.baseService.putData(`tenants/updateTenantUser/${tenantuser.id}`, formData).subscribe(
      response => {
        console.log('Request successful', response);
        // this.toastService.show('User updated successfully!', { classname: 'bg-success text-light', delay: 3000 });
      },
      error => {
        console.error('Request failed', error);
      }
    );
    }
  }

  openModal() {
    this.modalService.open(this.scrollDataModal, { size: 'lg', scrollable: true, windowClass: 'modal-holder', centered: true, backdrop: "static" });

    console.log(this.user);

    if (this.user) {
      this.mapUserData(this.user);
    }

  }

  formatDate(dateString: string): string {
    const date = new Date(dateString);
    const day = ('0' + date.getDate()).slice(-2);
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
  }


  private mapUserData(userData: any) {
    this.userForm.patchValue({
      username: userData.username,
      firstName: userData.name,
      lastName: userData.lastName,
      email: userData.email,
      domainId: userData.userId,
      tenant: this.getTenantName(userData.id),
      loginDisabled: false,
      lockedOut: false,
      external: 'No',
      organization:userData.organization,
      created: this.formatDate(userData.creationDt),
      lastLogin: '',
      createdBy: userData.createdby ? userData.createdby: ''
      // other fields as necessary
    });

    // Map roles
    this.assignedRoles = this.allRoles.filter(role => userData.roles.includes(role.role));

    // Map permissions
    this.permissions = userData.permissions.map((perm: string) => ({
      Type: 'Custom', // Assign a default or custom type if not provided
      Object: perm, // Assuming permission is a string
      Info: 'Info not available' // Assign default or actual info if available
    }));

    this.userForm.get('username')?.disable();
    this.userForm.get('domainId')?.disable();
    this.userForm.get('created')?.disable();
    this.userForm.get('createdBy')?.disable();
    this.userForm.get('external')?.disable();
    this.userForm.get('lastLogin')?.disable();

  }

  onSave() {
    // Handle save action
    if (this.userForm.valid) {
      console.log('User Form Data:', this.userForm.value);
      console.log('Assigned Roles:', this.assignedRoles);
      console.log('Permissions:', this.permissions);
    }
  }

  dismissModal(){
    this.modalService.dismissAll();
    this.userUpdated.emit();
  }
}
