import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { CommonFunctionService } from '../services/commonfunctions.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { NgModule } from '@angular/core';


@Component({
  selector: 'dvr-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']

})
export class CustomerComponent implements OnInit {
  public customerForm !: FormGroup;
  loginData: any = [];
  login_name: any;
  last_login_date: any;
  login_id: any;
  msg: any;
  cust_data: any = [];

  cont_name: any;
  cont_id: any;

  datalist: any = [];
  salePersonlist: any = [];
  cust_add: any;
  sp_add: any;

  checkfirstnm_flag: boolean = false;
  checklastnm_flag: boolean = false;
  checkmobilleno_flag: boolean = false;
  displayStyle = "none";
  error_msg: any;
  success_msg: boolean = false;
  status_msg: any;

  disabled_flag: boolean = false;
  contactList: any = [];
  dtOptions: any = {};
  dtTrigger: Subject<any> = new Subject();


  sucess_flag: boolean = false;
  backtodvr_flag: boolean = false;
  check_successflag: boolean = false;

  emailID_flag: boolean = true;
  role: any;

  resetflag:boolean=false;


  displayMessage: { [key: string]: string } = {};
  private validationMessage: { [key: string]: { [key: string]: string } }


  constructor(private commonservice: CommonFunctionService, private router: Router, private fb: FormBuilder) {


    this.dtOptions = {
      stateSave: true,   // 👈 ADD THIS
      stateSaveCallback: function(settings, data) {
        localStorage.setItem('customerTableState', JSON.stringify(data));
      },
      stateLoadCallback: function(settings) {
        return JSON.parse(localStorage.getItem('customerTableState'));
      },

      stateDuration: -1, // 👈 keeps forever (uses localStorage)
      // paging: true,
      pagingType: 'full_numbers',
      pageLength: 15,
      processing: true,
      order: [],
      lengthMenu: [15, 25, 35],
      ordering: true,
      dom: 'Blfrtip',
      initComplete: function(settings: any, json: any) {
  const api = new $.fn.dataTable.Api(settings);

  // Add filter row for spacing (optional)
  const tableHeader = $(settings.nTable).find('thead');
  if (!tableHeader.find('.filter-row').length) {
    tableHeader.append('<tr class="filter-row"></tr>');
  }
  const filterRow = tableHeader.find('.filter-row');

  api.columns().every(function () {
    const column = this;
    const colIndex = column.index();
    const header = $(column.header());
    const colName = header.text().trim(); // get column name text

    // --- SORT BUTTON (always added) ---
    // const sortBtn = $('<button class="sort-btn"></button>');
    const sortBtn = $('<button class="sort-btn" style="margin-left:4px;border:none;background:none;cursor:pointer;font-size:12px;"></button>');

    let sortState = 0;
    sortBtn.on('click', function () {
      // if (sortState === 0) { api.order([colIndex,'asc']).draw(); sortBtn.text('▲'); sortState = 1; }
      // else if (sortState === 1) { api.order([colIndex,'desc']).draw(); sortBtn.text('▼'); sortState = 2; }
      // else { api.order([]).draw(); sortBtn.text('⬍'); sortState = 0; }
    });
    header.append(sortBtn);

    // --- Skip filter if column is in skip list ---
    // if (skipFilterCols.includes(colIndex) || header.hasClass('no-export')) return;
    // Skip filter if column is in skipFilterCols or has 'no-export' class
    if (header.hasClass('no-export')) return;

    // --- FILTER BUTTON AND DROPDOWN ---
    const filterBtn = $('<button type="button" class="filter-btn">⬇</button>').appendTo(header);
    const dropdown = $('<div style="opacity: 1; background: white; overflow-y: auto; max-height: 400px;" class="floating-filter-dropdown"></div>').appendTo('body').hide();

    // Unique sorted values
    const uniqueValues = column.data()
      .unique()
      .toArray()
      .filter(d => d != null && d !== '')
      .map(d => d.toString())
      .sort((a,b) => a.localeCompare(b));

    // "All" checkbox
    const allCheckbox = $(`
      <div>
        <input type="checkbox" id="all_${colIndex}" value="all" checked>
        <label for="all_${colIndex}">All</label>
      </div>
    `);
    dropdown.append(allCheckbox);

    // Individual checkboxes
    uniqueValues.forEach(val => {
      const id = `filter_${colIndex}_${val.replace(/\s+/g,'_')}`;
      const checkbox = $(`
        <div>
          <input type="checkbox" id="${id}" value="${val}" checked>
          <label for="${id}">${val}</label>
        </div>
      `);
      dropdown.append(checkbox);
    });

    
    // Restore saved search
    const savedSearch = column.search();

    if (savedSearch) {
      const values = savedSearch.split('|')
        .map(v => v.replace(/^\^|\$$/g, '')); // remove ^ and $

      dropdown.find('input[type=checkbox]').not('[value="all"]').each(function () {
        const val = $(this).val()?.toString();
        $(this).prop('checked', values.includes(val));
      });

      const total = dropdown.find('input[type=checkbox]').not('[value="all"]').length;
      const checkedCount = dropdown.find('input[type=checkbox]:checked').not('[value="all"]').length;

      allCheckbox.find('input').prop('checked', checkedCount === total);
    }

    // --- Checkbox handling ---
    dropdown.on('change', 'input[type=checkbox]', function () {
      const allChecked = allCheckbox.find('input').prop('checked');

      if ($(this).val() === 'all') {
        const checked = $(this).prop('checked');
        dropdown.find('input[type=checkbox]').prop('checked', checked);
      } else {
        const total = dropdown.find('input[type=checkbox]').not('[value="all"]').length;
        const checkedCount = dropdown.find('input[type=checkbox]:checked').not('[value="all"]').length;
        allCheckbox.find('input').prop('checked', checkedCount === total);
      }

      const selectedValues: string[] = dropdown.find('input[type=checkbox]:checked').not('[value="all"]').map((i, el) => $(el).val()?.toString() || '').get();
      if (selectedValues.length === 0 || allChecked) column.search('').draw();
      else {
        // const regex = selectedValues.map(v => $.fn.dataTable.util.escapeRegex(v)).join('|');
        const regex = selectedValues.map(v => '^' + $.fn.dataTable.util.escapeRegex(v) + '$').join('|');
        column.search(regex, true, false).draw();
      }
    });

    // --- Show/hide dropdown ---
    filterBtn.on('click', function (e) {
      e.stopPropagation();
      const offset = filterBtn.offset();
      dropdown.css({
        top: offset.top + filterBtn.outerHeight() + 2,
        left: offset.left,
        position: 'absolute',
        zIndex: 1000
      }).toggle();
    });

// Prevent clicks inside the dropdown from closing it
dropdown.on('click', function (e) {
  e.stopPropagation(); // stops the document click from firing
});

// Only hide dropdown when clicking outside
$(document).on('click', function () {
  dropdown.hide();
});
  });
},
      buttons: [
        {
          extend: 'print',
          title: 'Customer Details Reports'
        },
        {
          extend: 'excelHtml5',
          title: 'Customer Details Reports'
        }

      ]

    }


  }

  ngOnInit() {

    this.contactList = [];
    this.customerForm = new FormGroup({
      customer_name: new FormControl('', Validators.required),
      sales_person: new FormControl('', Validators.required),
      status: new FormControl('', Validators.required)
    })


    this.loginData.push(JSON.parse(localStorage.getItem("loginData")));
    console.log("", this.loginData[0]["user_name"]);
    this.login_name = this.loginData[0]["user_name"];
    this.last_login_date = this.loginData[0]["last_loginDate"];
    this.login_id = this.loginData[0]["user_id"];
    this.role = this.loginData[0]["role"];

    this.commonservice.getAllData(this.commonservice.projectpath + "/getselectionData").subscribe(response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        this.cust_data = response.data[0].customerData;
        // console.log(this.cust_data);
        this.dtTrigger.next(this.dtOptions);
        console.log("yyyyyyyyyyyyyy");

      }
    });

    this.commonservice.getAllData(this.commonservice.projectpath + "/getsalepersonlist").subscribe(response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])

      }
      else {

        console.log("response of sale person list", response);
        console.log("response========================>", response.data[0]);

        this.salePersonlist.push(response.data[0].salePerson);

        for (var i = 0; i < this.salePersonlist.length; i++) {
          this.datalist.push(this.salePersonlist[i])
        }

        console.log("salePersonlist---------->", this.salePersonlist)
        console.log("this.salePersonlist", this.datalist);
      }
    });
  }

  customerData(form: FormGroup) {

    const customerData = {
      customer_id: "",
      customer_name: form.value.customer_name,
      sale_person: form.value.sales_person,
      status: form.value.status,
      created_by: this.login_id,
      action: 'insert'
    }

    console.log("customerData", customerData);

    this.commonservice.getData(this.commonservice.projectpath + "/createUpdateCustomerentry", customerData).subscribe(response => {

      console.log("response", response);

      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        console.log("response", response);
        // this.msg = response["message"];
        if (response.status == false) {
          //error occured
          this.openPopup();
          this.status_msg = "Warning";
          this.error_msg = response.error;
        } else {
          //succeessful response
          if (response.data[0].createcustomerStatus == 0) {
            this.openPopup();
            this.sucess_flag = true;
            this.status_msg = "Success";
            this.error_msg = response.data[0].message;
            this.checkfirstnm_flag = true;
            this.customerForm = new FormGroup({
              customer_name: new FormControl('', Validators.required),
              sales_person: new FormControl('', Validators.required),
              status: new FormControl('', Validators.required)
            });

          } else {
            this.openPopup();
            this.status_msg = "Warning";
            this.error_msg = response.data[0].message;
          }
        }



        // console.log("inside if")
        //     this.openPopup();
        //     this.status_msg = "Warning";
        //     this.error_msg = response.error;
        //   } else if (response.data.length > 0) {

        //     this.openPopup();
        //     this.sucess_flag = true;
        //     this.status_msg = "Success";
        //     this.error_msg = response.data[0].message;
        //     this.checkfirstnm_flag = true;

        //     console.log("response.data.message", response.data[0].message);
        //     if (response.data[0].exception.errorid != '') {
        //       this.openPopup();
        //       this.status_msg = "Warning";
        //       this.error_msg = response.error;
        //     }
        //   }
        //   else {
        //     this.status_msg = "";
        //     this.error_msg = "";
        //   }
        // } else {
        //   if (response.data.length == 0) {

        //     //console.log("inside if")
        //     this.openPopup();
        //     this.status_msg = "Warning";
        //     this.error_msg = response.error;
        //   }
        //   else if (response.data.length > 0) {
        //     //console.log("inside if(response.message== '')222222222222 ")
        //     this.openPopup();
        //     this.status_msg = "Success";
        //     this.error_msg = response.data[0].message;
        //     this.checkfirstnm_flag = true;

        //     this.customerForm = new FormGroup({
        //       customer_name: new FormControl('', Validators.required),
        //       sales_person: new FormControl('', Validators.required)
        //     });


        //     if (response.data[0].exception.errorid != '') {
        //       this.openPopup();
        //       this.status_msg = "Warning";
        //       this.error_msg = response.error;
        //     }
        //   }
        //   else {
        //     this.status_msg = "";
        //     this.error_msg = "";

      }
    });


  }


  resetForm() {
    this.msg = "";
  }


  onBack() {
    console.log("back dvr page");
    this.router.navigate(['/dvrentry'])
  }

  clearForm() {
    // this.form.reset();
  }
  isFieldValid(field: string) {
    // console.log("in field", field)
    return !this.customerForm.get(field).valid && this.customerForm.get(field).touched;
  }
  displayFieldCss(field: string) {
    return {
      'has-error': this.isFieldValid(field),
      'has-feedback': this.isFieldValid(field)
    };

  }

  onEditButtonClick() {
    if (this.isEditMode) {
        this.editCustomerLogic();
    }
  }

  onAddButtonClick() {
    if (this.isAddMode) {
      console.log("Adding");
      this.showAddBox = true;

        // this.addCustomerMappingLogic();
    }
  }

closeAddPanel() {
  this.showAddBox = false;
}

addTask(customerId: string, userId: string) {

  if (!customerId || !userId) {
    alert('Please select both Customer and User');
    return;
  }

  const payload = {
    customer_id: customerId,
    user_id: userId,
    created_by: this.login_id
  };

  console.log('Mapping Payload:', payload);
  this.commonservice.getData(this.commonservice.projectpath + "/addCustomerUserMapping", payload).subscribe(response => {

      console.log("response", response);

      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        console.log("response", response);
        // this.msg = response["message"];
        if (response.status == false) {
          //error occured
          this.status_msg = "Warning";
          this.error_msg = response.data[0].message;
          this.openPopup();
        } else {
          //succeessful response
          if (response.data?.[0]?.addCustomerMappingStatus === '0') {
            this.sucess_flag = true;
            this.status_msg = "Success";
            this.error_msg = response.data[0].message;
            this.openPopup();
            this.checkfirstnm_flag = true;
            this.closeAddPanel();

          } else {
            this.status_msg = "Warning";
            this.error_msg = response.data[0].message || response.error;
            this.openPopup();
          }
        }
      }
    });
}

  editCustomerLogic() {
    console.log("Editing");
    console.log(this.customerForm.value);
    console.log(this.old_sales_person_id);
    const customerData = {
      customer_id: this.selectedCustomerId,
      customer_name: this.customerForm.value.customer_name,
      sale_person: this.customerForm.value.sales_person,
      status: this.customerForm.value.status,
      updated_by: this.login_id,
      old_sale_person: this.old_sales_person_id
    }
    console.log(customerData);
    this.commonservice.updateData(this.commonservice.projectpath + "/updateCustomerDetails", customerData).subscribe(response => {

      console.log("response", response);

      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        console.log("response", response);
        // this.msg = response["message"];
        if (response.status == false) {
          //error occured
          this.openPopup();
          this.status_msg = "Warning";
          this.error_msg = response.error || response.mesasge;
        } else {
          //succeessful response
          if (response.updateCustomerStatus == 0) {
            this.openPopup();
            this.sucess_flag = true;
            this.status_msg = "Success";
            this.error_msg = response.mesasge;
            this.checkfirstnm_flag = true;
            this.customerForm = new FormGroup({
              customer_name: new FormControl('', Validators.required),
              sales_person: new FormControl('', Validators.required),
              status: new FormControl('', Validators.required)
            });

          } else {
            this.openPopup();
            this.status_msg = "Warning";
            this.error_msg = response.mesasge;
          }
        }
      }
    });

  }

  selectedCustomerId: any;
  isEditMode: boolean = false;
  isAddMode: boolean = true;
  showAddBox: boolean = false;
  old_sales_person_id: any;

  editCustomer(current: any) {
    console.log(current);
    this.isEditMode = true;
    this.selectedCustomerId = current.customer_id;
    console.log(this.selectedCustomerId);

    this.customerForm.patchValue({
        customer_id: current.customer_id,
        customer_name: current.customer_name,
        status: current.customer_status,
        sales_person: current.first_name + " " + current.last_name || current.first_name
    });

    this.old_sales_person_id = current.user_id;

    window.scrollTo({ top: 0, behavior: 'smooth' });

    // NEED TO ADD EDIT BUTTON ON UI BESIDES SAVE, DROPDOWN FOR STATUS, 
      // QUERY TO FETCH USER AS WELL SO CAN UPDATE THAT, ETC
  }

  deleteCustomer(i: any) {
    console.log("Deleting" + i)
  }

  openPopup() {
    this.displayStyle = "block";
  }

  closePopup() {
    this.displayStyle = "none";
    if (this.backtodvr_flag == true) {
      //  alert("in else ");
      this.router.navigate(['/dvrentry'])
    } else {
      if (this.checkfirstnm_flag == true) {
        window.location.reload();
      }

    }
  }






  modo(value: any) {
    console.log("data---->", value);
    console.log("customer_id", value.customer_id);

    var id;
    if (value.customer_id != undefined) {
      console.log("specific customer contact");
      id = parseInt(value.customer_id);
      console.log("parseInt", typeof (id));

    } else {
      console.log("in all customer data");
      id = value;
    }



    this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=" + id + "&passid=number").subscribe(response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {

        // this.dtTrigger.next(this.dtOptions)

        //console.log("check length",response.data[0]);
        if (response.data[0].getdvrDataStatus == '1') {
          //data not found
          this.contactList = [];
          console.log("in dataa not found");
          $(document).ready(function () {
            $('.odd').show();

          });


        } else {
          console.log("in data");
          this.contactList = response.data[0].conrtactData;
          // document.getElementById("myH1").style.display = "none";

          $(document).ready(function () {
            $('.odd').hide()
          });




        }

        // this.dtTrigger.next(this.dtOptions)
        console.log("aaaaaaaaaaa", this.contactList);
      }
    });
  }


  getContactName(first_name: any, last_name: any) {
    console.log("in contact details", first_name, last_name);
    localStorage.setItem('contactlastinsert', first_name + ' ' + last_name);
    //this.router.navigate(['/dvrentry']);
  }

  reset(){
    this.resetflag=true;
    this.isEditMode = false;
    this.isAddMode = true;
    this.customerForm.reset();
  }
}

