import { Component, ViewChild } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSort, SortDirection } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DomainService } from '../rgnt-domain/service/domain.service';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { HttpStatusCode } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { NameServerService } from '../name-server-form/service/name-server.service';

@Component({
    selector: 'app-rgtr-modify-request-reports',
    templateUrl: './rgtr-modify-request-reports.component.html',
    styleUrls: ['./rgtr-modify-request-reports.component.css'],
    standalone: false
})
export class RgtrModifyRequestReportsComponent {

  displayedColumns: string[] = [
    // 'checkbox',
    'domainId',
    'domainName',
    'organizationName',
    'numberOfYears',
    'registrationDate',
    'renewalDate',
    'status',
    //'markAsDelete',
  ]; // Matches matColumnDef values

  domainsList: any[] = [];
  domainsDataSource: MatTableDataSource<any>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  role: string = localStorage.getItem('userRole');
  userEmailId = localStorage.getItem('email');
  searchText:String='';
  maxDataCount:number=0;


  constructor(private domainService: DomainService, private router: Router,
    private toastr: ToastrService,
     private nameServerService: NameServerService,
  ) {
    this.domainsDataSource = new MatTableDataSource<any>();
  }

  // constructor(private domainService: DomainService, 
  //     private router: Router, private activatedRouter: ActivatedRoute,
  //     private nameServerService: NameServerService,private toastr:ToastrService,
  //      private domainInvoiceService: DomainInvoiceService,private http: HttpClient,
  //      private organisationService: OrganisationDetailsService,
  //      private domainApplicationService: DomainApplicationService,
  //      private registrationService :RegistrationService,
  //      private dnsSecService: DnsSecService,
  //      private assetService:AssetService
  //   ){
  
  //   }

  ngOnInit(): void {


    localStorage.setItem('isBoxVisible', 'false');

  
    //console.log(this.role)
    //console.log(this.userEmailId)
    // if(this.role !== 'IDRBTADMIN'){
    //   //console.log('exe')
    //   this.getAllDomainsList(this.userEmailId);
    // }else{
    //   //console.log('exe 1')
      this.getAllDomainsListByOrgId(0);
    //}
  }
  
  async getAllDomainsList(userId: string) {
    await lastValueFrom(this.domainService.getAllDomains(userId)).then(
      (response) => {
        if (response.status === HttpStatusCode.Ok) {
          this.domainsList = response.body;
          //console.log(this.domainsList)
          this.domainsDataSource.data = this.domainsList;
          setTimeout(() => {
            this.domainsDataSource.sort = this.sort;
            this.domainsDataSource.paginator = this.paginator;
          }, 0);
        }
      },
      (error) => {
        if (error.status === HttpStatusCode.Unauthorized) {
          this.navigateToSessionTimeout();
        }
      }
    );
  }
  async hasEditedNameServer(domainId: number): Promise<boolean> {
  try {
    const response = await lastValueFrom(
      this.nameServerService.getModifyNameServersByDomainId(domainId)
    );

    if (response.status === HttpStatusCode.Ok && response.body) {
      return response.body.some(ns => ns.isEdited === true);
    }

    return false;
  } catch (error) {
    if (error.status === HttpStatusCode.Unauthorized) {
      this.router.navigateByUrl('/session-timeout');
    }
    return false;
  }
}

  isLoadingData:boolean=false;
  async getAllDomainsListByOrgId(orgId: number) {
  this.isLoadingData = true;
  this.loadPaginationState();

  await lastValueFrom(this.domainService.getAllDomainsByOrgId(orgId)).then(
    async (response) => {
      if (response.status === HttpStatusCode.Ok) {

        // ORIGINAL
        this.domainsList = response.body;

        // 🔹 🔹 🔹 ADDITION STARTS HERE 🔹 🔹 🔹
        const filteredDomains = [];

        for (const domain of this.domainsList) {
          const hasEdited = await this.hasEditedNameServer(domain.domainId);
          if (hasEdited) {
            filteredDomains.push(domain);
          }
        }

        this.domainsList = filteredDomains;
        // 🔹 🔹 🔹 ADDITION ENDS HERE 🔹 🔹 🔹

        // ORIGINAL (unchanged)
        this.domainsDataSource.data = this.domainsList;
        this.maxDataCount = this.domainsDataSource.data.length;

        setTimeout(() => {
          this.paginator.pageIndex = this.pageIndex;
          this.paginator.pageSize = this.pageSize;
          this.domainsDataSource.paginator = this.paginator;
          this.paginator._changePageSize(this.pageSize);

          this.paginator.page.subscribe((event: PageEvent) => {
            this.handlePageEvent(event);
          });
        });

        setTimeout(() => {
          this.domainsDataSource.sort = this.sort;
          this.sort.sortChange.subscribe(() => {
            this.savePaginationState();
          });
        });

        this.isLoadingData = false;
      }
    },
    (error) => {
      if (error.status === HttpStatusCode.Unauthorized) {
        this.navigateToSessionTimeout();
      }
    }
  );
}

//   async getAllDomainsListByOrgId(orgId: number) {
//     this.isLoadingData=true;
//     this.loadPaginationState();
//     await lastValueFrom(this.domainService.getAllDomainsByOrgId(orgId)).then(
//       (response) => {
//         if (response.status === HttpStatusCode.Ok) {
//           this.domainsList = response.body;
//           //console.log(this.domainsList)
//           this.domainsDataSource.data = this.domainsList;
//           this.maxDataCount=this.domainsDataSource.data.length
//            setTimeout(() => {
//         // Set paginator state BEFORE assigning
//         this.paginator.pageIndex = this.pageIndex;
//         this.paginator.pageSize = this.pageSize;

//         // Assign paginator and sort
//         this.domainsDataSource.paginator = this.paginator;
       

//         // Force MatPaginator to render correct page
//         this.paginator._changePageSize(this.pageSize);

//         // Subscribe to future page changes
//         this.paginator.page.subscribe((event: PageEvent) => {
//           this.handlePageEvent(event);
//         });

        
//         //  this.domainsDataSource.sort = this.sort;
     
//       });
//       setTimeout(() => {
//          this.domainsDataSource.sort=this.sort;
//           this.sort.sortChange.subscribe(() => {
//   this.savePaginationState();
// });
//       });
//           this.isLoadingData=false;
//         }
//       },
//       (error) => {
//         if (error.status === HttpStatusCode.Unauthorized) {
//           this.navigateToSessionTimeout();
//         }
//       }
//     );
//   }

  navigateToDomainDetails(domainId: number){
    this.router.navigate(['/domain-details'],{queryParams:{domainId:domainId}});
  }

  navigateToSessionTimeout() {
    this.router.navigateByUrl('/session-timeout');
  }

  navigateToAddDomain(){
    this.router.navigateByUrl('/add-domain');
  }
  applyFilter() {
    const filterValue = (event.target as HTMLInputElement).value.trim().toLowerCase(); // Get the filter text
  
    this.domainsDataSource.filterPredicate = (data: any, filter: string) => {
   
      const displayedColumnsValues = this.displayedColumns.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];
          //console.log(dateValue)
          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.domainsDataSource.filter = filterValue;
  
    // Reset paginator to the first page after filtering
    if (this.domainsDataSource.paginator) {
      this.domainsDataSource.paginator.firstPage();
    }
  }
  formatDate(date: Date): string {
    const options: Intl.DateTimeFormatOptions = {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      hour12: true,
    };
    return date.toLocaleDateString('en-US', options);
 
  }
getFilteredDomains(): void {
  const filters = JSON.parse(localStorage.getItem('filters') || '{}'); // Retrieve filters from localStorage

  // Make sure that if the filters are empty, it handles properly
  if (!filters.organisationName && !filters.nsRecordStatus && !filters.status) {
    // If there are no filters applied, fetch all data (you might want to have a fallback here)
    this.getAllDomainsList(this.userEmailId);
    return;
  }

  this.domainService.getFilteredData(filters).subscribe(
    (response) => {
      // Check if the response has data
      if (response.body && response.body.length > 0) {
        this.domainsList = response.body;
        this.domainsDataSource.data = this.domainsList;
        this.domainsDataSource.paginator = this.paginator;
        this.domainsDataSource.sort = this.sort;
        this.noDataFound = false; // Hide "No results" message if data is found
      } else {
        // If no data is found, clear the table and show "No results" message
        this.domainsList = []; // Ensure the data list is empty
        this.domainsDataSource.data = this.domainsList; // Set the data source to empty
        this.noDataFound = true; // Set the flag to true to show "No results" message
      }
    },
    (error) => {
      //console.error('Error fetching filtered domains:', error);
      this.noDataFound = true; // In case of error, show "No results" message
    }
  );
}


filters = {
  userId: '',
  domainName:'',
  organisationName: '',
  nsRecordStatus: '',
  status: '',
  submissionDate:''
};

resetFilters(): void {
  this.filters = {
    userId: '',
    domainName:'',
    organisationName: '',
    nsRecordStatus: '',
    status: '',
    submissionDate:''
  };
 this.getFilteredDomains();
}

filterButton() {
  // Assuming you have a filter object with values (e.g., from input fields)
  const filters = {
    organisationName: this.filters.organisationName, // The value entered by the user
    nsRecordStatus: this.filters.nsRecordStatus,    // The value entered by the user
    status: this.filters.status,                     // The value entered by the user
  };

  // Store the filters in localStorage as a JSON string
  localStorage.setItem('filters', JSON.stringify(filters));

  // Clear the noDataFound flag and fetch filtered data
  this.noDataFound = false;
  this.getFilteredDomains(); // Fetch the filtered data
}

  noDataFound: boolean = false;

  clearButton(){
   
      localStorage.removeItem('filters');
      
      this.filters.organisationName= '';
      this.filters.nsRecordStatus = '';
      this.filters.status = '';
      this.filters.domainName='';
     
      this.getFilteredDomains();
    }

    markDomainAsDeleted(markAsDelete: any, domain: any) {
      console.log(markAsDelete.target.checked);
      var confirm = window.confirm('Are you sure you want to mark this domain as deleted?');
      if(confirm){
        domain.markAsDelete = markAsDelete.target.checked;
        this.domainService.updateDomainDetails(domain).subscribe(
          (response) => {
            if (response.status === HttpStatusCode.Ok) {
              //console.log('Domain marked as deleted successfully');
              this.getAllDomainsListByOrgId(0);
            }
          },
          (error) => {
            if (error.status === HttpStatusCode.Unauthorized) {
              this.navigateToSessionTimeout();
            }
          }
        );
      }else{
        this.toastr.error('Domain not marked as deleted');
      }
     

    }

    pageIndex = 0;
pageSize = 10;
private loadPaginationState(): void {
  const savedPageIndex = localStorage.getItem('domainsPageIndex');
  const savedPageSize = localStorage.getItem('domainsPageSize');
  const savedSortActive = localStorage.getItem('domainsSortActive');
  const savedSortDirection = localStorage.getItem('domainsSortDirection') as SortDirection;

  this.pageIndex = savedPageIndex ? +savedPageIndex : 0;
  this.pageSize = savedPageSize ? +savedPageSize : 10;

  setTimeout(() => {
    if (this.sort) {
      if (savedSortActive && savedSortDirection) {
        this.sort.active = savedSortActive;
        this.sort.direction = savedSortDirection;
      } else {
        // Default sort
        this.sort.active = 'domainId';
        this.sort.direction = 'desc';
      }

      this.sort.sortChange.emit({
        active: this.sort.active,
        direction: this.sort.direction,
      });
    }
  });
}

private savePaginationState(): void {
  localStorage.setItem('domainsPageIndex', this.pageIndex.toString());
  localStorage.setItem('domainsPageSize', this.pageSize.toString());

  if (this.sort) {
    localStorage.setItem('domainsSortActive', this.sort.active);
    localStorage.setItem('domainsSortDirection', this.sort.direction);
  }
}

handlePageEvent(event: PageEvent): void {
  this.pageIndex = event.pageIndex;
  this.pageSize = event.pageSize;
  this.savePaginationState();
}

}
