import { InputText } from "primereact/inputtext";
import { useEffect, useState, useRef } from "react";
import Image from "next/image";
import { ToastContainer, toast } from "react-toastify";
import { Modal } from "react-bootstrap";
import { Paginator } from "primereact/paginator";
import { CustomerChilddeleteid } from "@/services/profile";
import useAuthProvider from "@/useAuthProvider";

import { MultiSelect } from "primereact/multiselect";
import { Button } from "primereact/button";
import Checklist from "../../../public/images/Checklist.svg";
import viewEye from "../../../public/images/viewEye.svg";
import Prohibit from "../../../public/images/Prohibit .svg";
import "react-toastify/dist/ReactToastify.css";
import { DataTable } from "primereact/datatable";
import "primeicons/primeicons.css";
import LineGraph from "./LineGraph";
import { toCheckUserTypeSubscreption } from "@/helpers/toCheckUserType";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import Moment from "moment";
import "primereact/resources/themes/saga-blue/theme.css";
import { Column } from "primereact/column";
import { ScaleLoader } from "react-spinners";
import { useSession } from "next-auth/react";
import { getprofiletrack, toGetTableColumnData, toResetTableHeaderColumns } from "@/services/public";
import { useRouter } from "next/router";
import "primereact/resources/primereact.css";
import "rsuite/dist/rsuite.min.css";
import DashboardGraphCarrier from "./DashboardGraphCarrier";
import SubscriptionPlansModal from "../modal/SubscriptionPlansModal";
import styles from "@/styles/MultiSelect.module.css";
import PaginationTitle from "../pages/PaginationTitle";
import { toUpdateTableColumn } from "@/helpers/toUpdateTableColumn";

interface Props {
  datalisting: any;
  breadcrumbs: {
    title: string;
    path: string;
  }[];
}
const isLoadingModScope = (
  <div id='loader_table'>
    <ScaleLoader color='#3180f3' className='table_loader' />
  </div>
);
function LandingDashboardCarrier(props: Props) {
  const Router = useRouter();

  const [isloading, setIsloading] = useState(true);
  const [sortOrder, setSortOrder] = useState(null);
  const [sortField, setSortField] = useState(null);
  const [enddate] = useState("");
  const dt = useRef(null);

  const { data } = useSession();
  const [clearSelection, setClearSelection] = useState();
  const [totalRecords, setTotalRecords] = useState(0);
  const [startdate] = useState("");
  const [first, setFirst] = useState(0);
  const token = data?.user?.image;
  const [rateQuotesdata, setRateQuotesdata] = useState();
  const [sales_rep, setSalesrep] = useState("");
  const [contact, setContact] = useState("");
  const [email, setEmail] = useState("");
  const [showRegisterPopup, setShowRegisterPopup] = useState(false);
  const [customer, setCustomer] = useState("");
  const [city, setCity] = useState("");
  const [Viewed, setViewed] = useState();
  const [favourite, setFavourite] = useState();
  const [state, setState] = useState("");
  const [counts, setCounts] = useState("");
  const [phone, setPhone] = useState("");
  const [count, setCount] = useState();
  const [monthData, setMonthData] = useState("");
  const [stateData, setStateData] = useState("");
  const [delId, setDelId] = useState("");
  const [perPageDataShow, setPerPageDataShow] = useState(0);
  const [columns, setColumns] = useState<any>([]);
  const [columnsUpdateStatusCount, setColumnsUpdateStatusCount] = useState(0);
  const [tableHeaderId, setTableHeaderId] = useState("");
  const [resetTableHeaderStatus, setResetTableHeaderStatus] = useState(false);
  const [tableKey, setTableKey] = useState(0);

  const fetchTableColumn = async ()=>{
    const requestPayload: any = {
      requestType: 'carrier_customer'
    }
    const response = await toGetTableColumnData(requestPayload);
    if(response?.status == 'success'){
      const allColumns = response?.data?.column_preferences || [];
      const requiredFieldsOrder = [
        { field: "Customer", condition: true },
        { field: "city", condition: true },
        { field: "count", condition: Viewed !== "favorite" && Viewed !== "blocked" },
        { field: "phone", condition: true },
        { field: "state", condition: true },
        { field: "contact", condition: true },
        { field: "email", condition: true },
      ];

      const rulesMap = new Map((requiredFieldsOrder ?? []).map(r => [r?.field, r?.condition]));
      const filteredColumns = (allColumns ?? []).filter((col: { field: string; }) =>
        rulesMap.has(col?.field) ? rulesMap.get(col?.field) : true
      );

      setColumns(filteredColumns);
      setTableHeaderId(response?.data?.id);
    }
  }

  useEffect(()=>{
    fetchTableColumn();
  },[columnsUpdateStatusCount, resetTableHeaderStatus])
  const [visibleColumns, setVisibleColumns] = useState(columns);
  useEffect(() => {
    setVisibleColumns(columns);
  }, [Viewed]);
  const PopuptoggleRegister = (id: any) => {
    setShowRegisterPopup((prev) => !prev);
    setDelId(id);
  };
  const { Permission: userData } = useAuthProvider();

  const toastShownRef = useRef(false);

  useEffect(()=>{
    const storedRateColumn = localStorage.getItem('carrier_customer_selection');
    let selectedRateColumn: any[] = [];
    try {
      const parsed = JSON.parse(storedRateColumn ?? '[]');
      if (Array.isArray(parsed)) {
        selectedRateColumn = parsed;
      }
    } catch (error) {
      selectedRateColumn = [];
    }
    if (selectedRateColumn.length > 0) {
      const oldFieldSet = new Set(selectedRateColumn.map(item => item.field));
      const matchedData = columns.filter((item: { field: any; }) => oldFieldSet.has(item.field));
      setVisibleColumns(matchedData);
    } else {
      setVisibleColumns(columns);
    }
  },[columns])

  const rateQuotesDataGet = (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => {
    setIsloading(true);
    const queryparamdata = {
      start_date: query?.start_date,
      end_date: query?.end_date,
      business_company: query?.customer,
      business_city: query?.city,
      state: query?.state,
      business_phone: query?.phone,
      business_name: query?.contact,
      ...(item === "blocked"
        ? { business_email: query?.email }
        : { email: query?.email }),
      count: query?.count,
    };

    const queryparm = Object.entries(queryparamdata)
      .map(([key, value]) => `${key}=${value || ""}`)
      .join("&");
    getprofiletrack(
      access_token,
      pageno,
      queryparm,
      item === "favourite" ? "" : item
    ).then((response) => {
      if (response?.status === "success") {
        queryparmSuccessModScope(
          setIsloading,
          setTotalRecords,
          response,
          setRateQuotesdata,
          setMonthData,
          setCount,
          setStateData,
          setPerPageDataShow
        );
      } else {
        setIsloading(false);
      }
    });
  };

  useEffect(() => {
    useEffectRoute(
      userData,
      toastShownRef,
      Router,
      rateQuotesDataGet,
      token,
      favourite
    );
  }, [userData]);
  const FilterClear = () => {
    setClearSelection(true);
    setCustomer("");
    setCity("");
    setState("");
    setSalesrep("");
    setContact("");
    setPhone("");
    setEmail("");
    setStartDate(null);
    setEndDate(null);
    setFirst(1);
    setCounts("");
    const query = {
      start_date: "",
      end_date: "",
      customer: "",
      city: "",
      state: "",
      phone: "",
      sales_rep: "",
      contact: "",
      email: "",
      count: "",
    };
    rateQuotesDataGet(token, 1, query, favourite);
  };
  const Toggle = (event: any) => {
    ToggleMod(event, columns, setVisibleColumns);
  };
  const header = headerMod(columns, Toggle, visibleColumns, FilterClear, setVisibleColumns, setResetTableHeaderStatus, tableHeaderId, setTableKey);
  const handleDeleteSome = async () => {
    await handleDeleteSomeMod(
      token,
      delId,
      setShowRegisterPopup,
      rateQuotesDataGet
    );
  };
  const onPageChanges = (event: any) => {
    onPageChangesModule({
      setFirst,
      event,
      startdate,
      enddate,
      customer,
      city,
      state,
      phone,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const CustomerChangeFilterCol = (e: any) => {
    CustomerChangeFilterColModule({
      setCustomer,
      e,
      startdate,
      enddate,
      city,
      state,
      phone,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const spacehandlerOne = (event) => {
    spacehandlerOneModScoped(event);
  };

  const CustomerFilterChangesAll = (
    <>
      <InputText
        type='text'
        className='form-control max-size'
        value={customer}
        onChange={CustomerChangeFilterCol}
        placeholder='Customer Name'
        onKeyDown={spacehandlerOne}
      />
    </>
  );
  const CityFilter = (e) => {
    CityFilterMod({
      setCity,
      e,
      startdate,
      enddate,
      customer,
      state,
      phone,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const StateFilterChangesAll = (e) => {
    StateFilterChangesAllMod({
      setState,
      e,
      startdate,
      enddate,
      customer,
      city,
      phone,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const CountFilterChangesAll = (e) => {
    CountFilterChangesAllMod({
      setCounts,
      e,
      startdate,
      enddate,
      customer,
      city,
      state,
      phone,
      sales_rep,
      contact,
      email,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const phoneFilterChangeAll = (e) => {
    phoneFilterChangeAllModScope({
      e,
      setPhone,
      startdate,
      enddate,
      customer,
      city,
      state,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const SalesRepFilterChangeAll = (e) => {
    SalesRepFilterChangeAllModScope({
      setSalesrep,
      e,
      startdate,
      enddate,
      customer,
      city,
      state,
      phone,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const ContactFilterChangeAll = (e) => {
    ContactFilterChangeAllModScope({
      setContact,
      e,
      startdate,
      enddate,
      customer,
      city,
      state,
      phone,
      sales_rep,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const emailFilterChangeAll = (e) => {
    emailFilterChangeAllMod({
      setEmail,
      e,
      startdate,
      enddate,
      customer,
      city,
      state,
      phone,
      sales_rep,
      contact,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
    });
  };
  const cityFilter = (
    <>
      <InputText
        keyfilter='alpha'
        className='form-control '
        value={city}
        onChange={CityFilter}
        placeholder='City'
        onKeyDown={spacehandlerOne}
      />
    </>
  );

  const StateFilter = (
    <input
      type='text'
      className='form-control'
      value={state}
      onChange={StateFilterChangesAll}
      placeholder='State'
      onKeyDown={spacehandlerOne}
    />
  );
  const countFilter = (
    <input
      type='number'
      className='form-control'
      value={counts}
      onChange={CountFilterChangesAll}
      placeholder='View count'
      onKeyDown={spacehandlerOne}
    />
  );
  const phoneFilter = (
    <input
      type='text'
      className='form-control no-increment-input'
      value={phone}
      onChange={phoneFilterChangeAll}
      placeholder='Phone'
      onKeyDown={spacehandlerOne}
    />
  );

  const salesrepFilter = (
    <input
      type='text'
      className='form-control'
      value={sales_rep}
      onChange={SalesRepFilterChangeAll}
      placeholder='Business Sales Code'
      onKeyDown={spacehandlerOne}
    />
  );

  const ContactFilter = (
    <input
      type='text'
      className='form-control'
      value={contact}
      onChange={ContactFilterChangeAll}
      placeholder='Contact Name'
      onKeyDown={spacehandlerOne}
    />
  );

  const EmailFilter = (
    <input
      type='email'
      className='form-control'
      value={email}
      onChange={emailFilterChangeAll}
      placeholder='Email'
      onKeyDown={spacehandlerOne}
    />
  );

  const [endDate, setEndDate] = useState<DateType>(null);

  const [startDate, setStartDate] = useState<DateType>(null);
  const onSortChange = (e) => {
    setSortField(e.sortField);
    setSortOrder(e.sortOrder);
    customSort(e.sortField, e.sortOrder);
  };
  const handleDateChange = (dates: DateType[]) => {
    handleDateChangeModFunc({
      dates,
      customer,
      city,
      state,
      phone,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
      favourite,
      setStartDate,
      setEndDate,
    });
  };

  const FavouriteSent = (item) => {
    FavouriteSentModFunc({
      setFavourite,
      item,
      setViewed,
      startdate,
      enddate,
      customer,
      city,
      state,
      phone,
      sales_rep,
      contact,
      email,
      counts,
      rateQuotesDataGet,
      token,
    });
  };
  
  const [hoveredPlan, setHoveredPlan] = useState(null);
  const [modalStatus, setModalStatus] = useState(false);
  const [hoveredIndex, setHoveredIndex] = useState(null);

  const handlePlanHover = (plan) => {
    setHoveredPlan(plan);
  };
  const handlePlanLeaveEvent = (e) => {
    setHoveredPlan(null);
  };
  const CustomerBodyTemplate: any = CustomerBodyTemplateMod({
    hoveredPlan,
    data,
    handlePlanLeaveEvent,
    setModalStatus,
    handlePlanHover,
    setViewed,
    FavouriteSent,
    hoveredIndex,
    setHoveredIndex,
  });
  const CityBodyTemplateAllData = CityBodyTemplateAllDataModScope({
    hoveredPlan,
    data,
    handlePlanLeaveEvent,
    setModalStatus,
    handlePlanHover,
    setViewed,
    FavouriteSent,
    hoveredIndex,
    setHoveredIndex,
  });
  const PhoneBodyTemplateAllData = PhoneBodyTemplateAllDataModScope({
    hoveredPlan,
    data,
    handlePlanLeaveEvent,
    setModalStatus,
    handlePlanHover,
    setViewed,
    FavouriteSent,
    hoveredIndex,
    setHoveredIndex,
  });
  const StateBodyTemplateAllData = StateBodyTemplateAllDataModScope();
  const CountBodyTemplateAllData = CountBodyTemplateAllDataModScope();
  const ContactBodyTemplate = ContactBodyTemplateScope({
    hoveredPlan,
    data,
    handlePlanLeaveEvent,
    setModalStatus,
    handlePlanHover,
    setViewed,
    FavouriteSent,
    hoveredIndex,
    setHoveredIndex,
  });
  const EmailBodyTemplate = EmailBodyTemplateScopeMod({
    hoveredPlan,
    data,
    handlePlanLeaveEvent,
    setModalStatus,
    handlePlanHover,
    setViewed,
    FavouriteSent,
    hoveredIndex,
    setHoveredIndex,
  });

  const handleReorderTableColumn = async (event: any) => {
    const dataObj: any = {
      intialTableColumn: columns,
      updatedTableColumn: event,
      requestType: 'carrier_customer',
      visibleColumns: visibleColumns,
      setVisibleColumns: setVisibleColumns
    };
    try {
      const responceData = await toUpdateTableColumn(dataObj);
      if (responceData === true) {
        setColumnsUpdateStatusCount(columnsUpdateStatusCount+1);
      } else {
        console.warn("Reorder update failed or unchanged");
        setColumnsUpdateStatusCount(0);
      }
    } catch (err) {
      console.error("Error during reorder update", err);
      setColumnsUpdateStatusCount(0);
    }
  };

  const UiTemplate = () => {
    return (
      <>
        <div>
          <ToastContainer />
          <SubscriptionPlansModal
            modalStatus={modalStatus}
            SetModalStatus={setModalStatus}
            userDetails={data?.user}
          />
          <div className=''>
            {ViewedModuleScope({
              Viewed,
              FavouriteSent,
              setViewed,
              favourite,
              stateData,
              monthData,
              startDate,
              handleDateChange,
              endDate,
              count,
              handlePlanHover,
              data,
              hoveredPlan,
              handlePlanLeaveEvent,
              setModalStatus,
              setStartDate,
              setEndDate,
              clearSelection,
              setClearSelection,
            })}
          </div>

          <div className='userManaagementheader'>
            <div className='form-group secDiv'>
              {isloading && isLoadingModScope}
              <>
                <div className='datatable-filter-demo'>
                  <div className='card table_height'>
                    <DataTable
                      key={tableKey}
                      lazy
                      filterDisplay='row'
                      ref={dt}
                      header={header}
                      value={rateQuotesdata}
                      paginatorTemplate='FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport'
                      first={first}
                      rows={5}
                      sortField={sortField}
                      sortOrder={sortOrder}
                      onSort={onSortChange}
                      onPage={(e) => {
                        onPageChanges(e);
                      }}
                      totalRecords={totalRecords}
                      className='p-datatable-customers'
                      emptyMessage='No record found.'
                      reorderableColumns
                      onColReorder={(e) => handleReorderTableColumn(e.columns)}
                    >
                      {visibleColumns?.map((col) => {
                        const filterElementMap = {
                          Customer: CustomerFilterChangesAll,
                          city: cityFilter,
                          state: StateFilter,
                          phone: phoneFilter,
                          sales_rep: salesrepFilter,
                          count: countFilter,
                          contact: ContactFilter,
                          email: EmailFilter,
                        };
                        const bodyTemplateMap = {
                          Customer: CustomerBodyTemplate,
                          city: CityBodyTemplateAllData,
                          state: StateBodyTemplateAllData,
                          phone: PhoneBodyTemplateAllData,
                          count: CountBodyTemplateAllData,
                          contact: ContactBodyTemplate,
                          email: EmailBodyTemplate,
                        };
                        return (
                          <Column
                            className={col.field === 'Customer' ? 'title_heading' : ''}
                            sortable
                            key={col.field}
                            field={col.field}
                            columnKey={col.field}
                            header={col.header}
                            filter
                            filterElement={filterElementMap[col.field]}
                            body={bodyTemplateMap[col.field]}
                          />
                        );
                      })}
                    </DataTable>
                    <div className="pagination_footer">
                      <PaginationTitle first={first} totalRecords={totalRecords} perPageData={perPageDataShow}/>
                      <Paginator
                        rows={10}
                        first={first}
                        totalRecords={totalRecords}
                        onPageChanges={onPageChanges}
                      />
                    </div>
                  </div>
                </div>
              </>
            </div>
          </div>
          <Modal show={showRegisterPopup} onHide={PopuptoggleRegister}>
            <Modal.Header>
              <Modal.Title>Are you sure you want to delete ?</Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <div className='reg_button'>
                <Button
                  severity='danger'
                  className='mx-2 '
                  onClick={() => handleDeleteSome()}
                >
                  Confirm
                </Button>
                <Button
                  className='mx-2 carrierButton'
                  onClick={PopuptoggleRegister}
                >
                  Close
                </Button>
              </div>
            </Modal.Body>
            <Modal.Footer></Modal.Footer>
          </Modal>
        </div>
      </>
    );
  };
  const customSort = (field, order) => {
    customSortModScope(rateQuotesdata, order, field, setRateQuotesdata);
  };
  return <>{UiTemplate()}</>;
}
export default LandingDashboardCarrier;

function useEffectRoute(
  userData: undefined,
  toastShownRef,
  Router,
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void,
  token: string | null | undefined,
  favourite: undefined
) {
  if (userData && !userData?.ViewCustomerTab) {
    if (!toastShownRef.current) {
      toastShownRef.current = true;
      toast.error("Access Denied", {
        position: toast.POSITION.TOP_CENTER,
      });
    }
    Router.push("/dashboard");
  } else {
    rateQuotesDataGet(token, 1, "", favourite);
  }
}

function queryparmSuccessModScope(
  setIsloading,
  setTotalRecords,
  response: any,
  setRateQuotesdata,
  setMonthData,
  setCount,
  setStateData,
  setPerPageDataShow
) {
  setIsloading(false);
  setTotalRecords(response?.meta?.total);
  setRateQuotesdata(response?.data);
  setMonthData(response?.month_wise_count);
  setCount(response?.all_count ? response?.all_count : 0);
  setStateData(response?.state_wise_count);
  setPerPageDataShow(response?.meta?.per_page)
}

function spacehandlerOneModScoped(event: any) {
  if (event.which === 32 && event.target.value.trim() === "") {
    event.preventDefault();
  }
}

function CustomerBodyTemplateMod({
  hoveredPlan,
  data,
  handlePlanLeaveEvent,
  setModalStatus,
  handlePlanHover,
  setViewed,
  FavouriteSent,
  hoveredIndex,
  setHoveredIndex,
}: {
  hoveredPlan;
  data;
  handlePlanLeaveEvent;
  setModalStatus;
  handlePlanHover;
  setViewed;
  FavouriteSent;
  hoveredIndex;
  setHoveredIndex;
}) {
  // Track hovered index

  return (rowData, index) => {
    // Pass index as a parameter

    if (
      rowData?.business_company === undefined ||
      rowData?.business_company === null ||
      rowData?.business_company === ""
    ) {
      return <p>N/A</p>;
    } else {
      return (
        <>
          <div
            onMouseOver={() => {
              handlePlanHover("business_company");
              setHoveredIndex(index.rowIndex);
            }}
            // onClick={() => {
            //   ModOnclick(data, setViewed, FavouriteSent);
            // }}
            className={`user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
          >
            <p className='TypeRepBodyTemplateCss'>
              {rowData?.business_company}
            </p>
          </div>
          <div
            className='hover-box '
            onMouseLeave={() => handlePlanLeaveEvent()}
          >
            {hoveredPlan === "business_company" &&
              toCheckUserTypeSubscreption(data) &&
              data?.user?.is_child !== 1 &&
              hoveredIndex === index.rowIndex && (
                <div>
                  <div
                    className='dropdown-menu show dropdown-menu-light'
                    style={{ marginTop: "-60px" }}
                    onClick={() => setModalStatus(true)}
                  >
                    <a
                      className='dropdown-item active-anchor'
                      role='button'
                      tabIndex='0'
                      href='#'
                    >
                      Available in Draydex Premium
                    </a>
                  </div>
                </div>
              )}
          </div>
        </>
      );
    }
  };
}

function ModOnclick(data: any, setViewed: any, FavouriteSent: any) {
  if (data?.user?.is_premium !== 0) {
    setViewed("");
  }
  FavouriteSent("favourite");
}

function FavouriteSentModFunc({
  setFavourite,
  item,
  setViewed,
  startdate,
  enddate,
  customer,
  city,
  state,
  phone,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
}: {
  setFavourite;
  item: any;
  setViewed;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
}) {
  setFavourite(item);
  setViewed(item);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, item === "favourite" ? "" : item);
}

function handleDateChangeModFunc({
  dates,
  customer,
  city,
  state,
  phone,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
  setStartDate,
  setEndDate,
}: {
  dates: DateType[];
  customer: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
  setStartDate;
  setEndDate;
}) {
  const [start, end] = dates;
  const formattedStart = start ? Moment(start).format("YYYY-MM-DD") : null;
  const formattedEnd = end ? Moment(end).format("YYYY-MM-DD") : null;

  const query = {
    start_date: formattedStart,
    end_date: formattedEnd,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
  setStartDate(start);
  setEndDate(end);
}

function EmailBodyTemplateScopeMod({
  hoveredPlan,
  data,
  handlePlanLeaveEvent,
  setModalStatus,
  handlePlanHover,
  setViewed,
  FavouriteSent,
  hoveredIndex,
  setHoveredIndex,
}: {
  hoveredPlan;
  data;
  handlePlanLeaveEvent;
  setModalStatus;
  handlePlanHover;
  setViewed;
  FavouriteSent;
  hoveredIndex;
  setHoveredIndex;
}) {
  return EmailBodyTemplateScopeModData({
    handlePlanHover,
    setHoveredIndex,
    data,
    setViewed,
    FavouriteSent,
    handlePlanLeaveEvent,
    hoveredPlan,
    hoveredIndex,
    setModalStatus,
  });
}

function EmailBodyTemplateScopeModData({
  handlePlanHover,
  setHoveredIndex,
  data,
  setViewed,
  FavouriteSent,
  handlePlanLeaveEvent,
  hoveredPlan,
  hoveredIndex,
  setModalStatus,
}: {
  handlePlanHover: any;
  setHoveredIndex: any;
  data: any;
  setViewed: any;
  FavouriteSent: any;
  handlePlanLeaveEvent: any;
  hoveredPlan: any;
  hoveredIndex: any;
  setModalStatus: any;
}) {
  return (rowData, index) => {
    if (rowData?.email) {
      if (
        rowData?.email === undefined ||
        rowData?.email === null ||
        rowData?.email === ""
      ) {
        return <p>N/A</p>;
      } else {
        return EmailBodyTemplateScopeModDataJsx({
          handlePlanHover,
          setHoveredIndex,
          index,
          data,
          setViewed,
          FavouriteSent,
          rowData,
          handlePlanLeaveEvent,
          hoveredPlan,
          hoveredIndex,
          setModalStatus,
        });
      }
    }
    if (rowData?.business_email) {
      if (
        rowData?.business_email === undefined ||
        rowData?.business_email === null ||
        rowData?.business_email === ""
      ) {
        return <p>N/A</p>;
      } else {
        return (
          <>
            <div
              onMouseOver={() => {
                handlePlanHover("business_email");
                setHoveredIndex(index.rowIndex);
              }}
              onClick={() => {
                setViewedClick(data, setViewed);
                FavouriteSent("favourite");
              }}
              className={`user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
            >
              <p className='TypeRepBodyTemplateCss'>
                {rowData?.business_email}
              </p>
            </div>
            <div onMouseLeave={() => handlePlanLeaveEvent()}>
              {hoveredPlan === "business_email" &&
                toCheckUserTypeSubscreption(data) &&
                data?.user?.is_child !== 1 &&
                hoveredIndex === index.rowIndex && ( // Check if this index is hovered
                  <div>
                    <div
                      className='dropdown-menu show dropdown-menu-light'
                      style={{ marginTop: "-60px" }}
                      onClick={() => setModalStatus(true)}
                    >
                      <a
                        className='dropdown-item active-anchor'
                        role='button'
                        tabIndex='0'
                        href='#'
                      >
                        Available in Draydex Premium
                      </a>
                    </div>
                  </div>
                )}
            </div>
          </>
        );
      }
    }
  };
}

function setViewedClick(data: any, setViewed: any) {
  if (data?.user?.is_premium !== 0) {
    setViewed("");
  }
}

function EmailBodyTemplateScopeModDataJsx({
  handlePlanHover,
  setHoveredIndex,
  index,
  data,
  setViewed,
  FavouriteSent,
  rowData,
  handlePlanLeaveEvent,
  hoveredPlan,
  hoveredIndex,
  setModalStatus,
}: {
  handlePlanHover: any;
  setHoveredIndex: any;
  index: any;
  data: any;
  setViewed: any;
  FavouriteSent: any;
  rowData: any;
  handlePlanLeaveEvent: any;
  hoveredPlan: any;
  hoveredIndex: any;
  setModalStatus: any;
}) {
  return (
    <>
      <div
        onMouseOver={() => {
          handlePlanHover("email");
          setHoveredIndex(index.rowIndex); // Set hovered index
        }}
        onClick={() => {
          if (!toCheckUserTypeSubscreption(data) || toCheckUserTypeSubscreption(data) === "free") {
            return; 
          }

          setViewedClick(data, setViewed);
        }}

        className={`user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
      >
        <p className='TypeRepBodyTemplateCss'>{rowData?.email}</p>
      </div>
      <div onMouseLeave={() => handlePlanLeaveEvent()}>
        {hoveredPlan === "email" &&
          toCheckUserTypeSubscreption(data) &&
          data?.user?.is_child !== 1 &&
          hoveredIndex === index.rowIndex && ( // Check if this index is hovered
            <div>
              <div
                className='dropdown-menu show dropdown-menu-light'
                style={{ marginTop: "-60px" }}
                onClick={() => setModalStatus(true)}
              >
                <a
                  className='dropdown-item active-anchor'
                  role='button'
                  tabIndex='0'
                  href='#'
                >
                  Available in Draydex Premium
                </a>
              </div>
            </div>
          )}
      </div>
    </>
  );
}

function ContactBodyTemplateScope({
  hoveredPlan,
  data,
  handlePlanLeaveEvent,
  setModalStatus,
  handlePlanHover,
  setViewed,
  FavouriteSent,
  hoveredIndex,
  setHoveredIndex,
}: {
  hoveredPlan;
  data;
  handlePlanLeaveEvent;
  setModalStatus;
  handlePlanHover;
  setViewed;
  FavouriteSent;
  hoveredIndex;
  setHoveredIndex;
}) {
  return (rowData, index) => {
    // Pass index as a parameter

    if (
      rowData?.business_name === undefined ||
      rowData?.business_name === null ||
      rowData?.business_name === ""
    ) {
      return <p>N/A</p>;
    } else {
      return (
        <>
          <div
            onMouseOver={() => {
              handlePlanHover("business_name");
              setHoveredIndex(index.rowIndex);
            }}
            // onClick={() => {
            //   toCheckUserTypeSubscreption(data) && "free"?"":
            //   ModOnclick(data, setViewed, FavouriteSent);
            // }
            // }
            className={`user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
          >
            <p className='TypeRepBodyTemplateCss'>{rowData?.business_name}</p>
          </div>
          <div onMouseLeave={() => handlePlanLeaveEvent()}>
            {hoveredPlan === "business_name" &&
              toCheckUserTypeSubscreption(data) &&
              data?.user?.is_child !== 1 &&
              hoveredIndex === index.rowIndex && ( // Check if this index is hovered
                <div>
                  <div
                    className='dropdown-menu show dropdown-menu-light'
                    style={{ marginTop: "-60px" }}
                    onClick={() => setModalStatus(true)}
                  >
                    <a
                      className='dropdown-item active-anchor'
                      role='button'
                      tabIndex='0'
                      href='#'
                    >
                      Available in Draydex Premium
                    </a>
                  </div>
                </div>
              )}
          </div>
        </>
      );
    }
  };
}

function CountBodyTemplateAllDataModScope() {
  return (rowData) => {
    if (
      rowData.count === undefined ||
      rowData.count === null ||
      rowData.count == ""
    ) {
      return <p>N/A</p>;
    } else {
      return <p className='TypeRepBodyTemplateCss'>{rowData.count}</p>;
    }
  };
}

function StateBodyTemplateAllDataModScope() {
  return (rowData) => {
    if (
      rowData.state === undefined ||
      rowData.state === null ||
      rowData.state == ""
    ) {
      return <p>N/A</p>;
    } else {
      return <p className='TypeRepBodyTemplateCss'>{rowData.state}</p>;
    }
  };
}

function PhoneBodyTemplateAllDataModScope({
  hoveredPlan,
  data,
  handlePlanLeaveEvent,
  setModalStatus,
  handlePlanHover,
  setViewed,
  FavouriteSent,
  hoveredIndex,
  setHoveredIndex,
}: {
  hoveredPlan;
  data;
  handlePlanLeaveEvent;
  setModalStatus;
  handlePlanHover;
  setViewed;
  FavouriteSent;
  hoveredIndex;
  setHoveredIndex;
}) {
  return (rowData, index) => {
    // Pass index as a parameter

    if (!rowData.business_phone || rowData.business_phone.trim() === "") {
      return <p>N/A</p>;
    } else {
      const formattedPhoneNumber = rowData?.business_phone?.replace(
        /(\d{3})(\d{3})(\d{4})/,
        "$1-$2-$3"
      );
      return (
        <>
          <div
            onMouseOver={() => {
              handlePlanHover("formattedPhoneNumber");
              setHoveredIndex(index.rowIndex); // Set hovered index
            }}
            // onClick={() => {
            //   toCheckUserTypeSubscreption(data) && "free"?"":  ModOnclick(data, setViewed, FavouriteSent);
            // }}
            className={`user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
          >
            <p className='TypeRepBodyTemplateCss'>{formattedPhoneNumber}</p>
          </div>
          <div onMouseLeave={() => handlePlanLeaveEvent()}>
            {hoveredPlan === "formattedPhoneNumber" &&
              toCheckUserTypeSubscreption(data) &&
              data?.user?.is_child !== 1 &&
              hoveredIndex === index.rowIndex && ( // Check if this index is hovered
                <div>
                  <div
                    className='dropdown-menu show dropdown-menu-light'
                    style={{ marginTop: "-60px" }}
                    onClick={() => setModalStatus(true)}
                  >
                    <a
                      className='dropdown-item active-anchor'
                      role='button'
                      tabIndex='0'
                      href='#'
                    >
                      Available in Draydex Premium
                    </a>
                  </div>
                </div>
              )}
          </div>
        </>
      );
    }
  };
}

function CityBodyTemplateAllDataModScope({
  hoveredPlan,
  data,
  handlePlanLeaveEvent,
  setModalStatus,
  handlePlanHover,
  setViewed,
  FavouriteSent,
  hoveredIndex,
  setHoveredIndex,
}: {
  hoveredPlan;
  data;
  handlePlanLeaveEvent;
  setModalStatus;
  handlePlanHover;
  setViewed;
  FavouriteSent;
  hoveredIndex;
  setHoveredIndex;
}) {
  return (rowData, index) => {
    // Pass index as a parameter

    if (
      rowData?.business_city === undefined ||
      rowData?.business_city === null ||
      rowData?.business_city === ""
    ) {
      return <p>N/A</p>;
    } else {
      return (
        <>
          <div
            onMouseOver={() => {
              handlePlanHover("business_city");
              setHoveredIndex(index.rowIndex); // Set hovered index
            }}
            // onClick={() => {
            //   ModOnclick(data, setViewed, FavouriteSent);
            // }}
            className={`user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
          >
            <p className='TypeRepBodyTemplateCss'>{rowData?.business_city}</p>
          </div>
          <div onMouseLeave={() => handlePlanLeaveEvent()}>
            {hoveredPlan === "business_city" &&
              toCheckUserTypeSubscreption(data) &&
              data?.user?.is_child !== 1 &&
              hoveredIndex === index.rowIndex && ( // Check if this index is hovered
                <div>
                  <div
                    className='dropdown-menu show dropdown-menu-light'
                    style={{ marginTop: "-60px" }}
                    onClick={() => setModalStatus(true)}
                  >
                    <a
                      className='dropdown-item active-anchor'
                      role='button'
                      tabIndex='0'
                      href='#'
                    >
                      Available in Draydex Premium
                    </a>
                  </div>
                </div>
              )}
          </div>
        </>
      );
    }
  };
}

function emailFilterChangeAllMod({
  setEmail,
  e,
  startdate,
  enddate,
  customer,
  city,
  state,
  phone,
  sales_rep,
  contact,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setEmail;
  e: any;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setEmail(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: e.target.value,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function ContactFilterChangeAllModScope({
  setContact,
  e,
  startdate,
  enddate,
  customer,
  city,
  state,
  phone,
  sales_rep,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setContact;
  e: any;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setContact(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: e.target.value,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function SalesRepFilterChangeAllModScope({
  setSalesrep,
  e,
  startdate,
  enddate,
  customer,
  city,
  state,
  phone,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setSalesrep;
  e: any;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  phone: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setSalesrep(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    sales_rep: e.target.value,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function phoneFilterChangeAllModScope({
  e,
  setPhone,
  startdate,
  enddate,
  customer,
  city,
  state,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  e: any;
  setPhone;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  let inputValueData = e.target.value;
  const cleanedInputData = inputValueData.replace(/\D/g, "");
  const formattedNumber = cleanedInputData.slice(0, 10);
  const formattedDisplay = formattedNumber.replace(
    /(\d{3})(\d{3})(\d{4})/,
    "$1-$2-$3"
  );

  setPhone(formattedDisplay);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: formattedDisplay,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function customSortModScope(
  rateQuotesdata: undefined,
  order: any,
  field: any,
  setRateQuotesdata
) {
  if (Array.isArray(rateQuotesdata)) {
    const sortedData = [...rateQuotesdata];
    sortedData.sort((a, b) => {
      if (order === 1) {
        return a[field] > b[field] ? 1 : -1;
      } else {
        return b[field] > a[field] ? 1 : -1;
      }
    });
    setRateQuotesdata(sortedData);
  }
}

function ViewedModuleScope({
  Viewed,
  FavouriteSent,
  setViewed,
  favourite,
  stateData,
  monthData,
  startDate,
  handleDateChange,
  endDate,
  count,
  handlePlanHover,
  data,
  hoveredPlan,
  handlePlanLeaveEvent,
  setModalStatus,
  setStartDate,
  setEndDate,
  clearSelection,
  setClearSelection,
}: {
  Viewed: undefined;
  FavouriteSent: (item: any) => void;
  setViewed;
  favourite: undefined;
  stateData: string;
  monthData: string;
  startDate: DateType;
  handleDateChange: (dates: DateType[]) => void;
  endDate: DateType;
  count: undefined;
  handlePlanHover: (plan: any) => void;
  data;
  hoveredPlan: null;
  handlePlanLeaveEvent: (e: any) => void;
  setModalStatus;
  setStartDate;
  setEndDate;
  clearSelection;
  setClearSelection;
}) {
  return ViewedModuleScopeModFunction({ Viewed, FavouriteSent, setViewed, favourite, stateData, monthData, startDate, handleDateChange, endDate, count, clearSelection, setClearSelection, handlePlanHover, data, hoveredPlan, handlePlanLeaveEvent, setModalStatus });
}

function ViewedModuleScopeModFunction({ Viewed, FavouriteSent, setViewed, favourite, stateData, monthData, startDate, handleDateChange, endDate, count, clearSelection, setClearSelection, handlePlanHover, data, hoveredPlan, handlePlanLeaveEvent, setModalStatus }: { Viewed: undefined; FavouriteSent: (item: any) => void; setViewed: any; favourite: undefined; stateData: string; monthData: string; startDate: DateType; handleDateChange: (dates: DateType[]) => void; endDate: DateType; count: undefined; clearSelection: any; setClearSelection: any; handlePlanHover: (plan: any) => void; data: any; hoveredPlan: null; handlePlanLeaveEvent: (e: any) => void; setModalStatus: any; }) {
  return Viewed ? (
    <div className='row my-6'>
      {ViewedModuleScopeModFunctionJsx(FavouriteSent, setViewed, favourite)}
      {favouriteJsxScope({
        favourite,
        stateData,
        monthData,
        startDate,
        handleDateChange,
        endDate,
        count,
        clearSelection,
        setClearSelection,
      })}
    </div>
  ) : (
    ViewedModuleScopeModFunctionSecond(handlePlanHover, data, setViewed, FavouriteSent, hoveredPlan, handlePlanLeaveEvent, setModalStatus)
  );
}

function ViewedModuleScopeModFunctionSecond(handlePlanHover: (plan: any) => void, data: any, setViewed: any, FavouriteSent: (item: any) => void, hoveredPlan: null, handlePlanLeaveEvent: (e: any) => void, setModalStatus: any) {
  return <div className='d-flex justify-content-between gap-2 my-3'>
    <button
      onMouseOver={() => handlePlanHover("common_accessorial")}
      onClick={() => {
        if (!toCheckUserTypeSubscreption(data) || !("free")) {
          ModOnclick(data, setViewed, FavouriteSent);
        }
      } }
      type='button'
      // className={`btn btn_customer btn-primary btn-lg w-100${toCheckUserTypeSubscreption(data) && "free"}`}
      className={`btn btn_customer btn-primary btn-lg w-100 box-heading user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
    >
      <Image src={viewEye} alt={""}></Image>{" "}
      <span style={{ fontSize: "larger" }}>
        Customers who viewed your profile
      </span>
    </button>
    {hoveredPlan === "common_accessorial" &&
      toCheckUserTypeSubscreption(data) &&
      data?.user?.is_child !== 1 &&
      "free" && (
        <div onMouseLeave={() => handlePlanLeaveEvent()}>
          <div
            onMouseLeave={() => handlePlanLeaveEvent()}
            className='hover-box'
            style={{
              position: "relative",
              display: "block",
              marginLeft: "-328px",
            }}
            onClick={() => setModalStatus(true)}
            x-placement='bottom-start'
            aria-labelledby='nav-dropdown'
            className='dropdown-menu show dropdown-menu-light'
            data-popper-reference-hidden='false'
            data-popper-escaped='false'
            data-popper-placement='bottom-start'
            bis_skin_checked='1'
          >
            <a
              data-rr-ui-dropdown-item=''
              class='dropdown-item active-anchor'
              role='button'
              tabindex='0'
              href='#'
            >
              Available in Draydex Premium
            </a>
          </div>
        </div>
      )}
    <button
      onMouseOver={() => handlePlanHover("Carriers_list")}
      onClick={() => toCheckUserTypeSubscreption(data) && "free" ? "" : FavouriteSent("favorite")}
      type='button'
      // className="btn btn_customer btn-success btn-lg w-100"
      className={`btn btn_customer btn-success btn-lg w-100 box-heading user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
    >
      <Image src={Checklist} alt={""}></Image>{" "}
      <span style={{ fontSize: "larger" }}>
        Customer who added you in Their My Carriers list.
      </span>
    </button>
    {hoveredPlan === "Carriers_list" &&
      toCheckUserTypeSubscreption(data) &&
      data?.user?.is_child !== 1 &&
      "free" && (
        <div onMouseLeave={() => handlePlanLeaveEvent()}>
          <div
            onMouseLeave={() => handlePlanLeaveEvent()}
            className='hover-box'
            style={{
              position: "relative",
              display: "block",
              marginLeft: "-328px",
            }}
            onClick={() => setModalStatus(true)}
            x-placement='bottom-start'
            aria-labelledby='nav-dropdown'
            className='dropdown-menu show dropdown-menu-light'
            data-popper-reference-hidden='false'
            data-popper-escaped='false'
            data-popper-placement='bottom-start'
            bis_skin_checked='1'
          >
            <a
              data-rr-ui-dropdown-item=''
              class='dropdown-item active-anchor'
              role='button'
              tabindex='0'
              href='#'
            >
              Available in Draydex Premium
            </a>
          </div>
        </div>
      )}
    <button
      onMouseOver={() => handlePlanHover("Banned_list")}
      onClick={() => toCheckUserTypeSubscreption(data) && "free" ? "" : FavouriteSent("blocked")}
      type='button'
      className={`btn btn_customer btn-danger btn-lg w-100 box-heading user_subscreption_${toCheckUserTypeSubscreption(data) && "free"}`}
    >
      <Image style={{ fontSize: "larger" }} src={Prohibit} alt={""}></Image>

      <span style={{ fontSize: "larger" }}>
        Customer who added you in their Banned/Blocked list
      </span>
    </button>
    {hoveredPlan === "Banned_list" &&
      toCheckUserTypeSubscreption(data) &&
      data?.user?.is_child !== 1 &&
      "free" && (
        <div onMouseLeave={() => handlePlanLeaveEvent()}>
          <div
            onMouseLeave={() => handlePlanLeaveEvent()}
            className='hover-box'
            style={{
              position: "relative",
              display: "block",
              marginLeft: "-328px",
            }}
            onClick={() => setModalStatus(true)}
            x-placement='bottom-start'
            aria-labelledby='nav-dropdown'
            className='dropdown-menu show dropdown-menu-light'
            data-popper-reference-hidden='false'
            data-popper-escaped='false'
            data-popper-placement='bottom-start'
            bis_skin_checked='1'
          >
            <a
              data-rr-ui-dropdown-item=''
              class='dropdown-item active-anchor'
              role='button'
              tabindex='0'
              href='#'
            >
              Available in Draydex Premium
            </a>
          </div>
        </div>
      )}
  </div>;
}

function ViewedModuleScopeModFunctionJsx(FavouriteSent: (item: any) => void, setViewed: any, favourite: undefined) {
  return <div>
    <div className='about-Parent'>
      <button
        onClick={() => {
          FavouriteSent("favourite");
          setViewed("");
        } }
        type='button'
        className='btn btn-primary divStylecss-update'
      >
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-left-short" viewBox="0 0 16 16">
  <path fill-rule="evenodd" d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5"/>
</svg>
        Back
      </button>
      <div className={favouritesModule(favourite)}>
        <h4>
          {favourite === "favorite" && (
            <>
              Customer who added you in Their My Carriers list
              <hr className='hr mt-3' />{" "}
            </>
          )}
          {favourite === "blocked" && (
            <>
              Customer who added you in their Banned/Blocked list
              <hr className='hr mt-3' />{" "}
            </>
          )}
          {favourite === "favourite" && (
            <>
           <div className="table-headers-fallback"> 
             <h3> Customer who viewed your profile</h3></div>
              <hr className='hr mt-3' />{" "}
            </>
          )}
        </h4>
      </div>
    </div>
  </div>;
}

function CountFilterChangesAllMod({
  setCounts,
  e,
  startdate,
  enddate,
  customer,
  city,
  state,
  phone,
  sales_rep,
  contact,
  email,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setCounts;
  e: any;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setCounts(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    count: e.target.value,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: e.target.value,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function StateFilterChangesAllMod({
  setState,
  e,
  startdate,
  enddate,
  customer,
  city,
  phone,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setState;
  e: any;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setState(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: e.target.value,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function CityFilterMod({
  setCity,
  e,
  startdate,
  enddate,
  customer,
  state,
  phone,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setCity;
  e: any;
  startdate: string;
  enddate: string;
  customer: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setCity(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: e.target.value,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function CustomerChangeFilterColModule({
  setCustomer,
  e,
  startdate,
  enddate,
  city,
  state,
  phone,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setCustomer;
  e: any;
  startdate: string;
  enddate: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  setCustomer(e.target.value);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: e.target.value,
    city: city,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, 1, query, favourite);
}

function onPageChangesModule({
  setFirst,
  event,
  startdate,
  enddate,
  customer,
  city,
  state,
  phone,
  sales_rep,
  contact,
  email,
  counts,
  rateQuotesDataGet,
  token,
  favourite,
}: {
  setFirst;
  event: any;
  startdate: string;
  enddate: string;
  customer: string;
  city: string;
  state: string;
  phone: string;
  sales_rep: string;
  contact: string;
  email: string;
  counts: string;
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void;
  token: any;
  favourite: undefined;
}) {
  let perpage = 0;
  setFirst(event.first);
  const query = {
    start_date: startdate,
    end_date: enddate,
    customer: customer,
    city: city,
    state: state,
    phone: phone,
    sales_rep: sales_rep,
    contact: contact,
    email: email,
    count: counts,
  };
  rateQuotesDataGet(token, perpage, query, favourite);
}

async function handleDeleteSomeMod(
  token: any,
  delId: string,
  setShowRegisterPopup,
  rateQuotesDataGet: (
    access_token: string,
    pageno: number | string,
    query: string,
    item: any
  ) => void
) {
  const response = await CustomerChilddeleteid(token, delId);
  if (response.status === "success") {
    toast.success(response.message, {
      position: toast.POSITION.TOP_CENTER,
    });
    setShowRegisterPopup(false);
    rateQuotesDataGet(token);
  } else {
    toast.error(response.message, {
      position: toast.POSITION.TOP_CENTER,
    });
  }
}

function headerMod(
  columns: { field: string; header: string }[],
  Toggle: (event: any) => void,
  visibleColumns: { field: string; header: string }[],
  FilterClear: () => void,
  setVisibleColumns: any,
  setResetTableHeaderStatus: any,
  tableHeaderId: any,
  setTableKey: any,
) {
  const onShow = () => {
    let selectAllCheckbox = document.querySelector(
      ".p-multiselect-header > .p-checkbox"
    );
    selectAllCheckbox.style.marginRight = "8px";
    selectAllCheckbox.after(" Select All");
  };

  const clearSelectionFilter = () => {
    toast.success("View reset to default successfully.",{
      position: toast.POSITION.TOP_CENTER,
    });
    localStorage.removeItem('carrier_customer_selection');
    setVisibleColumns(columns);
  }

  const editViewFooterTemplate = () => {
    return (
      <div className="py-2 text-center">
        <Button onClick={()=>clearSelectionFilter()}>Default</Button>
      </div>
    );
  };

  const clearResetOrder = async ()=>{
    try {
      if (!tableHeaderId) {
        return;
      }
      const response = await toResetTableHeaderColumns({ id: tableHeaderId });
      if (response?.status === 'success') {
        setResetTableHeaderStatus((prev: any) => !prev);
        setTableKey((prev: number) => prev + 1);
        toast.success(response.message || 'Reset successful', {
          position: toast.POSITION.TOP_CENTER,
        });
      }
    } catch (error) {
      console.error('Error resetting table header:', error);
    }
  }
  
  return (
    <div className='table-header'>
      <div className='d-flex justify-content-end'>
        <div className='recent_quote'>
          <span className='p-input-icon-left'>
            <div className='d-none'></div>
          </span>
          <MultiSelect
            maxSelectedLabels={0}
            optionLabel='header'
            options={columns}
            placeholder='Edit View'
            selectedItemsLabel='Edit View'
            onChange={Toggle}
            value={visibleColumns}
            className={`${styles.MultiSelect} w-full sm:w-20rem divStylecss`}
            onShow={onShow}
            panelFooterTemplate={editViewFooterTemplate}
          />
          <Button
          className="divStylecss-update "
            type='button'
            icon='pi pi-filter-slash'
            label='Clear'
            onClick={FilterClear}
          />
          <Button
            className="divStylecss-clear reset-order-button"
            type="button"
            label="Reset Order"
            onClick={clearResetOrder}
          />
        </div>
      </div>
    </div>
  );
}

function ToggleMod(
  event: any,
  columns: { field: string; header: string }[],
  setVisibleColumns
) {
  let selectedColumns = event.value;
  let orderedSelectedColumns = columns.filter((col) =>
    selectedColumns.some((sCol) => sCol.field === col.field)
  );
  setVisibleColumns(orderedSelectedColumns);
  localStorage.setItem('carrier_customer_selection', JSON.stringify(orderedSelectedColumns));
}

function favouriteJsxScope({
  favourite,
  stateData,
  monthData,
  startDate,
  handleDateChange,
  endDate,
  count,
  clearSelection,
  setClearSelection,
}: {
  favourite: undefined;
  stateData: string;
  monthData: string;
  startDate: DateType;
  handleDateChange: (dates: DateType[]) => void;
  endDate: DateType;
  count: undefined;
  clearSelection;
  setClearSelection;
}) {
  return favourite === "favourite" ? (
    <>
      <div className='col-lg-4 map-liner'>
        <DashboardGraphCarrier datas={stateData} />
      </div>
      <div className='col-lg-4 col-sm-6 col_box map-liner'>
        <div className='graph_customer'>
          <LineGraph
            data={monthData}
            startDate={startDate}
            endDate={endDate}
            selection={clearSelection}
            clearSelection={setClearSelection}
          />
        </div>
      </div>
      <div className='col-lg-4 col-sm-12 col_box'>
        <div className='range_customer'>
          <h6>Select Date Range</h6>
          <DatePicker
            placeholderText='Select Date Range'
            wrapperClassName='datePicker'
            className='form-select form-select-sm pe-0 py-1 fs-14 '
            selected={startDate}
            onChange={handleDateChange}
            startDate={startDate}
            endDate={endDate}
            selectsRange
            showMonthYearPicker
            dateFormat='MM/yyyy'
            maxDate={Moment().toDate()}
          />
        </div>

        <div className='eye_icon'>
          <i className='bi bi-eye eye-font'></i>
          <div>
            <p style={{ textAlign: "center", height: '22px' }}>{count}</p>
            <p>Customers viewed your profile</p>
          </div>
        </div>
      </div>
    </>
  ) : (
    ""
  );
}

function favouritesModule(favourite: undefined): string | undefined {
  let colorCode: string;

  if (favourite === "favorite") {
    colorCode = "colorCodefavorite";
  } else if (favourite === "blocked") {
    colorCode = "colorCodeBlocked";
  } else if (favourite === "favourite") {
    colorCode = "colorCodeViewed";
  } else {
    colorCode = "";
  }

  return `viewed ${colorCode}`;
}
