
import React, { useState, useEffect } from "react";
import Head from "next/head";
import Layout from "@/components/layouts/Layout";
import { Typeahead } from "react-bootstrap-typeahead";
import ViewLog from "./ViewLog";
import "react-bootstrap-typeahead/css/Typeahead.css";
import RateTable from "@/components/ui/detailsRateQuotes/rate-Table";
import loads from "@/assets/loads";
import { ScaleLoader } from "react-spinners";
import { googleAddressActionUrl, toValidDigitNumber } from "@/helpers/projectHelper";
import Image from "next/image";
import alert from "../../public/alert.png"
import { useCollapsed } from "@/components/Context/CollapsedContext"; 

import {
  CustomerChildAdd,
  GetId,
  GetDetails,
} from "@/services/profile";
import {
  updateRate,
  getPorts,
  voidRates,
  getDashboardTerminals,
  CarrierTableFindAll,
} from "@/services/public";
import { Form, Row, Col, FormLabel, Modal, Button } from "react-bootstrap";
import AddRateModal from "@/components/ui/modal/AddRateModal";
import SendCarriersModal from "@/components/ui/modal/SendCarriersModal";
import UpdateQuteModal from "@/components/ui/modal/UpdateQuteModal";
import { ToastContainer, toast } from "react-toastify";
import {
  equipments,
  sub_specialServices,
} from "@/helpers/constants/static/values";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import {
  GetHazClasses,
  StreamLineSsl,
  storeViewlog,
} from "../../services/public";
import CustomerBadge from "../../components/ui/form/CustomerBadge";
import useAuthProvider from "@/useAuthProvider";
import { processResponseData } from "@/helpers/geolocationParsingUtils";
import { Suggestion } from "@/interfaces/Maps";

interface ServerSideProps {
  rateQuotesId: number;
  RateQuotesdetails: any;
}
const RateQuoteDetail = (props: ServerSideProps) => {
  const [allObject, setAllObject] = useState();
  const [initialclass, setInitialclass] = useState("");
  const [initialun_number, setInitialun_number] = useState("");
  const { data } = useSession();
  const { Permission: userData } = useAuthProvider();
  const userType = data?.user?.group_type;
  const Router = useRouter();
  const ownerId = allObject?.user_id;
  const logeduserId = data?.user?.id;
  const parentId = data?.user?.parent_id;
  const Id = Router?.query?.id;
  const tokens = data?.user?.image;
  const [marketValue, setMarketValue] = useState();
  const [sendMarketTerminal, setSendMarketTerminal] = useState(false);
  const [searchedSuggestions, setSearchSuggestions] = useState<Suggestion[]>([]);
  const [voids, setVoids] = useState(false);
  const [disable, setDisable] = useState(false);
  const [getUpdate, setUpdate] = useState();
  const [marketLat, setMarketLat] = useState("");
  const [marketLng, setMarketLng] = useState("");
  const [selectedOriginDestination, setSelectedOriginDestination] =
    useState("");
  const [dieselPrice] = useState();
  const [portsData, setPortsData] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [edit, setEdit] = useState(false);
  const [load, setLoad] = useState(false);
  const [highlightedLi, setHighlightedLi] = useState(null);
  const [showCarrierModal, setShowCarriersModal] = useState(false);
  const [showUpdateQuoteModal, setShowUpdateQuoteModal] = useState(false);
  const [classhaz, setClasshaz] = useState([]);
  const [keyf, setKey] = useState("");
  const [pickupenable, setPickupenable] = useState(false);
  const [deliveryenable, setDeliveryenable] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [streamlinelist, setStreamlinelist] = useState([]);
  const [suggestedstreamline, setSuggestedstreamline] = useState([]);
  const [enableFalse, setEnabeFalse] = useState(false);
  const [propData, setPropData] = useState([]);
  const [check, setCheck] = useState()
  const [refresh,setRefresh] = useState(false)
  const [selectedSpecialServices, setSelectedSpecialServices] = useState<
    { service_name: string; service_code: string }[]
  >([]);
  const accessToken = data?.user?.image;
  const [showRegisterPopup, setShowRegisterPopup] = useState(false);
  const [terminallistvalue, setTerminals] = useState([]);
  const [stremValue, setStremValue] = useState<any>();
  const [orignerror, setOriginerror] = useState(false);
  const [initialpayload, setInitialpayload] = useState("");
  const [sendVar, setSendVar] = useState({});
  const [takeInput, setTakeInput] = useState("");
  const [isViewLogOpen, setViewLogOpen] = useState(false);
  const [isloading, setIsloading] = useState(false);
  const [info, SetInfo] = useState(false);
  const [username, setUserName] = useState()
  const [notify,setNotify]= useState();
  const [checkTerminalChangeStatus, setCheckTerminalChangeStatus] = useState(false);
  const [addRateModalCount, setAddRateModalCount] = useState(0);

  const toggleRegisterPopup = () => {
    setShowRegisterPopup((prev) => !prev);
  };
  useEffect(() => {
    GetHazClasses().then((response) => {
      if (response.status == "success") {
        setClasshaz(response.data);
      }
    });
  }, []);

  useEffect(() => {
    StreamLineSsl(accessToken).then((response) => {
      if (response.status == "success") {
        setStreamlinelist(response.data);
      }
    });
  }, [accessToken]);
  const customToastStyle = {
    width: "450px",
  };
  useEffect(() => {
    if (check === false) {
      getPorts().then((response) => {
        if (response.status == "success") {
          setPortsData(response.data);
        }
      });
    }

  }, [setPortsData, check]);
  useEffect(() => {
    if (allObject?.pickup_date) {
      setPickupenable(true);
    }
    if (allObject?.delivery_date) {
      setDeliveryenable(true);
    }
  }, [allObject?.delivery_date, allObject?.pickup_date]);
  useEffect(() => {
    const fetchData = async () => {
      setIsloading(true)
      setSendMarketTerminal(true);
      setCheckTerminalChangeStatus(true);
      try {
        
        if (check === false) {
          if (tokens && Router?.query?.id) {
            const apiResponse = await GetDetails(tokens, Router?.query?.id);
            setPropData(apiResponse);
            if (apiResponse?.status == "success") {
              setIsloading(false)
              setSendMarketTerminal(false);
              setSelectedSpecialServices(apiResponse.data.services);
              setInitialpayload(apiResponse.data);
              setSendVar({
                chaild: apiResponse?.data?.child_c_name,
                selesRef: apiResponse?.data?.sales_rep,
                childId: apiResponse?.data?.child_id,
              });
              setAllObject((prevData) => ({
                ...prevData,
                ...apiResponse?.data,
              }));
              setKey(apiResponse?.data?.market_name);
              setInitialclass(apiResponse?.data?.class);
              setInitialun_number(apiResponse?.data?.un_number);
              setSelectedOriginDestination(
                apiResponse?.data?.origin_destination_full,
              );
              setStremValue([apiResponse?.data?.ssls?.ssac_code]);
              setLoad(false);
              setCheckTerminalChangeStatus(false);
            }
          }
        }
      } catch (error) {
        return error;
      }
    };  
    const getIdsAndFetchData = async () => {
      setIsloading(true)
      await getIds();
      fetchData();
    };

    getIdsAndFetchData();
  }, [data?.user && tokens, Router?.query, enableFalse, load, streamlinelist, check]);

  const getIds = async () => {
    let res = await GetId(tokens);
    const idFromQuery = Router?.query?.id;
    if (
      idFromQuery &&
      res?.data &&
      res.data.includes(parseInt(idFromQuery, 10))
    ) {
      toast.error("This Quote Has been Blocked", {
        position: toast.POSITION.TOP_CENTER,
      });
      SetInfo(true);
      Router.push("/dashboard");
    }
  };

  const handleStreamlineInputChange = (event: any) => {
    const inputvalue = event?.target?.value.toLowerCase();
    const showhidesuggestion = inputvalue.length > 0 ? true : false;
    const filteredData = streamlinelist?.filter((item) => {
      const carrierName = item?.name?.toLowerCase();
      const carrierNameAbbr = item?.abbreviation?.toLowerCase();
      const scac = item?.ssac_code?.toLowerCase();
      return (
        carrierName?.includes(inputvalue) ||
        carrierNameAbbr?.includes(inputvalue) ||
        scac?.includes(inputvalue)
      );
    });
    setSuggestedstreamline(filteredData);
    setStremValue(event?.target?.value);
    setShowSuggestions(showhidesuggestion);
  };
  const handleDropdownstreamlineClick = (itemstreamline: any) => {
    
    if (itemstreamline?.ssac_code?.length > 0) {
      setEdit(true);
    } else {
      setEdit(false);
    }
    setStremValue(itemstreamline?.ssac_code);
    setShowSuggestions(false);
    setAllObject((prevData) => ({
      ...prevData,
      ssl_id: itemstreamline?.id,
      scac_code: "",
    }));
  };
  const handleInputChange = (event) => {
    event.preventDefault();
    const { name, value } = event.target;
    if (name === "weight") {
      if (value === '' || toValidDigitNumber(value)) {
        setAllObject((prevData) => ({
          ...prevData,
          [name]: value,
        }));
      }
      const isValuePresent = value?.length > 0;
      setEdit(isValuePresent);
      return;
    }
  
    if (name === "carrier_equipment_code" && value === "reefer") {
      const isReeferAdded = selectedSpecialServices.some(
        (service) => service.service_code === "reefer"
      );
  
      if (!isReeferAdded) {
        setSelectedSpecialServices((prevServices) => [
          ...prevServices,
          { service_code: "reefer", service_name: "REEFER" }
        ]);
      }
    }
  
    const isValuePresent = value?.length > 0;
    setEdit(isValuePresent);
    if (name === "class" && value === "") {
      setEdit(true);
    }
    setAllObject((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };
  
useEffect(() => {
  if (allObject?.carrier_equipment_code === "reefer") {
    const isReeferAdded = selectedSpecialServices.some(
      (service) => service.service_code === "reefer"
    );

    if (!isReeferAdded) {
      selectedSpecialServices.push({
        service_code: "reefer",
        service_name: "REEFER",
      });
    }
  }
}, [allObject]);
  const handleTerminalInputChange = ({
    target: { value, options },
  }: React.ChangeEvent<HTMLSelectElement>) => {
    if (value?.length > 0) {
      setEdit(true);
    } else {
      setEdit(false);
    }
    const selectedOption = options[options.selectedIndex];
    const option = selectedOption.getAttribute("name");
    setAllObject((prevData) => ({
      ...prevData,
      terminal_id: (value == "Please select") ? null : value,
      terminals: option,
    }));
  };

  const handleUnInputChange = (event: any) => {
    const { value } = event.target;
    const truncatedValue = value.slice(0, 4);

    if (truncatedValue.length >= 4) {
      setEdit(true);
    } else {
      setEdit(false);
    }

    setAllObject((prevData) => ({
      ...prevData,
      un_number: truncatedValue,
    }));
  };
  const handlecomodityInputChange = (event: any) => {
    const { value } = event.target;
    const truncatedValue = value.slice(0, 50);
    if (truncatedValue.length > 0) {
      setEdit(true);
    } else {
      setEdit(false);
    }

    setAllObject((prevData) => ({
      ...prevData,
      commodity: truncatedValue,
    }));
  };
  const handleMarketInputChange = (event: any) => {
    const { value } = event.target;
    const changeValue = value ? JSON?.parse(value) : "";
    setMarketLat(changeValue?.lat);
    setMarketLng(changeValue?.lng);
    try {
      if (value?.length > 0) {
        setKey(changeValue.name);
        setEdit(true);
        setMarketValue(changeValue.name);
        setAllObject((prevData) => ({
          ...prevData,
          port_id: changeValue.id,
          port_name: changeValue.name,
        }));
      } else {
        setEdit(false);
      }
    } catch (error) {
      setEdit(false);
    }
  };
  const handleShowModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setAddRateModalCount(addRateModalCount => addRateModalCount+1)
    setShowModal(false);
  };
  const handleCarriersShowModal = () => {
    setShowCarriersModal(true);
  };
  const handleUpdateQuoteShowModal = () => {
    setShowUpdateQuoteModal(true);
  };
  useEffect(() => {
    const payload = {
      market: [keyf],
    };
    getDashboardTerminals(tokens, payload).then((response) => {
      if (response.status == "success") {
        const selectedArchivedTerminal = { id: allObject?.terminal_id, market:allObject?.market_name, name: allObject?.terminals }
        const terminalsWithExtra: any = response.data;
        const marketExists = terminalsWithExtra.some(
          (item: { market: any; }) => item.market === selectedArchivedTerminal.market
        );
        const fullMatchExists = terminalsWithExtra.some(
          (item: { market: any; name: any; }) => item.market === selectedArchivedTerminal.market && item.name === selectedArchivedTerminal.name
        );
        if (response.data.length > 0 && marketExists && !fullMatchExists && allObject?.terminals) {
            terminalsWithExtra.push(selectedArchivedTerminal);
        }
        setTerminals(terminalsWithExtra);
      }
    });
  }, [keyf, checkTerminalChangeStatus]);
  const handleCarriersCloseModal = () => {
    setShowCarriersModal(false);
  };
  const handleUpdateQuoteCloseModal = () => {
    setShowUpdateQuoteModal(false);
  };
  async function getAddressSuggestions(event: any) {
    try {
      const searchedString = event.target.value;
      const validationerror = searchedString.length > 0 ? false : true;
      setOriginerror(validationerror);

      if (searchedString.length > 1) {
        const searchResponse = await fetch(
          googleAddressActionUrl(searchedString),
        );
        const searchedResponseData = await searchResponse.json();
        const suggestionsArray = processResponseData(searchedResponseData?.results);
        setSearchSuggestions(suggestionsArray);
      } else {
        setSearchSuggestions([]);
      }
    } catch (error) {
      setSearchSuggestions([]);
    }
  }

  const CustomerButtons = () => (
    <>
      {userData?.SendRatetoCarrier ? <SendToCarriersButton onClick={handleCarriersShowModal} /> : ""}
      {
        userData?.RateQuoteAddRate ? <AddRateButton onClick={handleShowModal} /> : ""
      }
      {userData?.RateQuoteUpdateChanges ? <UpdateChangesButton
        disabled={disable || !edit}
        onClick={updateChanges}
      /> : ""}

      {userData?.ViewVoidQuote ? <VoidQuoteButton disabled={isDisabled} onClick={toggleRegisterPopup} /> : ""}
    </>
  );

  const renderCarrierButtons = () => (
    <AddRateButton onClick={handleShowModal} />
  );


  const renderButtons = () => {
    switch (userType) {
      case "customers":
        return (ownerId === logeduserId) || (ownerId === parentId) ? CustomerButtons() : "";
      case "carriers":
        return renderCarrierButtons();
      case "super_admin":
        return CustomerButtons();
      default:
        return null;
    }
  };

  function formatDestinationAddress(
    cityName: any,
    stateCode: any,
    zipCodeNumber: any,
  ) {
    let formattedAddress = cityName;
    if (stateCode) {
      formattedAddress += `, ${stateCode}`;
      if (zipCodeNumber) {
        formattedAddress += `, ${zipCodeNumber}`;
      }
    }
    return formattedAddress;
  }

  function cityNameOfValue(cityValue: any, fullItemValue: any) {
    if (cityValue) {
      return cityValue;
    } else if (
      fullItemValue?.name[0]?.city === "" &&
      fullItemValue?.name[0]?.state === ""
    ) {
      return fullItemValue?.name[0]?.zip_code;
    } else {
      return "";
    }
  }

  function stateNameOfValue(
    stateValue: any,
    fullItemValue: any,
    cityName: any,
  ) {
    if (stateValue) {
      return fullItemValue?.state_code;
    } else {
      if (fullItemValue?.name[0]?.zip_code !== cityName) {
        return fullItemValue?.name[0]?.zip_code;
      } else {
        return "";
      }
    }
  }

  function bindSelectedAddress(item: any) {
    const cityName = cityNameOfValue(item?.name[0]?.city, item);
    const stateCodeName = stateNameOfValue(
      item?.name[0]?.state,
      item,
      cityName,
    );
    // Validate ZIP/postal code (including Canadian format)
    const zipCodeNumber = /^[A-Za-z0-9\s]+$/.test(item?.name[0]?.zip_code)
    ? item?.name[0]?.zip_code
    : "";
    const finalDestinationName = formatDestinationAddress(
      cityName,
      stateCodeName,
      zipCodeNumber,
    );
    setSearchSuggestions([]);
    setSelectedOriginDestination(finalDestinationName);
    setEdit(true);
    const { state_code, lat, lng } = item;
    let stateCode = "";
    if (state_code) {
      const codeParts = state_code;
      if (codeParts) {
        stateCode = codeParts;
      }
    }
    setAllObject((prevData) => ({
      ...prevData,
      origin_destination: finalDestinationName,
      origin_city: item?.name[0]?.city?.trim(),
      origin_state_code: stateCode,
      origin_lat: lat || "",
      origin_lng: lng || "",
    }));
  }
  const handleChildAdd = async (Addtokens, AddtakeInput) => {
    const addChildPayload = {
      customer: AddtakeInput.customer,
      sales_rep: AddtakeInput.sales_rep?.trim() 
        ? AddtakeInput.sales_rep 
        : data?.user?.name,
    };
    const response = await CustomerChildAdd(Addtokens, addChildPayload);
    if (response.status === "success") {
      toast.success(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      return response.data;
    } else {
      toast.error(response.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      return null;
    }
  };

  const handleChild = async (childTokens, childInput) => {
    if (childInput?.enableBool) {
      const newData = await handleChildAdd(childTokens, childInput);
      if (newData) {
        setEnabeFalse(true);
        return newData;
      }
    } 
    return null;
  };

  const calculateRoundtripDistance = async (DistancemarketLng, DistancemarketLat, DistanceallObject) => {
    try {
      const turfModule = await import("@turf/turf");
      const point1 = turfModule.point([
        DistancemarketLng || DistanceallObject?.port_lon,
        DistancemarketLat || DistanceallObject?.port_lat,
      ]);
      const point2 = turfModule.point([
        DistanceallObject?.origin_lng,
        DistanceallObject?.origin_lat,
      ]);
      const oneWayDistance = turfModule.distance(point1, point2);
      return oneWayDistance * 2;
    } catch (error) {
      return null;
    }
  };

  const createStoreData = (StoreallObject, StorenewData, StoretakeInput, StoreoriginZip, StoreselectedServicenames, StoreselectedOriginDestination) => ({
    ...StoreallObject,
    origin_zip: StoreoriginZip,
    special_services: [StoreselectedServicenames.join(", ")],
    port_id: StoreallObject.port_id || determinePortId(),
    loading_or_onloading_date: StoreallObject.delivery_date,
    equipment: StoreallObject.carrier_equipment_code,
    size: StoreallObject.length,
    type: StoreallObject.load_type_code,
    port_name: StoreallObject.port_name,
    child_customer_id: StorenewData ? StorenewData?.id : StoretakeInput?.child_customer_id,
    origin_destination: StoreselectedOriginDestination,
  });

  const createUpdatedData = (dataObjects, additionalParams) => {
    const {
      allObject: ao,
      newData: nd,
      takeInput: ti
    } = dataObjects;

    const {
      selectedServiceCodes: ssc,
      originZip: oz,
      roundtripDistance: rtd,
      marketValue: mv,
      username: un,
      selectedOriginDestination: sod
    } = additionalParams;

    const baseData = {
      ...ao,
      weight: ao.weight && !isNaN(Number(ao.weight))
      ? Number(ao.weight).toFixed(2)
      : '',
      special_services: ssc,
      port_id: ao.port_id || determinePortId(),
      loading_or_onloading_date: ao.delivery_date,
      equipment: ao.carrier_equipment_code,
      size: ao.length,
      type: ao.load_type_code,
      port_name: ao.port_name,
      sales_rep: ti?.sales_rep,
      child_customer_id: nd ? nd.id : ti?.child_customer_id,
      round_trip_miles: rtd,
      market: mv,
      market_name: mv,
      origin_destination_full: sod,
      origin_destination: sod,
    };

    if (ao.load_type_code === "export") {
      return {
        ...baseData,
        origin_city: ao.origin_city,
        origin_state_code: ao.origin_state_code,
        origin_lat: ao.origin_lat,
        origin_lng: ao.origin_lng,
        origin_zip: originZipCodeName(oz, ao.origin_zip),
      };
    } else {
      return {
        ...baseData,
        destination_city: ao.origin_city,
        destination_state_code: ao.origin_state_code,
        destination_lat: ao.origin_lat,
        destination_lng: ao.origin_lng,
        destination_zip: originZipCodeName(oz, ao.origin_lng),
      };
    }
  };


  const updateChanges = async () => {
    setDisable(true);
    const newData = await handleChild(tokens, takeInput);
    const originZip = extractOriginZip(selectedOriginDestination);
    const selectedServiceCodes = extractServiceCodes(selectedSpecialServices);
    const selectedServicenames = extractServiceNames(selectedSpecialServices);
    const roundtripDistance = await calculateRoundtripDistance(marketLng, marketLat, allObject);

    if (roundtripDistance === null) {
      return new Error("Failed to calculate distance");
    }

    const storeData = createStoreData(allObject, newData, takeInput, originZip, selectedServicenames, selectedOriginDestination);
    const dataObjects = { allObject, newData, takeInput };
    const additionalParams = { selectedServiceCodes, originZip, roundtripDistance, marketValue, username, selectedOriginDestination };

    const updatedData = createUpdatedData(dataObjects, additionalParams);
    if (!orignerror) {
      setIsloading(true);
      const res = await updateRate(tokens, updatedData, Id);
      setIsloading(false);
      handleResponse(res, storeData);
    } else {
      setDisable(true);
      toast.error("OriginDestination is required.", {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };

  function originZipCodeName(originZipData: any, allObjectOriginZipData: any) {
    let resolvedOriginZip;
    if (originZipData) {
      resolvedOriginZip = originZipData === "not-zip-code" ? "" : originZipData;
    } else {
      resolvedOriginZip = allObjectOriginZipData;
    }
    return resolvedOriginZip;
  }
  function extractOriginZip(originDestination) {
    var numberOnly = originDestination.replace(/\D/g, "");
    if (numberOnly) {
      const zipCodeRegex = /\b\d{5}\b/;
      const match = zipCodeRegex.exec(originDestination);
      return match ? match[0] : "";
    } else {
      return "not-zip-code";
    }
  }
  function extractServiceCodes(selectedSpecialServices1) {
    return selectedSpecialServices1.map((service) => service.service_code);
  }
  function extractServiceNames(selectedSpecialServices1) {
    return selectedSpecialServices1.map((service) => service.service_name);
  }
  function determinePortId() {
    if (!allObject.port_id && !allObject.destination_port_id) {
      return allObject.origin_port_id;
    } else if (!allObject.port_id && !allObject.origin_port_id) {
      return allObject.destination_port_id;
    }
    return null;
  }
  async function handleResponse(res: any, submitiedpayload: any) {
    if (res?.status === "success") {
      const formattedArray = [
        initialpayload?.services
          .map((service) => service.service_name)
          .join(", "),
      ];
      await storeViewlog(
        tokens,
        loads(Id, initialpayload, submitiedpayload, formattedArray),
      );

      setDisable(false);
      setEdit(false);
      handleUpdateQuoteShowModal();
    } else if (res?.status === "error") {
      toast.error(res?.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      setIsloading(false)
      setEdit(false);
      setDisable(false);
    }
  }
  const showToast = (message, type) => {
    toast[type](message, {
      position: toast.POSITION.TOP_CENTER,
    });
  };

  const handleSuccess = () => {
    toggleRegisterPopup();

    setVoids(true);
  };

  const handleFailure = (message) => {
    toggleRegisterPopup();

    setVoids(false);
    showToast(message, "error");
  };

  const HandleVoid = async () => {
    setVoids(true);
    let res = await voidRates(tokens, Router?.query?.id);

    if (res?.message === "Quote doesn't exist.") {
      handleFailure(res?.message);
    } else if (res?.message === "Quote has been deleted successfully") {
      handleSuccess();
      showToast(res?.message, "success");
    }

    Router.push("/dashboard");
  };
  const sendCarriersClassName = sendCarriersClassNameScope1(getUpdate);
  const buttonClassName = edit ? "btn btn-orange divStylecss-update" : "btn btn-white divStylecss-update";
  const isDeleted = allObject?.is_deleted === 1;
  const isDisabled = voidDisabled(voids, isDeleted);


  
  function SendToCarriersButton({ onClick }) {
    return (
      <button
        disabled={getUpdate || sendMarketTerminal ? true : false}
        type="button"
        className={sendCarriersClassName}
        onClick={onClick}
      >
        SEND TO CARRIERS
      </button>
    );
  }

  function AddRateButton({ onClick }) {
    return (
      <button
        type="button"
        className="btn btn-orange divStylecss-update"
        data-bs-toggle="modal"
        data-bs-target="#create_quote"
        onClick={onClick}
      >
        ADD RATE
      </button>
    );
  }
  function UpdateChangesButton({ disabled, onClick }) {
    const shouldEnableButton = ((data?.user?.user_type == "admin" || data?.user?.user_type == "customer" && data?.user?.parent_id == null) && getUpdate || getUpdate === undefined) ? false : true;
    return (
      <button
        type="button"
        disabled={disabled || shouldEnableButton ? true : false}
        className={buttonClassName}
        onClick={onClick}
      >
        UPDATE CHANGES
      </button>
    );
  }
  function VoidQuoteButton({ disabled, onClick }: any) {
    const isAdminOrSuperAdminOrCustomer =
      userType === "super_admin" ||
      userType === "customers" ||
      userType === "admin";
    const shouldEnableButton = !isAdminOrSuperAdminOrCustomer && !getUpdate;

    return (
      <button
        type="button"
        disabled={disabled || shouldEnableButton}
        onClick={onClick}
        className="btn btn-red divStylecss-update"
      >
        VOID QUOTE
      </button>
    );
  }
  function getCurrentDate() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, "0");
    const day = String(today.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  }
  const handleHazmatChange = (e) => {
    setEdit(true);
    if (e.target.value == 1) {
      setAllObject((prevData) => ({
        ...prevData,
        hazmat: 1,
        class: initialclass,
        un_number: initialun_number,
      }));
    } else {
      setAllObject((prevData) => ({
        ...prevData,
        hazmat: 0,
        class: "",
        un_number: " ",
      }));
    }
  };

  const handleSizeChange = (e) => {
    setEdit(true);
    const { value} = e.target
    setAllObject((prevData) => ({
      ...prevData,
      load_type_code: value,
    }));
  };

  const handleLengthChange = (e) => {
    setEdit(true);
    const { value} = e.target
    setAllObject((prevData) => ({
      ...prevData,
      length: value,
    }));
  };

  const handleWeightTypeChange = (e) => {
    setEdit(true);
    const { value} = e.target
    setAllObject((prevData) => ({
      ...prevData,
      weight_type: value,
    }));
  };

  const marketName = allObject?.market_name;
  useEffect(() => {
    if (marketName) {
      setMarketValue(marketName);
    }
  }, [allObject?.market_name]);

  function stateNameOriginDestination(item: any) {
    const state_od = item?.name[0]?.state;
    const zip_od = item?.name[0]?.zip;

    let result = "";

    if (state_od) {
      result = `${zip_od ? state_od + ", " : state_od}`;
    }

    return result;
  }
  const isButtonDisabled = userType === "carriers" || getUpdate;
  const isOwnerCurrentUser = (ownerId === logeduserId);
  const isTrueOrFalse = isOwnerCurrentUser || (isOwnerCurrentUser && parentId);


  useEffect(() => {

  
    if (Id) {
      setIsloading(true)

      CarrierTableFindAll(tokens).then((response) => {
        if (response?.status === "success") {
          let res = response?.data?.includes(parseInt(Id));
          setIsloading(false)
          if (!res) {
            setCheck(true);
            toast.error(
              <div>
                <span className="Access">Access Denied <Image className="Access-img" src={alert} /></span>
                <br />
                You are attempting to access a quote that either does not exist or is not associated with your account. Please verify the URL and ensure you are logged into the correct account.
              </div>,
              {
                position: toast.POSITION.TOP_CENTER,
                icon: false,
                style: customToastStyle,
              }
            );
            setTimeout(() => {
               Router.push("/rate-quotes")
            }, 4000);
          }
          else {
            setCheck(false)
          }
        }
      });
    }
  }, [Id, accessToken]);

  useEffect(() => {
    if (check) {
      setSelectedSpecialServices([]);
      setInitialpayload("");
      setSendVar({
      });
      setAllObject({});
      setInitialclass("");
      setInitialun_number("");
      setSelectedOriginDestination(
        ""
      );
      setStremValue([]);

    }
  }, [check, isloading])

  const { newLocals_6: locals_6, newLocals_5: locals_5, newLocals_4: locals_4, newLocals_2: locals_2, newLocals_3: locals_3, newLocals_1: locals_1, newLocals: locals, shouldDisables: disables } = RefFun();

  const { isCollapsed } = useCollapsed(); 

  const sortedSpecialServices = [...sub_specialServices].filter(service => service.service_code.toLowerCase() !== "other").sort((a, b) => a.service_code.localeCompare(b.service_code));

  return (
    <div>
      <ToastContainer
      />
      {isloading && (
        <div id="loader_table">
          <ScaleLoader color="#3180f3" className="table_loader" />
        </div>
      )}
      {info && (
        infoMod()
      )
      }
      <Layout notify={notify} setnotifys={setNotify}>
        <Head>
          <title>Rate-Quotes Detail - Draydex</title>
        </Head>
        <div className={` ${isCollapsed ? 'collapsed-quote' : 'content-body mt-5'}`} >
          <div
            style={{ padding: "30px 10px" }}
            className="filter_block rate_block mb-4"
          >
            <div className="top_block new_block_add mb-3">
              <div className="first_blocks">
                <div className="headings add_heading">
                  <h5 className="h5_tag_round">
                    Quote# <span className="span_tag">{Id}</span>
                  </h5>
                  <h5 className="h5_tag_round">
                    Roundtrip Miles &nbsp;
                    <span className="span_tag">
                    {(allObject?.miles) ? parseFloat(allObject?.miles).toFixed(2): 'N/A'} mi
                    </span>
                  </h5>
                </div>
              </div>
                <CustomerBadge
                  name={setUserName}
                  detailsQuoteData={{
                    sendVar: sendVar,
                    setTakeInput: setTakeInput,
                    ownerId: ownerId,
                    setEdit: setEdit,
                    userType: userType,
                  }}
                />
              <div className="third_block">
                <div style={{ width: "max-content" }} className="top_btns float-end d-flex gap-2">
                  {userData?.SelectViewLog ? <button
                    className="btn map-btn btn_log   "
                    onClick={() => setViewLogOpen(true)}
                  >
                    <i className="bi bi-file-earmark-text"></i> View Log
                  </button> : ""}

                  <button
                    onClick={() => Router.back()}
                    className="btn map-btn btn_log"
                  >
                    <i className="bi bi-x-lg"></i> Close
                  </button>
                </div>
              </div>
            </div>
            <div className={`${isViewLogOpen ? "overlay" : ""}`}>
              {isViewLogOpen && (
                <ViewLog onClose={() => setViewLogOpen(false)} id={Id} />
              )}
            </div>
            <Form>
              <Row>
                <Col lg={6}>
                  <Row>
                    <Col md={4}>
                      {" "}
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">Market</FormLabel>
                        <Form.Select
                          disabled={isButtonDisabled}
                          className={`form-select-sm`}
                          id="port_ramp"
                          name="port_name"
                          onChange={(e)=> {
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleMarketInputChange(e);
                          }}
                        >
                          <option value={JSON.stringify({ id: '', name: allObject?.market_name, lat: allObject?.port_lat, lng: allObject?.port_lon })}>{allObject?.market_name ? allObject?.market_name : "Please Select"}</option>

                          {portsData?.filter(item => item.market !== allObject?.market_name).map((item) => {
                            const market1 = `${item?.state_code}-${item?.name}`;
                            const value1 = {
                              id: item?.id,
                              name: market1,
                              lat: item?.lat,
                              lng: item?.lng,
                            };
                            return (
                              <option
                                key={item.id}
                                value={JSON.stringify(value1)}
                                selected={allObject?.market_name === item.market}
                              >
                                {item.market}
                              </option>
                            );
                          })}
                        </Form.Select>
                      </div>
                    </Col>
                    <Col md={4}>
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">Type</FormLabel>
                        <div className="badge_block">
                          <div className="float-right">
                            <Form.Control
                              disabled={isButtonDisabled}
                              type="radio"
                              className="btn-check"
                              name="load_type_code"
                              id="load_type_code_one"
                              checked={allObject?.load_type_code == "import"}
                              value="import"
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleSizeChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light mb-0"
                              htmlFor="load_type_code_one"
                            >
                              IMPORT
                            </FormLabel>
                          </div>

                          <span className="span-cross-rate">/</span>
                          <div>
                            <Form.Control
                              disabled={isButtonDisabled}
                              type="radio"
                              className="btn-check"
                              name="load_type_code"
                              id="load_type_code_two"
                              checked={allObject?.load_type_code == "export"}
                              value="export"
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleSizeChange(e)
                              }}
                            />

                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="load_type_code_two"
                            >
                              EXPORT
                            </FormLabel>
                          </div>
                        </div>
                      </div>
                    </Col>
                    <Col md={4}>
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">SIZE</FormLabel>
                        <div className="badge_block">
                          <div className="float-right">
                            <Form.Control
                              disabled={isButtonDisabled}
                              type="radio"
                              className="btn-check"
                              name="length"
                              id="length-one"
                              checked={allObject?.length == 20}
                              value={20}
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleLengthChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="length-one"
                            >
                              20
                            </FormLabel>
                          </div>
                          <span className="span-cross-rate">/</span>
                          <div>
                            <Form.Control
                              disabled={isButtonDisabled}
                              type="radio"
                              className="btn-check"
                              name="length"
                              id="length-two"
                              checked={allObject?.length == 40}
                              value={40}
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleLengthChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="length-two"
                            >
                              40
                            </FormLabel>
                          </div>
                          <span className="span-cross-rate">/</span>
                          <div className="float-right">
                            <Form.Control
                              disabled={isButtonDisabled}
                              type="radio"
                              className="btn-check"
                              name="length"
                              id="length-three"
                              checked={allObject?.length == 45}
                              value={45}
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleLengthChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="length-three"
                            >
                              45
                            </FormLabel>
                          </div>
                          <span className="span-cross-rate">/</span>
                          <div>
                            <Form.Control
                              disabled={isButtonDisabled}
                              type="radio"
                              className="btn-check"
                              name="length"
                              id="length-four"
                              checked={allObject?.length == 53}
                              value={53}
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleLengthChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="length-four"
                            >
                              53
                            </FormLabel>
                          </div>
                        </div>
                      </div>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={4}>
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">
                          Terminal(If Known)
                        </FormLabel>
                        <Form.Select
                          disabled={isButtonDisabled}
                          className={`form-select-sm`}
                          id="terminal"
                          name="terminal"
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleTerminalInputChange(e)
                          }}
                        >
                          {locals_6}
                          {terminallistvalue?.length !== 0 ? (
                            terminallistvalue?.map((item: any) => (
                              <option
                                key={item.id}
                                selected={item.id === allObject?.terminal_id}
                                value={item.id}
                                name={item.name}
                              >
                                {item.name}
                              </option>
                            ))
                          ) : (
                            <option value="null ">Please select</option>
                          )}
                        </Form.Select>
                      </div>
                    </Col>
                    <Col md={4}>
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">Pickup Date</FormLabel>
                        <Form.Control
                          disabled={isButtonDisabled}
                          name="pickup_date"
                          type="date"
                          className="form-field"
                          placeholder=""
                          min={getCurrentDate()}
                          value={allObject?.pickup_date}
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleInputChange(e)
                          }}
                        />
                      </div>
                    </Col>
                    <Col md={4}>
                      <Row>
                        <Col>
                          <Row>
                            <div className="col-6">
                              <div className="first_one">
                                <FormLabel htmlFor="port_ramp">
                                  Start Time
                                </FormLabel>
                                <Form.Control
                                  name="pickup_time_start"
                                  type="time"
                                  disabled={locals_5 || isButtonDisabled}
                                  className=" "
                                  placeholder=""
                                  value={allObject?.pickup_time_start}
                                  onChange={(e)=>{
                                    if (isButtonDisabled) {
                                      e.preventDefault();
                                      e.target.value = "";
                                      return;
                                    }
                                    handleInputChange(e)
                                  }}
                                />
                              </div>
                            </div>

                            <div className="col-6">
                              <div className="first_one">
                                <FormLabel htmlFor="port_ramp">
                                  End Time
                                </FormLabel>
                                <Form.Control
                                  name="pickup_time_end"
                                  type="time"
                                  disabled={locals_5 || isButtonDisabled}
                                  className=" "
                                  placeholder=""
                                  value={allObject?.pickup_time_end}
                                  onChange={(e)=>{
                                    if (isButtonDisabled) {
                                      e.preventDefault();
                                      e.target.value = "";
                                      return;
                                    }
                                    handleInputChange(e)
                                  }}
                                />
                              </div>
                            </div>
                          </Row>
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={4}>
                      <div className="mb-3 position-relative">
                        <FormLabel htmlFor="port_ramp">
                          Origin/Destination
                        </FormLabel>
                        <Form.Control
                          disabled={isButtonDisabled}
                          autoComplete="off"
                          onInput={(e) => {
                            e.preventDefault();
                            getAddressSuggestions(e);
                          }}
                          value={selectedOriginDestination}
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            setSelectedOriginDestination(e.target.value)
                          }}
                          placeholder="Zip or Address"
                        />

                        <div
                          className={
                            locals_4
                          }
                        >
                          <ul className="city-listing-css">
                            {searchedSuggestions.map(
                              (item: any, index: any) => (
                                <li
                                  key={index}
                                  onClick={() => {
                                    bindSelectedAddress({
                                      name: [
                                        {
                                          city: item?.name[0].city,
                                          state: item?.name[0].state,
                                          zip_code: item?.name[0].zip,
                                        },
                                      ],
                                      lat: item.lat,
                                      lng: item.lng,
                                      state_code: item.state_code,
                                      post_code: item.post_code,
                                    });
                                  }}
                                >
                                  {item?.name[0]?.street
                                    ? `${item?.name[0]?.street + ", "}`
                                    : ""}
                                  {item?.name[0]?.city
                                    ? `${item?.name[0]?.city + ", "}`
                                    : ""}
                                  {stateNameOriginDestination(item)}
                                  {item?.name[0]?.zip
                                    ? `${item?.name[0]?.zip}`
                                    : ""}
                                </li>
                              ),
                            )}
                          </ul>
                        </div>
                      </div>
                    </Col>
                    <Col md={4}>
                      {" "}
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">
                          Loading/Unloading Date
                        </FormLabel>
                        <Form.Control
                          disabled={isButtonDisabled}
                          name="delivery_date"
                          type="date"
                          className="form-field"
                          placeholder=""
                          value={allObject?.delivery_date}
                          min={getCurrentDate()}
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleInputChange(e)
                          }}
                        />
                      </div>
                    </Col>

                    <Col md={4}>
                      <Row>
                        <div className="col-6">
                          <div className="first_one">
                            <FormLabel htmlFor="port_ramp">
                              Start Time
                            </FormLabel>
                            <Form.Control


                              name="delivery_time_start"
                              type="time"
                              disabled={locals_2 || isButtonDisabled}
                              className=" "
                              placeholder=""
                              value={allObject?.delivery_time_start}
                              onChange={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleInputChange(e)
                              }}
                            />
                          </div>
                        </div>

                        <div className="col-6">
                          <div className="first_one">
                            <FormLabel htmlFor="port_ramp">End Time</FormLabel>
                            <Form.Control
                              name="delivery_time_end"
                              type="time"
                              disabled={locals_3 || isButtonDisabled}
                              className=" "
                              placeholder=""
                              value={allObject?.delivery_time_end}
                              onChange={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleInputChange(e)
                              }}
                            />
                          </div>
                        </div>
                      </Row>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={4}>
                      <div className="mb-3">
                        <FormLabel
                          name="equipment"
                          onChange={handleInputChange}
                          htmlFor="port_ramp"
                        >
                          Equipment
                        </FormLabel>
                        <Form.Select
                          disabled={isButtonDisabled}
                          className="form-field form-control"
                          name="carrier_equipment_code"
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleInputChange(e)
                          }}

                        >
                          <option value="">Select Equipment</option>
                          {equipments.map(
                            (item: { name: string; value: string }) => {
                              return (
                                <option
                                  key={item.value}
                                  value={item.value}
                                  selected={
                                    item.value ==
                                    allObject?.carrier_equipment_code
                                  }
                                >
                                  {item.name}
                                </option>
                              );
                            },
                          )}
                        </Form.Select>
                      </div>
                    </Col>
                    <Col md={4} className="d-flex gap-1">
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">Quantity</FormLabel>
                        <Form.Control
                          name="quantity"
                          disabled={isButtonDisabled}
                          value={locals_1}
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleInputChange(e)
                          }}
                          className="form-field"
                          type="number"
                          min="0"
                          placeholder="Quantity"
                        />
                      </div>
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">Weight</FormLabel>
                        <Form.Control
                          name="weight"
                          disabled={isButtonDisabled}
                          value={locals}
                          onChange={(e)=>{
                              if (isButtonDisabled) {
                                e.preventDefault();
                                e.target.value = "";
                                return;
                              }
                            handleInputChange(e)
                          }}
                          className="form-field"
                          type="number"
                          min="0"
                          placeholder="Weight"
                        />
                      </div>
                    </Col>
                    <Col md={4}>
                      <div className="mb-3">
                        <FormLabel>Weight in LBS/KG</FormLabel>
                        <div className="badge_block">
                          <div className="float-right">
                            <Form.Control
                              type="radio"
                              className="btn-check"
                              disabled={isButtonDisabled}
                              name="weight_type"
                              id="option-lbs"
                              autoComplete="off"
                              checked={allObject?.weight_type === null || allObject?.weight_type == "lbs"}
                              value="lbs"
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleWeightTypeChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="option-lbs"
                            >
                              LBS
                            </FormLabel>
                          </div>
                          <span className="span-cross-rate">/</span>
                          <div>
                            <Form.Control
                              type="radio"
                              className="btn-check"
                              name="weight_type"
                              id="option-kg"
                              disabled={isButtonDisabled}
                              autoComplete="off"
                              checked={allObject?.weight_type == "kg"}
                              value="kg"
                              onClick={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleWeightTypeChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="option-kg"
                            >
                              KG
                            </FormLabel>
                          </div>
                        </div>
                      </div>
                    </Col>
                  </Row>
                  <Row>
                    <Col md={8}>
                      <div className="mb-3">
                        <FormLabel htmlFor="commodity">Commodity</FormLabel>
                        <Form.Control
                          type="text"
                          disabled={isButtonDisabled}
                          className="form-control"
                          id="exampleFormControlTextarea1"
                          name="commodity"
                          placeholder="Commodity "
                          value={allObject?.commodity}
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handlecomodityInputChange(e)
                          }}
                        />
                      </div>
                    </Col>
                    <Col md={4}>
                      <div className="mb-3">
                        <Form.Label>Hazmat?</Form.Label>
                        <div className="badge_block">
                          <div className="float-right">
                            <Form.Control
                              type="radio"
                              disabled={isButtonDisabled}
                              className="btn-check"
                              name="hazmat"
                              id="hazmat-yes"
                              autoComplete="off"
                              checked={allObject?.hazmat === 1}
                              value="1"
                              onChange={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleHazmatChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-danger radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="hazmat-yes"
                            >
                              Yes
                            </FormLabel>
                          </div>
                          <span className="span-cross-rate">/</span>
                          <div>
                            <Form.Control
                              type="radio"
                              disabled={isButtonDisabled}
                              className="btn-check"
                              name="hazmat"
                              id="hazmat-no"
                              autoComplete="off"
                              checked={allObject?.hazmat === 0}
                              value="0"
                              onChange={(e)=>{
                                if (isButtonDisabled) {
                                  e.preventDefault();
                                  e.target.value = "";
                                  return;
                                }
                                handleHazmatChange(e)
                              }}
                            />
                            <FormLabel
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light  mb-0"
                              htmlFor="hazmat-no"
                            >
                              No
                            </FormLabel>
                          </div>
                        </div>
                      </div>
                    </Col>
                  </Row>
                  <Row>
                    <Col>
                      <div className="mb-3">
                        <FormLabel htmlFor="port_ramp">
                          Special Services
                        </FormLabel>
                        <Typeahead
                          disabled={isButtonDisabled}
                          multiple
                          id="special_services"
                          labelKey={(option) => option.service_name}
                          options={sortedSpecialServices}
                          placeholder="Select Special Services"
                          selected={selectedSpecialServices}
                          onChange={(selected) => {
                            if (isButtonDisabled) {
                              return;
                            }
                            setEdit(true);
                            setSelectedSpecialServices(selected);
                          }}
                        />
                      </div>
                    </Col>
                    <Col>
                      <div className="mb-3 position-relative">
                        <FormLabel htmlFor="port_ramp">
                          Steamship Line (SSL)
                        </FormLabel>
                        <Form.Control
                          disabled={isButtonDisabled}
                          className="form-field form-control"
                          name="stramline"
                          placeholder="Select Steamship "
                          onChange={(e)=>{
                            if (isButtonDisabled) {
                              e.preventDefault();
                              e.target.value = "";
                              return;
                            }
                            handleStreamlineInputChange(e)
                          }}
                          value={stremValue}
                        />
                        <div className={classFunction1()}>
                          <ul
                            className={
                              classFunction()
                            }
                            
                          >
                            {suggestedstreamline.map((item, index) => {
                              return (
                                <li
                                  key={index}
                                  onClick={() =>
                                    handleDropdownstreamlineClick(item)
                                  }
                                  onMouseOver={() => setHighlightedLi(index)}
                                  onMouseOut={() => setHighlightedLi(null)}
                                  className={
                                    highlightedLi === index
                                      ? "highlighted-li"
                                      : ""
                                  }
                                >
                                  <b>SSL Name:</b> {item?.name}
                                  <br />
                                  <b>SCAC Code:</b> {item?.ssac_code}
                                  <br />
                                  <b>Abbreviated:</b> {item?.abbreviation}
                                  <br />
                                  <br />
                                </li>
                              );
                            })}
                          </ul>
                        </div>
                      </div>
                    </Col>
                    <Col>
                      <Row>
                        <Col>
                          <div className="quote_inputBlock">
                            <div className="mb-3">
                              <FormLabel htmlFor="port_ramp">UN#</FormLabel>
                              <Form.Control
                                type="number"
                                min="0001"
                                disabled={disables || isButtonDisabled}

                                className="form-field"
                                placeholder="Enter UN#"
                                name="un_number"
                                value={allObject?.un_number}
                                onChange={(e)=>{
                                  if (isButtonDisabled) {
                                    e.preventDefault();
                                    e.target.value = "";
                                    return;
                                  }
                                  handleUnInputChange(e)
                                }}
                              />
                            </div>
                          </div>
                        </Col>
                        <Col>
                          <div className="">
                            <div className="mb-3">
                              <FormLabel htmlFor="port_ramp">Class</FormLabel>
                              <Form.Select

                                className="form-field form-control text-info text-1"
                                name="class"
                                disabled={disables || isButtonDisabled}

                                value={allObject?.class}
                                onChange={(e)=>{
                                  if (isButtonDisabled) {
                                    e.preventDefault();
                                    e.target.value = "";
                                    return;
                                  }
                                  handleInputChange(e)
                                }}
                              >
                                <option value="">Select Class</option>
                                {classhaz?.map((item) => (
                                  <option key={item.id} value={item.code}>
                                    {item.code}
                                  </option>
                                ))}
                              </Form.Select>
                            </div>
                          </div>
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                </Col>
                <Col lg={6}>
                  <div className="mb-3">
                    <FormLabel htmlFor="port_ramp">
                      Notes for Carriers
                    </FormLabel>
                    <Form.Control
                      disabled={isButtonDisabled}
                      as="textarea"
                      className="form-control"
                      id="exampleFormControlTextarea1"
                      name="notes_for_carrier"
                      rows={5}
                      placeholder="Notes for Carriers"
                      value={allObject?.notes_for_carrier}
                      onChange={(e)=>{
                        if (isButtonDisabled) {
                          e.preventDefault();
                          e.target.value = "";
                          return;
                        }
                        handleInputChange(e)
                      }}
                      maxLength={400}
                    />
                  </div>

                  {userType === "customers" || userType === "super_admin"  ?
                    CustomerFunction():""
                  }


                </Col>
              </Row>
              <Row>
                <Col lg={9}>
                  <div className="btn_group">{renderButtons()}</div>
                </Col>
              </Row>
            </Form>
          </div>
          <div className="rateQuotestablelist">
            <RateTable
              note={{ note: allObject?.notes_for_carrier, ownerId: ownerId }}
              update={setUpdate}
              keyVerify={isTrueOrFalse}
              check={check}  
              refresh={refresh}
              setRef={setRefresh}
              propData={propData}
              setNotify={setNotify}
            />
          </div>
          <SendCarriersModal
            key={true}
            show={showCarrierModal}
            id={Router?.query?.id}
            handleClose={handleCarriersCloseModal}
            marketData={propData}
            portsData={portsData}
          />
          <UpdateQuteModal
            load={setLoad}
            key={true}
            show={showUpdateQuoteModal}
            id={Router?.query?.id}
            handleClose={handleUpdateQuoteCloseModal}
          />
          <AddRateModal
            key={addRateModalCount}
            selectedSpecialServices={selectedSpecialServices}
            dieselprice={dieselPrice}
            rateQuotesId={Router?.query?.id}
            show={showModal}
            handleClose={handleCloseModal}
            refresh={setRefresh}
            propData={propData}
            setNotify={setNotify}
          />
        </div>
      </Layout>
      <Modal show={showRegisterPopup} onHide={toggleRegisterPopup}>
        <Modal.Header>
          <Modal.Title>Are you sure you want to delete your quote?</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className="reg_button">
            <Button
              disabled={voids}
              variant="primary"
              className="mx-2 "
              onClick={() => HandleVoid()}
            >
              Confirm
            </Button>
            <Button
              disabled={voids}
              variant="danger"
              className="mx-2 carrierButton"
              onClick={toggleRegisterPopup}
            >
              Close
            </Button>
          </div>
        </Modal.Body>
        <Modal.Footer></Modal.Footer>
      </Modal>
    </div>
  );


  function RefFun() {
    const isHazmatFalsy = !allObject?.hazmat;
    const shouldDisables = isHazmatFalsy || isButtonDisabled;
    const newLocals = allObject?.weight ? allObject?.weight : "";
    const newLocals_1 = allObject?.quantity ? allObject?.quantity : "";
    const newLocals_2 = !deliveryenable || userType === "carriers";
    const newLocals_3 = !deliveryenable || userType === "carriers";
    const newLocals_4 = searchedSuggestions.length < 1 ? "d-none" : "";
    const newLocals_5 = !pickupenable || isButtonDisabled;
    const newLocals_6 = terminallistvalue?.length !== 0 ? (
      <>
        <option>Please select</option>
      </>
    ) : (
      <></>
    );
    return { newLocals_6, newLocals_5, newLocals_4, newLocals_2, newLocals_3, newLocals_1, newLocals, shouldDisables };
  }



  function classFunction1(): string | undefined {
    return showSuggestions ? "" : "d-none";
  }

  function CustomerFunction(): React.ReactNode {
    return <div className="mb-3">
      <FormLabel htmlFor="port_ramp">Internal Notes</FormLabel>
      <Form.Control
        disabled={isButtonDisabled}
        as="textarea"
        className="form-control"
        id="exampleFormControlTextarea1"
        name="notes"
        rows={5}
        placeholder="Internal Notes"
        value={allObject?.notes}
        onChange={(e)=>{
          if (isButtonDisabled) {
            e.preventDefault();
            e.target.value = "";
            return;
          }
          handleInputChange(e)
        }}
        maxLength={400} />
    </div>;
  }

  function classFunction(): string | undefined {
    return suggestedstreamline.length > 0
      ? "city-listing-css"
      : "d-none";
  }
};
export default RateQuoteDetail as any;
function sendCarriersClassNameScope1(getUpdate: undefined) {
  return getUpdate ? "btn btn-white divStylecss-update" : "btn btn-green divStylecss-update";
}

function infoMod(): React.ReactNode {
  return <div id="loader">
    <div
      className="spinner-border icon_loder text-primary"
      role="status"
    ></div>
  </div>;
}

function voidDisabled(voids: boolean, isDeleted: boolean) {
  return voids || isDeleted;
}

