import { Component, OnInit, ViewChild } from '@angular/core';
import { RegistrarDashboardServiceService } from './service/registrar-dashboard-service.service';
import { Chart, BarController, BarElement, LineController, LineElement, PointElement, CategoryScale, LinearScale, Tooltip, Legend } from 'chart.js';
import { error } from 'jquery';
import { OrganisationDetailsService } from '../organisation-details/service/organisation-details.service';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { lastValueFrom } from 'rxjs';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { HttpStatusCode } from '@angular/common/http';
import { Router } from '@angular/router';
import { UserService } from '../user/service/user.service';



// Register required components
Chart.register(BarController,LineController,PointElement, LineElement,BarElement, CategoryScale, LinearScale, Tooltip, Legend);

const Week = 'week';
const Month = 'month';
const Year = 'year';
@Component({
    selector: 'app-registrars-dashboard',
    templateUrl: './registrars-dashboard.component.html',
    styleUrls: ['./registrars-dashboard.component.css'],
    standalone: false
})
export class RegistrarsDashboardComponent implements OnInit {
  
  organisationStatusMap = new Map<number, string>();
  periodFiltersApplication:string=Month
  periodFilterForApplicationStatus:string=Month
  applicationStatusChart:any;
  applicationChart:any;
  applicationYearLabel:any[]=[];
  TotalDomainForWeek:any[]=[]
  TotalDomainForMonth:any[]=[]
  TotalDomainForYear:any[]=[]
  TotalApplicationStatusForYear:any[]=[];
  TotalApplicationStatusForMonth:any[]=[];
  TotalApplicationStatusForWeek:any[]=[];
  entitiesList: any[] = [];
  totalRegistrants:number=0
  totalDomains:number=0
  applicationInQueue:number=0
  revenueCollected:number=0
  
displayedApplicationInQueue: string[] = [
  'organisationDetailsId',
  //'domainName',
  'institutionName',
  'submissionDate',
  //'renewalDate',
  'organisationApplicationStatus',
];

  applicationQueData: any[] = [];
  applicationInQueueDataSourse: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;


  constructor(private registrarDashboardService:RegistrarDashboardServiceService,
    private organisationService:OrganisationDetailsService,
    private domainService:DomainService,
    private orgService: OrganisationDetailsService,
    private router:Router,private userService:UserService){
    this.applicationInQueueDataSourse = new MatTableDataSource<any>();
  }
  isLoadingData:boolean=false;
  ngOnInit(): void {
   
    this.fetchDataForTopCards();
    this.fetchDataForDomainRegistration('email');
    this.fetchDataForApplicationStatus();
    this.fetchDataForApplicationInQueue("");
    // this.fetchOrganizationDetails();
  }

  async fetchDataForTopCards(){
    await this.getAllOrg();
    await this.getDomainDetails();
    await this.getAllActiveUsers();
  }
  async getAllOrg(){
    this.organisationService.getAllOrganisations().subscribe({
      next: response=>{
        ////console.log(response)
        this.totalRegistrants=response.body.length;
      },error:error=>{
        if(error.status==HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    })
    // this.domainService.getAllDomainsByOrgId(0).subscribe({
    //   next:(response)=>{
    //     this.totalRegistrants=response.body.length;
    //   },error:(error)=>{
    //     if(error.status==HttpStatusCode.Unauthorized){
    //       this.navigateToSessionTimeout();
    //     }
    //   }
    // })
  }
  allActiveUsersCount:number=0
 async getAllActiveUsers(){
    this.userService.getAllActiveUsers().subscribe({
      next: response=>{
        // ////console.log(response)
        this.allActiveUsersCount=response.body;
      },error:error=>{
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    })
  }
 async getDomainDetails(){
    this.registrarDashboardService.getDomainCount().subscribe({
      next:response=>{
        ////console.log(response)
        this.totalDomains=response.body[0];
        this.applicationInQueue=response.body[1];
      },error:error=>{
        if(error.status === HttpStatusCode.Unauthorized){
          this.navigateToSessionTimeout();
        }
      }
    })
  }
  fetchDataForDomainRegistration(emailIds) {
    if(this.applicationChart!=null){
      this.applicationChart.destroy();
    }
    
    if (this.periodFiltersApplication === Week) {
      const currentDate = new Date();
      const startDate = new Date(currentDate);
      startDate.setHours(0, 0, 0, 0);
      
      // Set the start date to the beginning of the current week (Sunday)
      startDate.setDate(currentDate.getDate() - currentDate.getDay());
      
      const endDate = new Date(startDate);
      // Set the end date to the end of the current week (Saturday)
      endDate.setDate(startDate.getDate() + 6);
      endDate.setHours(23, 59, 59, 999);
      
      ////console.log('Start Date:', startDate.toISOString());
      ////console.log('End Date:', endDate.toISOString());
      this.registrarDashboardService.fetchDomainStatusforWeek(startDate.toISOString(), endDate.toISOString()).subscribe({
        next: response => {
          this.TotalDomainForWeek = response.body;
          ////console.log(this.TotalDomainForWeek)
          this.createDomainTrendChart();

        }
      })
    } else if (this.periodFiltersApplication === Month) {
      if (this.applicationChart != null) {
        this.applicationChart.destroy();
      }
      const startDate = new Date();
      const endDate = new Date();

      startDate.setFullYear(new Date().getFullYear(), 0, 1);
      endDate.setFullYear(new Date().getFullYear(), 11, 31);
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
      this.registrarDashboardService.fetchDomainStatusforMonth(startDate.toISOString(), endDate.toISOString()).subscribe({
        next: response => {
          this.TotalDomainForMonth = response.body;
          this.createDomainTrendChart();
        }
      })


    }
    else if (this.periodFiltersApplication === Year) {
      if (this.applicationChart != null) {
        this.applicationChart.destroy();
      }
      this.applicationYearLabel=[]
      const currentYear = new Date().getFullYear();
      const baseYear = currentYear - 4;
      const startDate = new Date(baseYear, 0, 1);
      const endDate = new Date(currentYear + 1, 11, 31);
      
      // Set times to 00:00:00 for start and 23:59:59.999 for end (optional)
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
      ////console.log(startDate+"  "+endDate)

      // Iterate from base year to current year and add to array
      for (let year = baseYear; year <= currentYear+1; year++) {
        this.applicationYearLabel.push(year);
      }
      this.registrarDashboardService.fetchDomainStatusforYear(startDate.toISOString(), endDate.toISOString()).subscribe({
        next: response => {
          this.TotalDomainForYear = response.body;
          this.createDomainTrendChart();
        }
      })


    }


  }
  fetchDataForApplicationStatus(){
    if(this.applicationStatusChart!=null){
      this.applicationStatusChart.destroy();
    }
    if (this.periodFilterForApplicationStatus === Week) {
      const currentDate = new Date();
      const startDate = new Date(currentDate);
      startDate.setHours(0, 0, 0, 0);
      
      // Set the start date to the beginning of the current week (Sunday)
      startDate.setDate(currentDate.getDate() - currentDate.getDay());
      
      const endDate = new Date(startDate);
      // Set the end date to the end of the current week (Saturday)
      endDate.setDate(startDate.getDate() + 6);
      endDate.setHours(23, 59, 59, 999);
      
      //console.log('Start Date:', startDate.toISOString());
      //console.log('End Date:', endDate.toISOString());
      this.registrarDashboardService.fetchApplicationStatusforWeek(startDate.toISOString(), endDate.toISOString()).subscribe({
        next: response => {
          this.TotalApplicationStatusForWeek = response.body;
          //console.log(this.TotalApplicationStatusForWeek)
          this.createApplicationStatusChart();

        }
      })
    } else if (this.periodFilterForApplicationStatus === Month) {
      if (this.applicationStatusChart != null) {
        this.applicationStatusChart.destroy();
      }
      const startDate = new Date();
      const endDate = new Date();

      startDate.setFullYear(new Date().getFullYear(), 0, 1);
      endDate.setFullYear(new Date().getFullYear(), 11, 31);
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
      this.registrarDashboardService.fetchApplicationStatusforMonth(startDate.toISOString(), endDate.toISOString()).subscribe({
        next: response => {
          this.TotalApplicationStatusForMonth = response.body;
          //console.log(this.TotalApplicationStatusForMonth)
          this.createApplicationStatusChart();
        }
      })


    }
    else if (this.periodFilterForApplicationStatus === Year) {
      if (this.applicationStatusChart != null) {
        this.applicationStatusChart.destroy();
      }
      this.applicationYearLabel=[]
      const currentYear = new Date().getFullYear();
      const baseYear = currentYear - 4;
      const startDate = new Date(baseYear, 0, 1);
      const endDate = new Date(currentYear + 1, 11, 31);
      
      // Set times to 00:00:00 for start and 23:59:59.999 for end (optional)
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
      //console.log(startDate+"  "+endDate)

      // Iterate from base year to current year and add to array
      for (let year = baseYear; year <= currentYear+1; year++) {
        this.applicationYearLabel.push(year);
      }
      this.registrarDashboardService.fetchApplicationStatusforYear(startDate.toISOString(), endDate.toISOString()).subscribe({
        next: response => {
          this.TotalApplicationStatusForYear = response.body;
          //console.log(this.TotalApplicationStatusForYear)
          this.createApplicationStatusChart();
        }
      })


    }
  }
  createDomainTrendChart(){
    if(this.periodFiltersApplication===Week){
      this.applicationChart = new Chart("applicationChart", {
        type: 'bar',
        data: {
          labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
          datasets: [
            {
              label: ".bank.in",
              data: this.TotalDomainForWeek[1],
              // backgroundColor: dayColors,
              backgroundColor:' #9EDEF8',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
              {
    label: ".fin.in",
    data: this.TotalDomainForWeek[0],
    backgroundColor: '#F2AA86',
    barPercentage: 0.8,
    stack:'Stack 0',
    order:1
  }
          ]
        },
        options: {
          responsive: true,
          aspectRatio: 1.0,
          maintainAspectRatio:false,
          scales: {
            x: {
              display: true,
              stacked:true,
              
              grid: {
                display: false,
              },
            },
            y: {
              display: true,
              // suggestedMax:SuggestedWeekMax,
              grid: {
                display: false,
              },
              ticks: {
                stepSize: 1, // Set stepSize to 1 to display only whole numbers on the y-axis
              },
            },
          },
          plugins: {
            datalabels: {
              anchor: 'center',
              align: 'center',
              // offset: -18,
              formatter: Math.round,
              font: {
              //weight: 'bolder'
              family:'Aptos Narrow',
            },
              color:"#000",
              display: function(context) { // Filter out zeros
                const value = context.dataset.data[context.dataIndex];
                return value !== 0;
              },
            },
            legend: {
              display: true,
              position: 'bottom',
              align: 'center',
              labels: {
                usePointStyle: true,
                font: {
                  size: 12,
                },
                padding: 16,
                pointStyle: 'rectRounded',

              },
            },
          },
        }
      });
    }else  if(this.periodFiltersApplication===Month){
      this.applicationChart = new Chart("applicationChart", {
        type: 'bar',
        data: {
          xLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
          datasets: [
            // {
            //   label: ".fin.in",
            //   data:  this.TotalDomainForMonth[0],
            //   backgroundColor: '#F2AA86',
            //   // backgroundColor: dayColors,
            //   barPercentage: 0.8,
            //   stack:'Stack 0',
            //   order:1
            // },
         
               {
    label: ".fin.in",
    data: this.TotalDomainForMonth[0],
    backgroundColor:'#F2AA86',
    barPercentage: 0.8,
    stack:'Stack 0',
    order:1
  },
     {
              label: ".bank.in",
              data: this.TotalDomainForMonth[1],
              // backgroundColor: dayColors,
              backgroundColor:'#9EDEF8',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
             },
             
            // {
            //   label: "Total Domain",
            //   data: this.TotalDomainForMonth[2],
            //   // backgroundColor: dayColors,
            //   type:'line',
            //   order:0,
            //   // borderColor: "green",
            //   borderWidth:1,
            //   pointStyle:"rectRot",
            //   // pointRadius: 3,
            //   //pointHoverRadius:4,
            //   borderColor: "#156082",
            // pointBorderColor:'#156082',
            // backgroundColor: "#156082",
             
            //     datalabels: {
            //       anchor: 'center',
            //       align: 'top',
            //       // offset: -18,
            //       formatter: Math.round,
            //       font: {
            //         weight: 'bolder'
            //       },
            //       color:"#156082",
            //       display: function(context) { // Filter out zeros
            //         const value = context.dataset.data[context.dataIndex];
            //         return value !== 0;
            //       },
            //       // ... other datalabel options (optional)
            //     }
             
            // }
          ]
        },
        options: {
          responsive: true,
          aspectRatio: 1.0,
          maintainAspectRatio:false,
          scales: {
            x: {
              display: true,
              stacked:true,
              
              grid: {
                display: false,
              },
            },
            y: {
              display: true,
              // suggestedMax:SuggestedMonthMax,
              grid: {
                display: false,
              },
              ticks: {
                stepSize: 1, // Set stepSize to 1 to display only whole numbers on the y-axis
              },
            },
          },
          plugins: {
            datalabels: {
              anchor: 'center',
              align: 'center',
              // offset: -18,
              formatter: Math.round,
              font: {
              //weight: 'bolder'
              family:'Aptos Narrow',
            },
              color:"#000",
              display: function(context) { // Filter out zeros
                const value = context.dataset.data[context.dataIndex];
                return value !== 0;
              },
              // ... other datalabel options (optional)
            },
            legend: {
              display: true,
              position: 'bottom',
              align: 'center',
              labels: {
                usePointStyle: true,
                font: {
                  size: 12,
                },
                padding: 16,
                pointStyle: 'rectRounded',

              },
            },
            title: {
              text:"Action Items by Priority",
              position:"bottom",
              padding:{
                top:10
              },
              display: true,
            //  text: '   '+this.meetingChartText,
              align: 'center',
              font: {
                size: 14,
              },
            },
          },
          // elements: {
          //   // arc: {
          //   //   borderRadius: 3,
          //   //   borderWidth: 2,
          //   //   borderAlign: 'inner' // Set the border width for pie chart segments
          //   // },
          // },
        }
      });
    }else  if(this.periodFiltersApplication===Year){
      this.applicationChart = new Chart("applicationChart", {
        type: 'bar',
        data: {
          labels: this.applicationYearLabel,
          datasets: [
            // {
            //   label: ".fin.in",
            //   data:  this.TotalDomainForYear[0],
            //   backgroundColor: '#F2AA86',
            //   // backgroundColor: dayColors,
            //   barPercentage: 0.8,
            //   stack:'Stack 0',
            //   order:1
            // },
        
              {
    label: ".fin.in",
    data: this.TotalDomainForYear[0],
    backgroundColor:'#F2AA86',
    barPercentage: 0.8,
    stack:'Stack 0',
    order:1
  },
      {
              label: ".bank.in",
              data: this.TotalDomainForYear[1],
              // backgroundColor: dayColors,
              backgroundColor:'#9EDEF8',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            }
            // {
            //   label: "Total Domain",
            //   data: this.TotalDomainForYear[2],
            //   // backgroundColor: dayColors,
            //   type:'line',
            //   order:0,
            //   // borderColor: "green",
            //   borderWidth:1,
            //   pointStyle:"rectRot",
            //   // pointRadius: 3,
            //   //pointHoverRadius:4,
            //   borderColor: "#156082",
            // pointBorderColor:'#156082',
            // backgroundColor: "#156082",
             
            //     datalabels: {
            //       anchor: 'center',
            //       align: 'top',
            //       // offset: -18,
            //       formatter: Math.round,
            //       font: {
            //         weight: 'bolder'
            //       },
            //       color:"#156082",
            //       display: function(context) { // Filter out zeros
            //         const value = context.dataset.data[context.dataIndex];
            //         return value !== 0;
            //       },
            //       // ... other datalabel options (optional)
            //     }
             
            // }
          ]
        },
        options: {
          responsive: true,
          aspectRatio: 1.0,
          maintainAspectRatio:false,
          scales: {
            x: {
              display: true,
              stacked:true,
              
              grid: {
                display: false,
              },
            },
            y: {
              display: true,
              // suggestedMax:SuggestedMonthMax,
              grid: {
                display: false,
              },
              ticks: {
                stepSize: 1, // Set stepSize to 1 to display only whole numbers on the y-axis
              },
            },
          },
          plugins: {
            datalabels: {
              anchor: 'center',
              align: 'center',
              // offset: -18,
              formatter: Math.round,
              font: {
              //weight: 'bolder'
              family:'Aptos Narrow',
            },
              color:"#000",
              display: function(context) { // Filter out zeros
                const value = context.dataset.data[context.dataIndex];
                return value !== 0;
              },
              // ... other datalabel options (optional)
            },
            legend: {
              display: true,
              position: 'bottom',
              align: 'center',
              labels: {
                usePointStyle: true,
                font: {
                  size: 12,
                },
                padding: 16,
                pointStyle: 'rectRounded',

              },
            },
            title: {
              text:"Action Items by Priority",
              position:"bottom",
              padding:{
                top:10
              },
              display: true,
            //  text: '   '+this.meetingChartText,
              align: 'center',
              font: {
                size: 14,
              },
            },
          },
          // elements: {
          //   // arc: {
          //   //   borderRadius: 3,
          //   //   borderWidth: 2,
          //   //   borderAlign: 'inner' // Set the border width for pie chart segments
          //   // },
          // },
        }
      });
    }

  }
  
    

  
  createApplicationStatusChart(){
    if(this.periodFilterForApplicationStatus===Week){
      this.applicationStatusChart = new Chart("applicationStatusChart", {
        type: 'bar',
        data: {
          labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
          datasets: [
            {
              label: "Approved",
              data: this.TotalApplicationStatusForWeek[0],
              backgroundColor: ' #99FF99',
              // backgroundColor: dayColors,
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
            {
              label: "Submitted",
              data: this.TotalApplicationStatusForWeek[1],
              // backgroundColor: dayColors,
              backgroundColor:' #FF9c66',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
            //  {
            //   label: "Documents Approved",
            //   data: this.TotalApplicationStatusForWeek[2],
            //   // backgroundColor: dayColors,
            //   backgroundColor:' #9AA5FE',
            //   barPercentage: 0.8,
            //   stack:'Stack 0',
            //   order:1
            // },
            //  {
            //   label: "Documents Rejected",
            //   data: this.TotalApplicationStatusForWeek[3],
            //   // backgroundColor: dayColors,
            //   backgroundColor:' #FF9999',
            //   barPercentage: 0.8,
            //   stack:'Stack 0',
            //   order:1
            // },
             {
              label: "Incomplete",
              data: this.TotalApplicationStatusForWeek[2],
              // backgroundColor: dayColors,
              backgroundColor:' #FF6666',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            }
          ]
        },
        options: {
          responsive: true,
          aspectRatio: 1.0,
          maintainAspectRatio:false,
          scales: {
            x: {
              display: true,
              stacked:true,
              
              grid: {
                display: false,
              },
            },
            y: {
              display: true,
              // suggestedMax:SuggestedWeekMax,
              grid: {
                display: false,
              },
              ticks: {
                stepSize: 1, // Set stepSize to 1 to display only whole numbers on the y-axis
              },
            },
          },
          plugins: {
            datalabels: {
              anchor: 'center',
              align: 'center',
              // offset: -18,
              formatter: Math.round,
              font: {
              //weight: 'bolder'
              family:'Aptos Narrow',
            },
              color:"#000",
              display: function(context) { // Filter out zeros
                const value = context.dataset.data[context.dataIndex];
                return value !== 0;
              },
              // ... other datalabel options (optional)
            },
            legend: {
              display: true,
              position: 'bottom',
              align: 'center',
              labels: {
                usePointStyle: true,
                font: {
                  size: 12,
                },
                padding: 16,
                pointStyle: 'rectRounded',

              },
            },
            // title: {
            //   text:"Action Items by Priority",
            //   position:"bottom",
            //   padding:{
            //     top:10
            //   },
            //   display: true,
            //  text: '   '+this.meetingChartText,
            //   align: 'center',
            //   font: {
            //     size: 14,
            //   },
            // },
          },
          // elements: {
          //   // arc: {
          //   //   borderRadius: 3,
          //   //   borderWidth: 2,
          //   //   borderAlign: 'inner' // Set the border width for pie chart segments
          //   // },
          // },
        }
      });
    }else  if(this.periodFilterForApplicationStatus===Month){
      this.applicationStatusChart = new Chart("applicationStatusChart", {
        type: 'bar',
        data: {
          xLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
          datasets: [
             {
              label: "Approved",
              data: this.TotalApplicationStatusForMonth[0],
              backgroundColor: ' #99FF99',
              // backgroundColor: dayColors,
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
            {
              label: "Submitted",
              data: this.TotalApplicationStatusForMonth[1],
              // backgroundColor: dayColors,
              backgroundColor:' #FF9c66',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
             {
              label: "Incomplete",
              data: this.TotalApplicationStatusForMonth[2],
              // backgroundColor: dayColors,
              backgroundColor:' #FF6666',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            }
          ]
        },
        options: {
          responsive: true,
          aspectRatio: 1.0,
          maintainAspectRatio:false,
          scales: {
            x: {
              display: true,
              stacked:true,
              
              grid: {
                display: false,
              },
            },
            y: {
              display: true,
              // suggestedMax:SuggestedMonthMax,
              grid: {
                display: false,
              },
              ticks: {
                stepSize: 1, // Set stepSize to 1 to display only whole numbers on the y-axis
              },
            },
          },
          plugins: {
            datalabels: {
              anchor: 'center',
              align: 'center',
              // offset: -18,
              formatter: Math.round,
              font: {
              //weight: 'bolder'
              family:'Aptos Narrow',
            },
              color:"#000",
              display: function(context) { // Filter out zeros
                const value = context.dataset.data[context.dataIndex];
                return value !== 0;
              },
              // ... other datalabel options (optional)
            },
            legend: {
              display: true,
              position: 'bottom',
              align: 'center',
              labels: {
                usePointStyle: true,
                font: {
                  size: 12,
                },
                padding: 16,
                pointStyle: 'rectRounded',

              },
            },
            title: {
              text:"Action Items by Priority",
              position:"bottom",
              padding:{
                top:10
              },
              display: true,
            //  text: '   '+this.meetingChartText,
              align: 'center',
              font: {
                size: 14,
              },
            },
          },
          // elements: {
          //   // arc: {
          //   //   borderRadius: 3,
          //   //   borderWidth: 2,
          //   //   borderAlign: 'inner' // Set the border width for pie chart segments
          //   // },
          // },
        }
      });
    }else  if(this.periodFilterForApplicationStatus===Year){
      this.applicationStatusChart = new Chart("applicationStatusChart", {
        type: 'bar',
        data: {
          labels:this.applicationYearLabel,
          datasets: [
            {
              label: "Approved",
              data: this.TotalApplicationStatusForYear[0],
              backgroundColor: ' #99FF99',
              // backgroundColor: dayColors,
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
            {
              label: "Submitted",
              data: this.TotalApplicationStatusForYear[1],
              // backgroundColor: dayColors,
              backgroundColor:' #FF9c66',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            },
         
             {
              label: "Incomplete",
              data: this.TotalApplicationStatusForYear[2],
              // backgroundColor: dayColors,
              backgroundColor:' #FF6666',
              barPercentage: 0.8,
              stack:'Stack 0',
              order:1
            }
          ]
        },
        options: {
          responsive: true,
          aspectRatio: 1.0,
          maintainAspectRatio:false,
          scales: {
            x: {
              display: true,
              stacked:true,
              
              grid: {
                display: false,
              },
            },
            y: {
              display: true,
              // suggestedMax:SuggestedMonthMax,
              grid: {
                display: false,
              },
              ticks: {
                stepSize: 1, // Set stepSize to 1 to display only whole numbers on the y-axis
              },
            },
          },
          plugins: {
            datalabels: {
              anchor: 'center',
              align: 'center',
              // offset: -18,
              formatter: Math.round,
              font: {
              //weight: 'bolder'
              family:'Aptos Narrow',
            },
              color:"#000",
              display: function(context) { // Filter out zeros
                const value = context.dataset.data[context.dataIndex];
                return value !== 0;
              },
              // ... other datalabel options (optional)
            },
            legend: {
              display: true,
              position: 'bottom',
              align: 'center',
              labels: {
                usePointStyle: true,
                font: {
                  size: 12,
                },
                padding: 16,
                pointStyle: 'rectRounded',

              },
            },
            title: {
              text:"Action Items by Priority",
              position:"bottom",
              padding:{
                top:10
              },
              display: true,
            //  text: '   '+this.meetingChartText,
              align: 'center',
              font: {
                size: 14,
              },
            },
          },
          // elements: {
          //   // arc: {
          //   //   borderRadius: 3,
          //   //   borderWidth: 2,
          //   //   borderAlign: 'inner' // Set the border width for pie chart segments
          //   // },
          // },
        }
      });
    }

  }

    // async fetchDataForApplicationInQueue(userId){
    //  this.isLoadingData=true;
    //     await lastValueFrom(this.domainService.getAllApplicationInQueue()).then(
    //       (response) => {
    //         if (response.status === HttpStatusCode.Ok) {
    //           this.applicationQueData = response.body;
    //           //console.log(this.applicationQueData)
    //           this.applicationInQueueDataSourse.data = this.applicationQueData;
    //           setTimeout(() => {
    //             this.applicationInQueueDataSourse.sort = this.sort;
    //             this.applicationInQueueDataSourse.paginator = this.paginator;
    //           }, 0);
    //           this.isLoadingData=false;
    //         }else{
    //           this.isLoadingData=false;
    //         }
    //       },
    //       (error) => {
    //         this.isLoadingData=false;
    //         if (error.status === HttpStatusCode.Unauthorized) {
    //           this.navigateToSessionTimeout();
    //         }
    //       }
    //     );
    //   }




    

//     async fetchDataForApplicationInQueue(userId){
//   this.isLoadingData=true;

//   await lastValueFrom(this.domainService.getAllApplicationInQueue()).then(

//     (response) => {

//       if (response.status === HttpStatusCode.Ok) {

//         console.log(response.body);

//         this.applicationQueData = response.body;

//         this.applicationQueData.forEach((element) => {

//   if (element.organisationId) {

//     this.orgService
//       .getOrganisationDetailsByOrganisationId(element.organisationId)
//       .subscribe({

//         next: (res) => {

//           if (res.status === HttpStatusCode.Ok) {

//             this.organisationStatusMap.set(
//               element.organisationId,
//               res.body.organisationApplicationStatus
//             );

//           }
//         }

//       });

//   }

// });

//         this.applicationInQueueDataSourse.data =
//           this.applicationQueData;

//         setTimeout(() => {
//           this.applicationInQueueDataSourse.sort = this.sort;
//           this.applicationInQueueDataSourse.paginator =
//             this.paginator;
//         }, 0);

//         this.isLoadingData=false;

//       } else {

//         this.isLoadingData=false;
//       }
//     },

//     (error) => {

//       this.isLoadingData=false;

//       if (error.status === HttpStatusCode.Unauthorized) {
//         this.navigateToSessionTimeout();
//       }
//     }
//   );
// }

async fetchDataForApplicationInQueue(searchText: string) {

  this.isLoadingData = true;

  this.orgService.getAllOrganisations().subscribe({

    next: (response) => {

      if (response.body && response.body.length > 0) {

        this.entitiesList = response.body.filter(
          (entity: any) =>
            entity.organisationApplicationStatus === 'SUBMITTED'
        );

        this.applicationQueData = this.entitiesList;

        this.applicationInQueueDataSourse.data =
          this.applicationQueData;

        setTimeout(() => {

          this.applicationInQueueDataSourse.paginator =
            this.paginator;

          this.applicationInQueueDataSourse.sort =
            this.sort;

        }, 0);

      } else {

        this.applicationQueData = [];

        this.applicationInQueueDataSourse.data = [];

      }

      this.isLoadingData = false;

    },

    error: (error) => {

      this.isLoadingData = false;

      if (error.status === HttpStatusCode.Unauthorized) {

        this.navigateToSessionTimeout();

      }

    }

  });

}



navigateToEntityDetails(entity: any) {

  this.router.navigate(
    ['/entity-application-details'],
    {
      queryParams: {
        organisationDetailsId:
          entity.organisationDetailsId
      }
    }
  );

}

navigateToEntityApplicationDetails(domain: any) {

  this.router.navigate(
    ['/entity-application-details'],
    {
      queryParams: {
        organisationDetailsId: domain.organisationId
      }
    }
  );

}


      navigateToSessionTimeout() {
        this.router.navigateByUrl('/session-timeout');
      }
      searchText: string = '';
      applyFilter() {
        const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text
     
        this.applicationInQueueDataSourse.filterPredicate = (data: any, filter: string) => {
       
          const displayedColumnsValues = this.displayedApplicationInQueue.map(column => {
            if (column === 'registrationDate' || column === 'renewalDate') {
              // 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 if(column === 'domainName'){
              const domainName = data.domainName?.toString().toLowerCase() || "";
                    const bankName = data.bankName?.toString().toLowerCase() || "";
                    // console.log(domainName+bankName)
                    return bankName+domainName; // Combine for filtering
            } 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.applicationInQueueDataSourse.filter = filterValue;
     
        // Reset paginator to the first page after filtering
        if (this.applicationInQueueDataSourse.paginator) {
          this.applicationInQueueDataSourse.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'
      }

      async navigateToApplicationDetails(domain){
        //http://localhost:4200/#/domain-application-details?domainId=442
        this.router.navigate(['/domain-application-details'], { queryParams: { domainId: domain.domainId } });
      }

    }

