/* eslint-disable react/jsx-key */
import React, { useState, useEffect } from "react";
import { Row, Col, Modal, Button } from "react-bootstrap";
import SubmitRateModal from "../modal/SubmitRateModal";
import { useSession } from "next-auth/react";
import { ScaleLoader } from "react-spinners";
import {
  getDrayageSpotRateQuotes,
  SpotRateQuoteDetails,
  CsvData,
  DeleteRate,
} from "@/services/public";
import SubscriptionPlansModal from "../modal/SubscriptionPlansModal";
import { useRouter } from "next/router";
import carriersLogo from "@/public/images/carriersLogo.png";
import users from "@/public/images/users.svg";
import useAuthProvider from "@/useAuthProvider";
import admin from "@/public/images/admin.png";
import Image from "next/image";
import { ToastContainer, toast } from "react-toastify";
import { useSearchParams } from 'next/navigation';
const finalised = <div>
  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    Quote Finalized Based on Carrier Rate Selected Below
  </p>
</div>;
const fegmentUi = finalised;
const newLocal_1 = <div>
  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table divStylecss-update'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    RATE QUOTE HAS BEEN SENT TO CUSTOMER
  </p>
</div>;
const newLocal_2 = <div>
  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table divStylecss-update'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    RATE QUOTE HAS BEEN SENT TO CUSTOMER
  </p>
</div>;
const newLocal_3 = <div>

  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    Quote Finalized Based on Carrier Rate Selected Below
  </p>{" "}
</div>;
const content2ScopeReturn = <div>

  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    Quote Finalized Based on Carrier Rate Selected Below
  </p>{" "}
</div>;
const newLocal_4 = <div>
  {/* <button>Revise</button> */}
  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table divStylecss-update'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    RATE QUOTE HAS BEEN SENT TO CUSTOMER
  </p>
</div>;
const newLocal_5 = <div>
  <p
    style={{ pointerEvents: "none" }}
    className='btn btn-primary rate-btn-rate-table divStylecss-update'
  >
    <svg
      xmlns='http://www.w3.org/2000/svg'
      width='16'
      height='16'
      fill='currentColor'
      class='bi bi-send'
      viewBox='0 0 16 16'
    >
      <path d='M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76 7.494-7.493Z' />
    </svg>{" "}
    RATE QUOTE HAS BEEN SENT TO CUSTOMER
  </p>
</div>;
const premiumScopeRender = newLocal_1;
const returnTernaryRole32 = newLocal_5;
const newLocal = newLocal_4;
function RateTable(props: any) {
  const [showModal, setShowModal] = useState(false);
  const [spotsrate, setSpotsrate] = useState([]);
  const [spotDetails, setSpotDetail] = useState([]);
  const [showRegisterPopup, setShowRegisterPopup] = useState(false);
  const { Permission: userData } = useAuthProvider();
  const [dataRole, setdataRole] = useState();
  const [newId, setNewId] = useState("");
  const [CarrierId,setCarrierId]= useState("")
  const { data } = useSession();
  const user = useRouter();
  const loggedInUser = data?.user?.id;
  const parentId = data?.user?.parent_id;
  const [isloading, setIsLoading] = useState(false);
  const QuoteOwener = props?.note?.ownerId;
  const HideSelectBtn = QuoteOwener == loggedInUser || parentId;
  const [sortColumn, setSortColumn] = useState("total_price");
  const [sortDirection, setSortDirection] = useState(1);
  const token = data?.user?.image;
  const [process, setProcess] = useState(false);
  const [quoteId, setQuoteId] = useState();
  const [hoveredPlan, setHoveredPlan] = useState(null);
  const [modalStatus, setModalStatus] = useState(false);

  const searchParams = useSearchParams()
  const searchNotificationRoleId = searchParams.get('rateId')

  const userType = data?.user?.group_type;
  const handleShowModal = () => {
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
  };
  const toggleRegisterPopup = (id) => {
    setQuoteId(id);
    setShowRegisterPopup((prev) => !prev);
  };
  const quote = async () => {
    const response = await getDrayageSpotRateQuotes(token, user?.query?.id);

    if (response.status === "success") {
      setProcess(false);
      setdataRole(response);
      setIsLoading(false);
      setSpotsrate(response?.data);
      props?.setRef(false);
    }
  };

  useEffect(() => {
    if (!props?.check) {
      quote();
    }
  }, [showModal, process, props?.refresh, props?.check]);

  const getSpotDetails = async (id: any,carrier_id:any) => {
    setNewId(id);
    
    
    setCarrierId(carrier_id)
    const response: any = await SpotRateQuoteDetails(token, user?.query?.id, id);
    if (response.status === "success") {
      if (response?.data?.assential_service?.length) {
        const clean = (arr: any[]) => arr.filter((v) => v != null && v !== "").join(",");
        const services = response?.data?.assential_service;
        response.data.accessorial_id = clean(services.map((item: { id: any; }) => item?.id));
        response.data.accessorial_cost = clean(services.map((item: { cost: any; }) => item?.cost));
        response.data.accessorial_original_cost = clean(services.map((item: { original_cost: any; }) => item?.original_cost));
        response.data.special_services = clean(services.map((item: { name: any; }) => item?.name));
        response.data.required_for_move = clean(services.map((item: { required_for_move: any; }) => item?.required_for_move));
      }
      setSpotDetail([response?.data]);
    }
  };
  const [showPopups, setShowPopups] = useState(
    Array(spotsrate?.length).fill(false)
  );

  const handleMouseEnter = (index) => {
    const updatedPopups = [...showPopups];
    updatedPopups[index] = true;
    setShowPopups(updatedPopups);
  };

  const DeleteRates = async () => {
    setIsLoading(true);
    let res = await DeleteRate(token, quoteId);
    if (res?.status === "success") {
      toast.success("Rate deleted successfully", {
        position: toast.POSITION.TOP_CENTER,
      });
      toggleRegisterPopup();
      setQuoteId("");
      setProcess(true);
    }
  };
  const getNotificationRateWiseScroll = ()=>{
    if(searchNotificationRoleId){
      const rowId = "tbl_rate_id-"+searchNotificationRoleId;
      const tableElement = document.getElementById(rowId);
      if (tableElement) {
        const topPosition = tableElement.getBoundingClientRect().top + window.scrollY;
        window.scrollTo({ top: topPosition, behavior: "smooth" });
      }
    }
  }

  useEffect(() => {
    getNotificationRateWiseScroll();
  },[spotsrate]);

  useEffect(() => {
    let role =
      dataRole?.data?.some(
        (items) => items.basic_customer_is_rate_closed === 1
      ) || dataRole?.is_rate_send === 1;
    if (role) props?.update(true);
  }, [dataRole]);
  const handleMouseLeave = (index) => {
    const updatedPopups = [...showPopups];
    updatedPopups[index] = false;
    setShowPopups(updatedPopups);
  };
  const renderRateSentButton = (item, index) => {
    const isDisabled =
      data?.user?.is_premium === 0
        ? dataRole?.data?.some(
            (items) =>
              items.basic_customer_is_rate_closed === 1 ||
              dataRole?.is_rate_send === 1
          )
        : dataRole?.data.some(
            (items) => items.basic_customer_is_rate_closed === 1
          ) && data?.user?.is_premium !== 1;

    const handlePlanHover = (plan) => {
      setHoveredPlan(plan);
    };

    const handlePlanLeaveEvent = (e) => {
      setHoveredPlan(null);
    };
    return (
      <>
        <SubscriptionPlansModal
          modalStatus={modalStatus}
          SetModalStatus={setModalStatus}
          userDetails={data?.user}
        />
        {isDisabled && userType != "super_admin" ? (
          <button
            onMouseOver={() => handlePlanHover("avg_chassis")}
            key={index}
            className='btn btn-primary btn-rate-table-all divStylecss-update'
            type='submit'
          >
            Revise
          </button>
        ) : (
          <button
            onMouseEnter={() => handleMouseEnter(index)}
            onMouseLeave={() => handleMouseLeave(index)}
            onClick={() => {
              handleShowModal();
              getSpotDetails(item?.id,item?.carrier_id);
            }}
            key={index}
            className='btn btn-primary btn-rate-table divStylecss-update'
            type='submit'
          >
            Revise
          </button>
        )}
        {hoveredPlan === "avg_chassis" && (
          <div
            onMouseLeave={() => handlePlanLeaveEvent()}
            className='hover-box'
            style={{ bottom: "200px",marginLeft:"-150px" }}
            onClick={() => setModalStatus(true)}
            x-placement='bottom-start'
            aria-labelledby='nav-dropdown'
            className='dropdown-menu show dropdown-menu-lights'
            data-popper-reference-hidden='false'
            data-popper-escaped='false'
            data-popper-placement='bottom-start'
            bis_skin_checked='1'
          >
            <a
              data-rr-ui-dropdown-item=''
              className='dropdown-item'
              role='button'
              tabindex='0'
            
            >
              Available in Draydex Premium
            </a>
          </div>
      )}  
      </>
    );
  };
  const formatEstimatedMargin = (grossMargin) => {
    if (typeof grossMargin === "string") {
      return Number(grossMargin).toFixed(2);
    } else if (typeof grossMargin === "number") {
      return grossMargin.toFixed(2);
    } else {
      return "N/A";
    }
  };

  const renderPopupContent = (item, index) => (
    <div key={index} className='popups'>
      <div className='popup-content'>
        <span className='float'>
          <span>
            <b>Sent Total:</b>
          </span>
          $
          {(() => {
            const estimatedTotal = item?.is_rate_send_data?.estimated_total;

            if (typeof estimatedTotal === "string") {
              return Number(estimatedTotal).toFixed(2);
            } else if (typeof estimatedTotal === "number") {
              return estimatedTotal.toFixed(2);
            } else {
              return "N/A";
            }
          })()}
        </span>

        <br></br>
        <br></br>
        <span className='float'>
          <span className='float'>
            <span>
              <b>Carrier Total:</b>
            </span>
            $
            {(() => {
              const originalTotal = item?.original_total;

              if (typeof originalTotal === "string") {
                return Number(originalTotal).toFixed(2);
              } else if (typeof originalTotal === "number") {
                return originalTotal.toFixed(2);
              } else {
                return "N/A";
              }
            })()}
          </span>
        </span>

        <br></br>
        <br></br>
        <span className='float'>
          <span>
            <b>Estimated Margin:</b>
          </span>
          ${formatEstimatedMargin(item?.is_rate_send_data?.gross_margin)}
        </span>
      </div>
    </div>
  );

  const renderTableRow = (item, index) => {
    const website = item?.website;
    function formatWebsiteLink(site) {
      if (site) {
        return site.startsWith("http") || site.startsWith("https")
          ? site
          : `http://${site}`;
      }
      return "";
    }

    const websiteLink = formatWebsiteLink(website);
    const terms = (e) => {
      e.preventDefault();
      toast.error("No Website Available.", {
        position: toast.POSITION.TOP_CENTER,
      });
    };

    const isRateSendData = item?.is_rate_send_data;
    const numberOfDays = isRateSendData?.number_of_days;

    let backgroundColorClass;

    backgroundColorClass = formatWebsiteLinkScope(
      isRateSendData,
      numberOfDays,
      backgroundColorClass,
      item,
      userType,
      user
    );
    const isRateSend = dataRole?.is_rate_send === 1;
    const hasRateClosed =
      dataRole?.data.some(
        (items) => items.basic_customer_is_rate_closed === 1
      ) || dataRole?.is_rate_send === 1;
    const hidden = isRateSend ? true : false;
    const iconSource = users;
    let userTypeLabel = item?.added_by;
    let fuelPrice;
    fuelPrice = FuelScope(userType, fuelPrice, item);

    let selectButton = selectButtonScope(
      userData,
      props,
      hidden,
      handleShowModal,
      getSpotDetails,
      item,
      hasRateClosed
    );

    let isHidden = keyVerifyHiddenScope(props, userType);

    return jsxContentFnc({
      index,
      backgroundColorClass,
      item,
      userTypeLabel,
      iconSource,
      userType,
      fuelPrice,
      downloadCSV,
      websiteLink,
      terms,
      HideSelectBtn,
      selectButton,
      isHidden,
      toggleRegisterPopup,
      renderRateSentButton,
      showPopups,
      renderPopupContent,
      userData
    });
  };
  const sortData = (columnName) => {
    if (sortColumn === columnName) {
      setSortDirection(-sortDirection);
    } else {
      setSortColumn(columnName);
      setSortDirection(1);
    }
  };

  const sortTableData = () => {
    const sortedData = [...spotsrate];
    sortedData.sort((a, b) => {
      const aValue = a[sortColumn];
      const bValue = b[sortColumn];

      let comparison;
      if (aValue < bValue) {
        comparison = -sortDirection;
      } else if (aValue > bValue) {
        comparison = sortDirection;
      } else {
        comparison = 0;
      }

      if (a.is_rate_send_data && !b.is_rate_send_data) {
        comparison = -1;
      } else if (!a.is_rate_send_data && b.is_rate_send_data) {
        comparison = 1;
      } else if (
        a.basic_customer_is_rate_closed &&
        !b.basic_customer_is_rate_closed
      ) {
        comparison = -1;
      } else if (
        !a.basic_customer_is_rate_closed &&
        b.basic_customer_is_rate_closed
      ) {
        comparison = 1;
      }

      return comparison;
    });
    return sortedData;
  };

  const renderTableRows = () => {
    const sortedData = sortTableData();
    return sortedData.map((item, index) => {
      return renderTableRow(item, index);
    });
  };
  const convertDataToCSV = (datas) => {
    if (
      datas &&
      datas.length > 0 &&
      datas[0] !== null &&
      typeof datas[0] === "object"
    ) {
      const headers = Object.keys(datas[0]).join(",");
      const rows = datas.map((item) => Object.values(item).join(","));
      return `${headers}\n${rows.join("\n")}`;
    }
  };

  const downloadCSV = async (idss) => {
    let res = await CsvData(idss);
    if (res?.data?.length > 0) {
      const csvData = convertDataToCSV(res?.data);

      const blob = new Blob([csvData], { type: "text/csv" });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "Accessorials.csv";
      a.click();
      window.URL.revokeObjectURL(url);
    } else {
      toast.error("No data available to download.", {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };
  let arrowDirection;

  arrowDirection = ArrowScope(sortColumn, arrowDirection, sortDirection);

  const jsxFegment = jsxFegmentMain(data, userType, dataRole);

  return (
    <div className='filter_block border-0'>
      <ToastContainer />
      {jsxFegment()}
      <div className='tabel_top my-3 table-responsive'>
        {spotsrate?.length > 0 ? (
          <table className='table table-bordered'>
            <thead className='table_light'>
              <tr>
                <th scope='col'>
                  Date
                  <i
                    onClick={() => sortData("created_date")}
                    className={`bi bi-arrow-${arrowDirection}`}
                  ></i>{" "}
                </th>
                <th scope='col'>Provided By</th>
                <th scope='col'>
                  Carrier
                  <i
                    onClick={() => sortData("carrier_name")}
                    className={`bi bi-arrow-${arrowDirection}`}
                  ></i>{" "}
                </th>
                <th scope='col'>Rate Summary</th>
                <th scope='col'>Accessorials</th>
                <th scope='col'>
                  Estimated Total
                  <i
                    onClick={() => sortData("total_price")}
                    className={`bi bi-arrow-${arrowDirection}`}
                  ></i>
                </th>
                <th scope='col'>Capacity?</th>
                <th scope='col'>Notes</th>
                {userType !== "carriers" && <th scope='col'></th>}
              </tr>
            </thead>
            <tbody>{renderTableRows()}</tbody>
          </table>
        ) : (
          <div className='text-center'>
            <p style={{ textAlign: "center" }}>No record found</p>
          </div>
        )}
      </div>
      <SubmitRateModal
        show={showModal}
        handleClose={handleCloseModal}
        datas={spotDetails}
        newid={newId}
        queryid={user?.query?.id}
        isButtonShow={dataRole}
        propData={props?.propData}
        setNotify={props?.setNotify}
        CarrId={CarrierId}
      />
      <Modal
        show={showRegisterPopup}
        onHide={toggleRegisterPopup}
        backdrop='static'
      >
        <Modal.Header>
          <Modal.Title> Are you sure you want to delete this Rate?</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className='reg_button'>
            {isloading && (
              <div id='loader_table'>
                <ScaleLoader color='#3180f3' className='table_loader1 ' />
              </div>
            )}
            <Button
              variant='danger'
              className='mx-2 customerButton'
              onClick={() => DeleteRates()}
            >
              Yes
            </Button>
            <Button
              variant='secondary'
              onClick={toggleRegisterPopup}
              className='mx-2 carrierButton'
            >
              No
            </Button>
          </div>
        </Modal.Body>
        <Modal.Footer>
          <div style={{ textAlign: "center" }}></div>
        </Modal.Footer>
      </Modal>
    </div>
  );
}

export default RateTable;


function jsxFegmentMain(data, userType, dataRole) {
  return () => {
    if (checkFegmentContent(data, userType, dataRole)) {
      return handleFegmentContent(dataRole);
    }

    if (checkPremiumScopeFilter(data, userType, dataRole)) {
      return handlePremiumScopeFilter(dataRole);
    }

    if (checkJsxTempLocal(userType, dataRole)) {
      return handleJsxTempLocal(dataRole);
    }

    return "";
  };
}

function checkFegmentContent(data, userType, dataRole) {
  return fegmentContent1(data, userType) && (fegmentContent2(dataRole) || jsxFegment23(dataRole) || jsxContentTernaryDataRole(dataRole));
}

function handleFegmentContent(dataRole) {
  if (fegmentContent2(dataRole)) {
    return newLocal_4;
  } else if (jsxFegment23(dataRole)) {
    return dataRoleReturn1();
  } else if (jsxContentTernaryDataRole(dataRole)) {
    return premiumScopeRender;
  }
  return "";
}

function checkPremiumScopeFilter(data, userType, dataRole) {
  return premiumScopeFilterTer(data, userType) && (scopeFilterFegment2(dataRole) || femScope8(dataRole) || adminFuncScope123(dataRole));
}

function handlePremiumScopeFilter(dataRole) {
  if (scopeFilterFegment2(dataRole)) {
    return fegmentUi;
  } else if (femScope8(dataRole) || adminFuncScope123(dataRole)) {
    return newLocal_2;
  }
  return "";
}

function checkJsxTempLocal(userType, dataRole) {
  return jsxTempLocal12(userType) && (jsxFegment49(dataRole) || jsxFegment23(dataRole) || jsxContentTernaryDataRole(dataRole));
}

function handleJsxTempLocal(dataRole) {
  if (jsxFegment49(dataRole)) {
    return newLocal_2;
  } else if (jsxFegment23(dataRole)) {
    return returnFegment23();
  } else if (jsxContentTernaryDataRole(dataRole)) {
    return returnTernaryRole32;
  }
  return "";
}

function dataRoleReturn1() {
  return fegmentUi;
}

function returnFegment23() {
  return newLocal_3;
}

function jsxFegment49(dataRole: undefined) {
  return dataRole?.is_rate_send === 1;
}

function jsxFegment23(dataRole: undefined) {
  return dataRole?.data?.some(
    (items) => items.basic_customer_is_rate_closed === 1
  ) &&
    dataRole?.is_rate_send !== 1;
}

function scopeFilterFegment2(dataRole: undefined) {
  return dataRole?.data?.some(
    femScope6(dataRole)
  );
}

function jsxContentTernaryDataRole(dataRole: undefined) {
  return dataRole?.data?.some(
    (items) => items.basic_customer_is_rate_closed === 1
  ) &&
    dataRole?.is_rate_send === 1;
}

function jsxTempLocal12(userType: any) {
  return userType === "super_admin" && userType != "carriers";
}

function premiumScopeFilterTer(data, userType: any) {
  return data?.user?.is_premium === 0 && userType != "super_admin" && userType != "carriers";
}

function adminFuncScope123(dataRole: undefined) {
  return dataRole?.data?.some(
    (items) => items.basic_customer_is_rate_closed === 0 &&
      dataRole?.is_rate_send === 1
  );
}

function femScope8(dataRole: undefined) {
  return dataRole?.data?.some(
    (items) => items.basic_customer_is_rate_closed === 1 &&
      dataRole?.is_rate_send === 1
  );
}

function femScope6(dataRole: never): any {
  return (items) => items.basic_customer_is_rate_closed === 1 &&
    dataRole?.is_rate_send === 0;
}


function fegmentContent2(dataRole: undefined) {
  return dataRole?.is_rate_send === 1;
}

function fegmentContent1(data, userType: any) {
  return data?.user?.is_premium === 1 && userType != "super_admin" && userType != "carriers";
}

function jsxContentFnc({
  index,
  backgroundColorClass,
  item,
  userTypeLabel,
  iconSource,
  userType,
  fuelPrice,
  downloadCSV,
  websiteLink,
  terms,
  HideSelectBtn,
  selectButton,
  isHidden,
  toggleRegisterPopup,
  renderRateSentButton,
  showPopups,
  renderPopupContent,
  userData
}: {
  index: any;
  backgroundColorClass: any;
  item: any;
  userTypeLabel: any;
  iconSource: any;
  userType: any;
  fuelPrice: any;
  downloadCSV: (idss: any) => Promise<void>;
  websiteLink: any;
  terms: (e: any) => void;
  HideSelectBtn: any;
  selectButton: string;
  isHidden: boolean;
  toggleRegisterPopup: (id: any) => void;
  renderRateSentButton: (item: any, index: any) => JSX.Element;
  showPopups: any[];
  renderPopupContent: (item: any, index: any) => JSX.Element;
  userData: any;
}) {
  return (
    <tr key={index} id={`tbl_rate_id-${item.id}`}>
      <td className={backgroundColorClass} scope='row'>
        <div>{item?.created_date}</div>
      </td>

      <td className={backgroundColorClass}>
        {insideJsx(item, userTypeLabel, iconSource)}
      </td>
      <td className={backgroundColorClass}>
        <a target='_blank' href={`/carriers/${item?.carrier_id}`}>
          {item?.billing_company}
        </a>
      </td>
      <td className={backgroundColorClass}>
        <div>
          <Row>
            <Col className='d-flex text-end flex-column span-text-market'>
              <span>
                Linehaul:
                <span>
                  <span style={{ color: "black" }}>
                    $
                    {userType === "carriers"
                      ? Number(item?.original_linehaul).toFixed(2)
                      : Number(item?.linehaul).toFixed(2)}
                  </span>
                </span>
              </span>
              <span>
                Fuel (
                {userType === "carriers"
                  ? Number(item?.original_fsc).toFixed(2)
                  : Number(item?.fuel_surcharge_percent).toFixed(2)}
                %):
                <span>{fuelPrice}</span>
              </span>
              <span>
                Chassis({item?.per_day} day minimum):
                <span>
                  $
                  {userType === "carriers"
                    ? Number(item?.original_chasis).toFixed(2)
                    : Number(item?.chessis_price).toFixed(2)}
                </span>
              </span>
            </Col>
          </Row>
        </div>
      </td>
      <td className={`${backgroundColorClass}`}>
        <div>
          <div>
            <Col className='d-flex text-end flex-column span-text-market toolTipRates'>
              {insideJsx1(item, userType, index)}
            </Col>
          </div>

          <div className='d-flex'>
            <Col>
              <div
                onClick={() => downloadCSV(item?.carrier_id)}
                className='span-div'
              >
                <i className='bi bi-tag-fill'></i>
                <span>Accessorials</span>
              </div>
            </Col>
            <Col>
              {item?.website ? (
                <div className='span-div'>
                  <a
                    className='bi bi-journal-richtext'
                    style={{
                      textDecoration: "none",
                      color: "#ff9800",
                    }}
                    href={websiteLink}
                    target='_blank'
                    rel='noopener noreferrer'
                  >
                    <span>Terms</span>
                  </a>
                </div>
              ) : (
                <p
                  className='bi bi-journal-richtext'
                  style={{
                    textDecoration: "none",
                    color: "#ff9800",
                  }}
                  onClick={(e) => terms(e)}
                  target='_blank'
                  rel='noopener noreferrer'
                >
                  <span
                    style={{
                      cursor: "pointer",
                    }}
                  >
                    Terms
                  </span>
                </p>
              )}

              {/* )} */}
            </Col>
          </div>
        </div>
      </td>
      <td className={backgroundColorClass}>
        <p className='totalprice'>
          $
          {userType === "carriers"
            ? Number(item.original_total).toFixed(2)
            : Number(item.total_price).toFixed(2)}
        </p>
      </td>
      <td className={backgroundColorClass}>
        <div>
          <p>
            {item?.has_capacity === 0 ? "No" : "Yes"}
            <br />
            {item?.has_capacity === 1 ? item?.earliest_capacity : ""}
          </p>
          <p></p>
        </div>
      </td>
      <td className={`${backgroundColorClass} align-middle`}>
        <div className='info-icon-table'>
          <i
            className='bi bi-info-circle-fill'
            data-toggle='tooltip'
            data-placement='top'
            title={item?.rate_notes}
          ></i>
        </div>
      </td>
      {(userType === "super_admin" ||
        (userType === "customers" && HideSelectBtn)) && (
        <td className={`${backgroundColorClass} align-middle`}>
          <div>
            {item?.is_rate_send_data === 0 &&
            item.basic_customer_is_rate_closed !== 1 ? (
              <>
                <div className='gap-select'>
                  {selectButton}
                  {userData?.DeleteRate == 'Delete Rate' && (
                    <button
                      className='btn btn-primary btn-rate-table'
                      type='submit'
                      style={{ width: "max-content" }}
                      onClick={() => toggleRegisterPopup(item?.id)}
                    >
                      Delete
                    </button>
                  )}
                </div>
              </>
            ) : (
              <div key={index} className='popup-container'>
                {renderRateSentButton(item, index)}

                {showPopups[index] && renderPopupContent(item, index)}
              </div>
            )}
          </div>
        </td>
      )}
    </tr>
  );
}

function insideJsx1(item: any, userType: any, index: any): React.ReactNode {
  return item?.assential_services?.map((item1, index3) => {
    const costsForMove1 = item?.assential_services
      .filter((service) => service.required_for_move === 1)
      .map(
        (service2) =>
          `$${
            userType === "carriers"
              ? Number(service2.original_cost).toFixed(2)
              : Number(service2.cost).toFixed(2)
          }`
      );

    const costsForMove0 = item?.assential_services
      .filter((service) => service.required_for_move === 0)
      .map(
        (service) =>
          `$${
            userType === "carriers"
              ? Number(service.original_cost).toFixed(2)
              : Number(service.cost).toFixed(2)
          }`
      );
    const costName = item?.assential_services
      .filter((service) => service.required_for_move === 0)
      .map((service) => service.name);

    const costName2 = item?.assential_services
      .filter((service) => service.required_for_move === 1)
      .map((service) => service.name);
    let costText;
    if (userType === "carriers") {
      costText = item1?.original_cost
        ? `:$${Number(item1.original_cost).toFixed(2)}`
        : ": No Cost Found";
    } else {
      costText = item1.cost
        ? `:$${Number(item1.cost).toFixed(2)}`
        : ": No Cost Found";
    }
    return (
      <div className='' data-toggle='tooltip' data-placement='top' key={index}>
        <ul className='dropdown-tooltip' aria-labelledby='dropdownMenu2'>
          {costsForMove1?.length > 0 && (
            <p>
              <strong>Applicable Accessorials:</strong>
            </p>
          )}

          <div
            className='items_tooltip'
            style={{ display: "flex", gap: "10px" }}
          >
            <div>{costName2?.map((i) => <p>{i}</p>)}</div>

            <div>{costsForMove1?.map((i) => <p>{i}</p>)}</div>
          </div>
          {costsForMove0?.length > 0 ? (
            <p>
              <strong>Other Accesorials may include:</strong>
            </p>
          ) : (
            ""
          )}
          <div
            className='items_tooltip'
            style={{ display: "flex", gap: "10px" }}
          >
            <div>{costName?.map((i) => <p>{i}</p>)}</div>
            <div>{costsForMove0?.map((i) => <p>{i}</p>)}</div>
          </div>
        </ul>

        <span>
          {item1.name}
          <span>{costText}</span>
        </span>
      </div>
    );
  });
}

function insideJsx(
  item: any,
  userTypeLabel: any,
  iconSource: any
): React.ReactNode {
  return item?.user_type === "carriers" ? (
    <>
      <Image
        className='bi bi-info-circle-fill'
        style={{
          height: "35px",
          width: "35px",
          cursor: "pointer",
        }}
        src={carriersLogo}
        alt=''
      />
      <p>{userTypeLabel}</p>
    </>
  ) : (
    <>
      <Image
        className='bi bi-info-circle-fill'
        style={{
          height: "30px",
          width: "30px",
          cursor: "pointer",
        }}
        src={iconSource}
        alt=''
      />
      <p>{userTypeLabel}</p>
    </>
  );
}

function keyVerifyHiddenScope(props: any, userType: any) {
  let isHidden;
  if (props?.keyVerify) {
    isHidden = false;
  } else if (userType === "super_admin") {
    isHidden = false;
  } else {
    isHidden = true;
  }
  return isHidden;
}

function selectButtonScope(
  userData: undefined,
  props: any,
  hidden: boolean,
  handleShowModal: () => void,
  getSpotDetails: (id: any) => Promise<void>,
  item: any,
  hasRateClosed
) {
  let selectButton = "";
  if (userData?.SelectCarrierrate) {
    selectButton = (
      <button
        hidden={props?.keyVerify ? false : true}
        className='btn btn-primary btn-rate-table'
        type='submit'
        hidden={hidden || hasRateClosed}
        onClick={() => {
          handleShowModal();
          getSpotDetails(item?.id,item?.carrier_id);
        }}
      >
        select
      </button>
    );
  }
  return selectButton;
}

function FuelScope(userType: any, fuelPrice: any, item: any) {
  if (userType === "carriers") {
    fuelPrice = item?.original_linehaul_fuel_percent_price
      ? `$${Number(item.original_linehaul_fuel_percent_price).toFixed(2)}`
      : "";
  } else {
    fuelPrice = item?.linehaul_fuel_percent_price
      ? `$${Number(item.linehaul_fuel_percent_price).toFixed(2)}`
      : "";
  }
  return fuelPrice;
}

function formatWebsiteLinkScope(
  isRateSendData: any,
  numberOfDays: any,
  backgroundColorClass: any,
  item: any,
  userType: any,
  user: any
) {
  

  if (isRateSendData && numberOfDays > 30) {
    backgroundColorClass = "red-class";
  } 
  else if (Number(user?.query?.rateId) === item?.id) { // Convert rateId to number
    // Scroll to the bottom of the window
    backgroundColorClass = " blink-animation"; // Apply blink class and initial green color
  }   else if (
    isRateSendData ||
    (item?.basic_customer_is_rate_closed === 1 && userType !== "carriers")
  ) {
    backgroundColorClass = "success-class";
  } else {
    backgroundColorClass = "";
  }

  return backgroundColorClass;
}


function ArrowScope(
  sortColumn: string,
  arrowDirection: any,
  sortDirection: number
) {
  if (sortColumn === "created_date") {
    arrowDirection = sortDirection === 1 ? "down" : "up";
  } else if (sortColumn === "carrier_name") {
    arrowDirection = sortDirection === 1 ? "down" : "up";
  } else if (sortColumn === "total_price") {
    arrowDirection = sortDirection === 1 ? "down" : "up";
  } else {
    arrowDirection = "down-up";
  }
  return arrowDirection;
}
