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';

@Component({
    selector: 'app-rgtr-domain',
    templateUrl: './rgtr-domain.component.html',
    styleUrls: ['./rgtr-domain.component.css'],
    standalone: false
})
export class RgtrDomainComponent {

  displayedColumns: string[] = [
    // 'checkbox',
    'domainId',
    'organisationId',
    'domainName',
    'organizationName',
    'numberOfYears',
    'registrationDate',
   // 'renewalDate',
    'alignedRenewalDate',
  'renewalStatus',
  //'paymentStatus'
   // 'status',
   // 'deleteAction',
    // 'markAsDelete',
   // 'restoreApprove'
  ]; // 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
  ) {
    this.domainsDataSource = new MatTableDataSource<any>();
  }

  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();
        }
      }
    );
  }
  isLoadingData:boolean=false;
//   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();
//         }
//       }
//     );
//   }

async getAllDomainsListByOrgId(orgId: number) {

  this.isLoadingData = true;

  console.log('Org Id Request:', orgId);

  this.loadPaginationState();

  await lastValueFrom(
    this.domainService.getAllDomainsByOrgId(orgId)
  ).then(

    (response) => {

      console.log('Full API Response:', response);

      if (response.status === HttpStatusCode.Ok) {

        console.log('Response Body:', response.body);

        this.domainsList = response.body;

        console.log('Domains List:', this.domainsList);

        this.domainsDataSource.data = this.domainsList;

        console.log('Datasource Data:', this.domainsDataSource.data);

        this.maxDataCount = this.domainsDataSource.data.length;

        console.log('Total Count:', this.maxDataCount);

        setTimeout(() => {

          // Set paginator state BEFORE assigning
          this.paginator.pageIndex = this.pageIndex;
          this.paginator.pageSize = this.pageSize;

          console.log('Paginator Page Index:', this.pageIndex);
          console.log('Paginator Page Size:', 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) => {

            console.log('Paginator Event:', event);

            this.handlePageEvent(event);

          });

        });

        setTimeout(() => {

          this.domainsDataSource.sort = this.sort;

          console.log('Sort Object:', this.sort);

          this.sort.sortChange.subscribe(() => {

            console.log('Sort Changed');

            this.savePaginationState();

          });

        });

        this.isLoadingData = false;

        console.log('Loading Completed');

      }

    },

    (error) => {

      console.log('API Error:', 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();
}


canDelete(domain: any): boolean {
  if (!domain.alignedRenewalDate) return false;

  const now = new Date();
  const expiry = new Date(domain.alignedRenewlDate);

  const graceEnd = new Date(expiry);
  graceEnd.setDate(graceEnd.getDate() + 45);

  return (
    domain.status?.toLowerCase() === 'active' &&
    now > graceEnd
  );
}


deleteDomain(domain: any) {

  if (!confirm('Are you sure you want to delete this domain?')) return;

  this.domainService.deleteDomainInNixi(domain.domainId).subscribe(() => {
    this.toastr.success('Domain deleted successfully');

    this.getAllDomainsListByOrgId(0);
  });
}

approveRestore(domain: any) {
  this.domainService.approveRestore(domain.domainId).subscribe(() => {
    this.toastr.success('Restore approved');

    this.getAllDomainsListByOrgId(0);
  });
}


getRenewalStatus(domain: any): string {

  // ✅ FIRST PRIORITY: backend status
  if (domain.status?.toLowerCase() === 'inactive') {
    return 'Inactive';
  }

  const expiryDate = domain.alignedRenewalDate;

  if (!expiryDate) return 'Active';

  const today = new Date();
  const aligned = new Date(expiryDate);

  const diffDays = Math.floor(
    (aligned.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)
  );

  if (diffDays > 60) {
    return 'Active';
  }

  if (diffDays > 0 && diffDays <= 60) {
    return 'Renewal Due';
  }

  if (diffDays <= 0 && diffDays >= -45) {
    return 'Renew Grace Period';
  }

  return 'RGP';
}

}
