import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DepartmentService } from './service/department.service';
import { RgtrDepartment } from '../model/rgtrDepartment.model';
import { ToastrModule, ToastrService } from 'ngx-toastr';
import { HttpStatusCode } from '@angular/common/http';
import { lastValueFrom } from 'rxjs';
import { UserService } from '../user/service/user.service';
import { Router } from '@angular/router';

@Component({
    selector: 'app-rgtr-department',
    templateUrl: './rgtr-department.component.html',
    styleUrls: ['./rgtr-department.component.css'],
    standalone: false
})
export class RgtrDepartmentComponent implements OnInit{
  originalDepartmentName: string;


  constructor(private departmentService:DepartmentService,private toastr:ToastrService,
    private userService:UserService,private router:Router){
    this.departmentDataSource = new MatTableDataSource<any>();
    
  }
  isLoadingData:boolean=false
  ngOnInit(): void {
    this.getLoggedInUser();
    // this.getAllDepartments();
      
  }
  loggedInEmail:string=localStorage.getItem('email');
   departmentList: any[];
    departmentDataSource: MatTableDataSource<any>;
    @ViewChild(MatPaginator) paginator!: MatPaginator;
    @ViewChild(MatSort) sort!: MatSort;
    displayedDepartmentColumn=[
      'departmentId',
      'departmentName',
      'departmentCode',
      'departmentStatus',
      'createdDateTime',
      'modifiedBy',
      'modifiedDateTime',
      'active',
      'edit',
      'delete'
    ];
    ngAfterViewInit() {
      // This is necessary to apply the sort and paginator after the data is loaded
      this.departmentDataSource.sort = this.sort;
      this.departmentDataSource.paginator = this.paginator;
    }
    getAllDepartments(){
      this.isLoadingData=true;
      this.departmentService.getAllDepartments().subscribe({
        next:(response)=>{
          this.departmentList=response.body;
          console.log(this.departmentList)
          // this.departmentDataSource.data=this.departmentList;
          // this.departmentDataSource.sort=this.sort;
          // setTimeout(() => {
          //   this.departmentDataSource.paginator=this.paginator;
          // }, 0);
          // this.isLoadingData=false;
          this.departmentDataSource.data = this.departmentList;
          // this.departmentList.forEach((item, index) => {
          //   item.departmentId= index+1; // Add originalIndex property to your data
        //  });
          this.departmentDataSource.paginator = this.paginator;
          console.log(this.sort)
          // setTimeout(() => {
          //   this.departmentDataSource.sort = this.sort;
          // }, 0);
          this.isLoadingData=false;
        
        },error:(error)=>{
          this.isLoadingData=false;
          if(error.status===HttpStatusCode.Unauthorized){
            this.router.navigateByUrl('/session-timeout')
          }
        }
      })
    }
    loggedInUser: any;
    async getLoggedInUser(){
       await lastValueFrom(this.userService.getRgtrUserByEmailId(this.loggedInEmail)).then(
        response => {
          if(response.status === HttpStatusCode.Ok){
            this.loggedInUser = response.body;
            //console.log(this.loggedInUser)
            this.getAllDepartments();
          }
        },error => {
          //console.log(error);
        }
       )
      }
    
    department:RgtrDepartment=new RgtrDepartment();
    createdDepartment: RgtrDepartment;
    isDepartmentNameValid:boolean=false;
    isDepartmentCodeValid:boolean=false;
    
  createDepartment(){
    let isNameValid = true;
    // let isHeadValid = true;
    let isCodeValid = true;
    // let isLocationValid = true;
    var flag = 0;
    
    if(this.isDepartmentNameValid === false){
      var valid = this.validateDepartmentName();
      isNameValid = valid;
      flag = 1;
    }
    if(this.isDepartmentCodeValid === false){
     var valid = this.validateDepartmentCode();
      isCodeValid = valid;
      flag = 1;
    }
   
   
    // if(flag==1){
    //   this.toastr.error('Please fill the required fields')
    // }
    if(isNameValid === true && isCodeValid === true
    ){
    //set createdBy
    // this.addDepartment.departmentName = this.transformToTitleCase(this.addDepartment.departmentName);
    // this.addDepartment.departmentAddress = this.transformToTitleCase(this.addDepartment.departmentAddress);
    // this.addDepartment.departmentCode = this.addDepartment.departmentCode.toUpperCase();

    this.department.createdBy =this.loggedInUser.userName;
    this.department.createdByEmailId = this.loggedInUser.userId;
  
    this.departmentService.addDepartment(this.department).subscribe({
      next: (response)=> {
        if(response.status === HttpStatusCode.Created){
          this.createdDepartment = response.body;
        this.toastr.success('Department added successfully')
        document.getElementById('closeAddModal').click();
          setTimeout(()=>{
            window.location.reload();
          },1000)
        }
      },error: (error) => {
        if(error.status === HttpStatusCode.Unauthorized){
          this.router.navigateByUrl('/session-timeout')
        }else{
          this.toastr.error("Department name '"+this.department.departmentName+ "' already exists")
          //document.getElementById('closeAddModal').click();
        }
        
      }
     })
     }}
  
    // addDepartment(){
    //   this.departmentService.addDepartment(this.department).subscribe({
    //     next:(response)=>{
    //       this.toastr.success("Department added successfully");
    //     }
    //   })
    // }
    departmentNameErrorInfo: string = '';
    departmentCodeErrorInfo:string='';
    // isDepartmentNameValid = false;
    validateDepartmentName() {
      // Check if departmentName exists before trying to trim
      if (!this.department?.departmentName) {
        this.departmentNameErrorInfo = 'Department name cannot be empty';
        this.isDepartmentNameValid = false;
        return false; // Return early if department name is missing
      }
    
      const departmentName = this.department.departmentName.trim();
    
      const regex = /^[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)*$/;
    
      if (departmentName === '') {
        this.departmentNameErrorInfo = 'Department name cannot be empty';
        this.isDepartmentNameValid = false;
        return false;
      }
    
      if (departmentName.startsWith(" ")) {
        this.departmentNameErrorInfo = 'Department name cannot start with a space.';
        this.isDepartmentNameValid = false;
      } else if (!/^[A-Za-z0-9]/.test(departmentName)) {
        this.departmentNameErrorInfo = 'Department name must start with an alphabet or a digit.';
        this.isDepartmentNameValid = false;
      } else if (!regex.test(departmentName)) {
        this.departmentNameErrorInfo = 'Department name can only contain letters, numbers, hyphens, underscores.';
        this.isDepartmentNameValid = false;
      } else if (departmentName.length < 2) {
        this.departmentNameErrorInfo = 'Department name should have a minimum of 2 characters.';
        this.isDepartmentNameValid = false;
      } else if (departmentName.length > 30) {
        this.departmentNameErrorInfo = 'Department name should not exceed more than 30 characters.';
        this.isDepartmentNameValid = false;
      } else {
        this.isDepartmentNameValid = true;
        this.departmentNameErrorInfo = '';
      }
    
      return this.isDepartmentNameValid;
    }
    
    validateDepartmentCode() {
      if (!this.department?.departmentCode) {
        this.departmentCodeErrorInfo = 'Department code cannot be empty';
        this.isDepartmentCodeValid = false;
        return false; // Return early if department code is missing
      }
    
      const departmentCode = this.department.departmentCode.trim();
      const regex = /^[A-Za-z0-9][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)*$/;
    
      if (departmentCode === '') {
        this.departmentCodeErrorInfo = 'Department code cannot be empty';
        this.isDepartmentCodeValid = false;
        return false;
      }
    
      if (departmentCode.startsWith(" ")) {
        this.departmentCodeErrorInfo = 'Department code cannot start with a space.';
        this.isDepartmentCodeValid = false;
      } else if (!/^[A-Za-z0-9]/.test(departmentCode)) {
        this.departmentCodeErrorInfo = 'Department code must start with an alphabet or a digit.';
        this.isDepartmentCodeValid = false;
      } else if (!regex.test(departmentCode)) {
        this.departmentCodeErrorInfo = 'Department code can only contain letters, numbers, hyphens, and underscores.';
        this.isDepartmentCodeValid = false;
      } else if (departmentCode.length < 1) {
        this.departmentCodeErrorInfo = 'Department code should be minimum of 1 character.';
        this.isDepartmentCodeValid = false;
      } else if (departmentCode.length > 15) {
        this.departmentCodeErrorInfo = 'Department code should not exceed more than 15 characters.';
        this.isDepartmentCodeValid = false;
      } else {
        this.isDepartmentCodeValid = true;
        this.departmentCodeErrorInfo = '';
      }
    
      return this.isDepartmentCodeValid;
    }
      
 

    clearErrorMessages(){
      this.departmentNameErrorInfo = '';
      this.department.departmentName = '';
      this.departmentCodeErrorInfo='';
      this.department.departmentCode='';
      this.updatedDepartmentNameErrorInfo=''
      this.updatedDepartmentCodeErrorInfo=''
      this.existingDepartment.departmentName='';
      this.existingDepartment.departmentCode='';
    }

    existingDepartment:RgtrDepartment=new RgtrDepartment();
    isUpdatedDepartmentNameValid:boolean=false;
    isUpdatedDepartmentCodeValid:boolean=false;
    modifyDepartment(){
      this.validateUpdatedDepartmentName();
      this.validateUpdatedDepartmentCode();
    
      // Check if both department name and code are invalid
      if (!this.isUpdatedDepartmentNameValid || !this.isUpdatedDepartmentCodeValid) {
        // this.toastr.error('Please fill all required fields');
        return;
      }
      if (this.existingDepartment.departmentName !== this.originalDepartmentName) {
      
                  this.validateUpdatedDepartmentName();
      }
    
      this.departmentService.updateDepartment(this.existingDepartment).subscribe({
        next: (response) => {
          if(response.status === HttpStatusCode.Created){
            this.toastr.success("Department updated successfully")
            document.getElementById('closeUpdateModal').click();
            setTimeout(()=>{
              window.location.reload();
            },1000)
          }
        },error: (error) => {
          if(error.status === HttpStatusCode.Unauthorized){
            this.router.navigateByUrl('/session-timeout')
          }

          else{
            this.toastr.error("Department name '" +this.existingDepartment.departmentName+ "' already exists")
        }
        }
       })
       }
    

    updatedDepartmentNameErrorInfo: string = ''
    // isUpdatedDepartmentNameValid = false;
    validateUpdatedDepartmentName() {
      // Check if departmentName exists before trying to trim
      if (!this.existingDepartment?.departmentName) {
        this.updatedDepartmentNameErrorInfo = 'Department name cannot be empty';
        this.isUpdatedDepartmentNameValid = false;
        return false; // Return early if department name is missing
      }
    
      const departmentName = this.existingDepartment.departmentName.trim();
    
      const regex = /^[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)*$/;
    
      if (departmentName === '') {
        this.updatedDepartmentNameErrorInfo = 'Department name cannot be empty';
        this.isUpdatedDepartmentNameValid = false;
        return false;
      }
    
      if (departmentName.startsWith(" ")) {
        this.updatedDepartmentNameErrorInfo = 'Department name cannot start with a space.';
        this.isUpdatedDepartmentNameValid = false;
      } else if (!/^[A-Za-z0-9]/.test(departmentName)) {
        this.updatedDepartmentNameErrorInfo = 'Department name must start with an alphabet or a digit.';
        this.isUpdatedDepartmentNameValid = false;
      } else if (!regex.test(departmentName)) {
        this.updatedDepartmentNameErrorInfo = 'Department name can only contain letters, numbers, hyphens, underscores.';
        this.isUpdatedDepartmentNameValid = false;
      } else if (departmentName.length < 2) {
        this.updatedDepartmentNameErrorInfo = 'Department name should have a minimum of 2 characters.';
        this.isUpdatedDepartmentNameValid = false;
      } else if (departmentName.length > 30) {
        this.updatedDepartmentNameErrorInfo = 'Department name should not exceed more than 30 characters.';
        this.isUpdatedDepartmentNameValid = false;
      } else {
        this.isUpdatedDepartmentNameValid = true;
        this.updatedDepartmentNameErrorInfo = '';
      }
    
      return this.isUpdatedDepartmentNameValid;
    }
     updatedDepartmentCodeErrorInfo: string = ''
    //  isUpdatedDepartmentCodeValid = false;
    validateUpdatedDepartmentCode() {
      if (!this.existingDepartment?.departmentCode) {
        this.updatedDepartmentCodeErrorInfo = 'Department code cannot be empty';
        this.isUpdatedDepartmentCodeValid = false;
        return false; // Return early if department code is missing
      }
    
      const departmentCode = this.existingDepartment.departmentCode.trim();
      const regex = /^[A-Za-z0-9][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)*$/;
    
      if (departmentCode === '') {
        this.updatedDepartmentCodeErrorInfo = 'Department code cannot be empty';
        this.isUpdatedDepartmentCodeValid = false;
        return false;
      }
    
      if (departmentCode.startsWith(" ")) {
        this.updatedDepartmentCodeErrorInfo = 'Department code cannot start with a space.';
        this.isUpdatedDepartmentCodeValid = false;
      } else if (!/^[A-Za-z0-9]/.test(departmentCode)) {
        this.updatedDepartmentCodeErrorInfo = 'Department code must start with an alphabet or a digit.';
        this.isUpdatedDepartmentCodeValid = false;
      } else if (!regex.test(departmentCode)) {
        this.updatedDepartmentCodeErrorInfo = 'Department code can only contain letters, numbers, hyphens, and underscores.';
        this.isUpdatedDepartmentCodeValid = false;
      } else if (departmentCode.length < 1) {
        this.updatedDepartmentCodeErrorInfo = 'Department code should be minimum of 1 character.';
        this.isUpdatedDepartmentCodeValid = false;
      } else if (departmentCode.length > 15) {
        this.updatedDepartmentCodeErrorInfo = 'Department code should not exceed more than 15 characters.';
        this.isUpdatedDepartmentCodeValid = false;
      } else {
        this.isUpdatedDepartmentCodeValid = true;
        this.updatedDepartmentCodeErrorInfo = '';
      }
    
      return this.isUpdatedDepartmentCodeValid;
    }
     fetchOneDepartment(departmentId: number){
      this.departmentService.fetchDepartmentById(departmentId).subscribe({
        next: (response)=>{
          console.log(response)
          if(response.status === HttpStatusCode.Ok){
           this.existingDepartment = response.body;
          }
        },error: (error) => {
          if(error.status === HttpStatusCode.Unauthorized){
            this.router.navigateByUrl('/session-timeout')
          }
        }
      })
    }

    departmentToDelete:any
    deletedepartmentById(departmentId: number){
      this.departmentToDelete=departmentId;
      document.getElementById('depDelete')?.click();
      
     }
     confirmDelete(){
      this.departmentService.deleteDepartment(this.departmentToDelete).subscribe({
        next:(response) => {
         //console.log(response)
          if(response.status === HttpStatusCode.Ok){
            var result = response.body;
            this.toastr.success('Department '+this.departmentToDelete+' deleted successfully')
            setTimeout(()=>{
              window.location.reload();
            },1000)
          } else if(response.status === HttpStatusCode.Conflict){
           this.toastr.error("Department is already in usage by a user, cannot be deleted.");
         }
        },error: (error) => {
         //console.log(error)
          if(error.status === HttpStatusCode.Unauthorized){
            this.router.navigateByUrl('/session-timeout')
          }
          else if(error.status === HttpStatusCode.Conflict){
            this.toastr.error("Department is already in usage by an user, cannot be deleted.");
          }
          else{
            this.toastr.error('Error occured while deleting department ' + this.departmentToDelete  +'. Please try again !')
          }
        }
     })
     }
     searchText='';
     applyFilter() {
      const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text
    
      this.departmentDataSource.filterPredicate = (data: any, filter: string) => {
     
        const displayedColumnsValues = this.displayedDepartmentColumn.map(column => {
          if (column === 'createdDateTime' || column === 'modifiedDateTime') {
            // For date columns, format the date to 'MMM d, y, h:mm a' format
            const dateValue = data[column];
            return this.formatDate(new Date(dateValue));
          } else {
            // For non-date columns, return the column value
            return data[column];
          }
        });
    
        // Perform a case-insensitive search across the columns
        return displayedColumnsValues.some(value =>
          value?.toString().toLowerCase().includes(filter)
        );
      };
    
      // Apply the filter value to the data source
      this.departmentDataSource.filter = filterValue;
    
      // Reset paginator to the first page after filtering
      if (this.departmentDataSource.paginator) {
        this.departmentDataSource.paginator.firstPage();
      }
    }
    
    formatDate(date: Date): string {
      const options: Intl.DateTimeFormatOptions = {
        month: 'short',  // 'Jan', 'Feb', etc.
        day: 'numeric',  // '30', '1', etc.
        year: 'numeric', // '2025', '2026', etc.
        hour: 'numeric', // '3', '12', etc.
        minute: 'numeric', // '46', '30', etc.
        hour12: true, // AM/PM format
      };
    
      return date.toLocaleString('en-US', options); // Format as 'Jan 30, 2025, 3:46 PM'
    }
}
