import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { number, object, string, array } from "yup";
import { ToastContainer, toast } from "react-toastify";
import React, { useEffect, useState } from "react";
import QuoteCreatedModal from "@/components/ui/modal/QuoteCreatedModal";
import { createQuickQuote,QuoteUserNofication } from "@/services/dashboard";
import { useSession } from "next-auth/react";
import { googleAddressActionUrl, toValidDigitNumber } from "@/helpers/projectHelper";
import { Typeahead } from "react-bootstrap-typeahead";
import { isValidLocationData } from "../../utils/conditions/ConditionCreateQuotes";
import "react-bootstrap-typeahead/css/Typeahead.css";
import {
  quoteTypes,
  equipments,
  specialServices,
  sizes,
} from "@/helpers/constants/static/values";
import {
  Form,
  FormSelect,
  Row,
  Col,
  FormLabel,
  FormControl,
} from "react-bootstrap";
import { getChildCustomer, getCreatePorts, getDashboardCreateTerminals, roundTrip } from "@/services/public";
import { useRouter } from "next/router";
import useAuthProvider from "@/useAuthProvider";
import { processResponseData } from "@/helpers/geolocationParsingUtils";
import { Suggestion } from "@/interfaces/Maps";
import { CustomerChildAdd } from "@/services/profile";

type FuncNewlyCreated = (arg1: string) => void;

interface PropType {
  funcNewlyCreated: FuncNewlyCreated;
  update: update;
  modalCloseStatus?: any;
  setmodalCloseStatus?: any;
  modelType?: any;
  setModalQuoteNumber?: any;
  setModalMarketName?: any;
}
function CreateQuote({ funcNewlyCreated, update, modalCloseStatus, setmodalCloseStatus, modelType, setModalQuoteNumber, setModalMarketName }: PropType) {  
  const { Permission: userData } = useAuthProvider();

  const { data } = useSession();
  const userType = data?.user?.group_type;
  const Router = useRouter();
  const accessToken = data?.user?.image;
  const [marketLat, setMarketLat] = useState<string>("");
  const [marketLng, setMarketLng] = useState<string>("");
  const [selectedSpecialServices, setSelectedSpecialServices] = useState([]);
  const minimumSizeRequired = parseInt(sizes[0]?.value);
  const [findErr, setFindErr] = useState({
    origin_destination: "",
    market: "",
  });
  const [marketId, setMarketId] = useState();
  const [fieldValue, setFieldValue] = useState("");
  const [suggestionsArray, setSuggestionsArray] = useState<any[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [childCustomerIdValue, setChildCustomerIdValue] = useState("");

  const { register, handleSubmit, formState, reset, setValue, setError, getValues} =
    useForm({
      resolver: yupResolver(
        object().shape({
          port_id: string().required("The market value is required."),
          origin_destination: object().required(""),
          equipment: string().required("The equipment value is required."),
          quantity: number()
            .min(1, "The quantity can not be 0.")
            .required("The quantity value is required"),
          type: string().required("The type value is required"),
          size: number().min(minimumSizeRequired).required(""),
          weight: number()
            .min(1, "The weight can not be 0.")
            .required("The weight value is required"),
          weight_type: string().required("The weight type value is required"),
          special_services: array(),
          commodity: string(),
          customer_lead: string(),
        }),
      ),
    });

    
  const { errors } = formState;

  const validator = (formData) => {
    const newErrors = { terminal: "", market: "" };
    if (formData?.origin_destination === "") {
      reset();
      newErrors.origin_destination =
        "The origin or destination value is required.";
    } else {
      newErrors.terminal = "";
    }
    if (formData?.port_id === "") {
      reset();
      newErrors.market = "The market value is required.";
    }
    setFindErr(newErrors);

    return !Object.values(newErrors).some((error) => error !== "");
  };
  const [marketName, setMarketName] = useState();
  let additionalClass = additionalClassScope(userType);

  const onSubmit = async (formData: any, e: any, navigate: string) => {  

    e?.preventDefault();
    let validators = validator(formData);
    const locationData = selectedLocationObject as any;
    if (!isValidLocationData(locationData)) {
      setError("origin_destination", {
        type: "manual",
        message: "The origin or destination value is required.",
      });
      return false;
    }
    formData.lat = locationData.lat;
    formData.lng = locationData.lng;
    formData.state_code = locationData.state_code;
    formData.origin_zip = formData.origin_destination.zip_code;
    formData.city = formData.origin_destination.city;
    if (navigate === "find_rate") {
      validator(formData);
    }
    if (validators === false) {
      return;
    }
    const calculateRoundtripDistance = (lng, lat, formDataLng, formDataLat) => {
      const payload = {
        port_id: marketId,
        lat: formDataLat,
        lng: formDataLng,
      };

      return roundTrip(accessToken, payload);
    };
    let finalChildCustomerId: any;
    if (childCustomerIdValue == "" && formData.customer_lead != '') {
      const addChildPayload = {
        customer: formData.customer_lead,
        sales_rep: data?.user?.name,
      };
      try {
        const response = await CustomerChildAdd(accessToken, addChildPayload);
        if (response?.status === 'success') {
          finalChildCustomerId = response?.data?.id;
        } else {
          finalChildCustomerId = "";
        }
      } catch (error) {
        finalChildCustomerId = "";
      }
    }else{
      finalChildCustomerId = childCustomerIdValue;
    }
    
    const handleCreateQuote = async () => {
      
      setQuoteBtnDisabled(true);
      const payloadsubmit = {
        type: formData.type,
        port_id: formData.port_id,
        origin_destination: selectedOriginDestination,
        special_services: formData.special_services ||selectedSpecialServices?selectedSpecialServices?.map(item => item.value):"",
        size: formData.size,
        equipment: formData.equipment,
        quantity: formData.quantity,
        weight: formData.weight,
        weight_type: formData.weight_type,
        market: marketName,
        origin_city: formData.city,
        origin_state_code: formData.state_code,
        origin_lat: formData.lat,
        origin_lng: formData.lng,
        origin_zip: /^\d+$/.test(formData.origin_zip)
          ? formData.origin_zip
          : "", 
        terminal_id: formData.terminal,
        commodity: formData?.commodity,
        child_customer_id: finalChildCustomerId
      };
    
      try {
       
        let response = await createQuickQuote(accessToken, payloadsubmit, "2");
        const  notifyPayload={
          market_name:payloadsubmit?.market,
         quote_id:response?.data?.quote_id,
          type:"quote_create"
          }
        setQuoteBtnDisabled(false);
        SuccessScope(response, update, handleQuoteError);
        if (response?.status_code === 404) {
          setFindErr({});
          reset();
          setSelectedOriginDestination("");
          setSelectedSpecialServices([]);
          setSelectedOriginDestination("");
        } else {
          if(response?.status == 'success'){
            QuoteUserNofication(accessToken,notifyPayload);
            if(modelType == 'create_quote_modal'){
              setmodalCloseStatus(false);
            }
            handleQuoteSuccess(response);
          }
        }
      } catch (error) {
        return error;
      }
    };

    const handleQuoteError = (response) => {
      toast.error(response?.message, {
        position: toast.POSITION.TOP_CENTER,
        className: "toast-font-size"
      });
      setSelectedSpecialServices([]);
    };

    const handleQuoteSuccess = (response) => {
      setSelectedSpecialServices([]);
      reset();
      setChildCustomerIdValue("");
      setFieldValue("");
      setSelectedOriginDestination("");
      setSelectedLocationObject({});
      setQuoteNumber(response?.data?.quote_id);
      setQuoteId(response?.data?.quote_id);
      funcNewlyCreated("created-" + response?.data?.quote_id);
      handelModalClick(true);
      setModalQuoteNumber(response?.data?.quote_id);
      setModalMarketName(marketName);
    };

    const handleFindRate = async () => {
      if (navigate !== "find_rate") return;

      const roundtripDistance = await calculateRoundtripDistance(
        marketLng,
        marketLat,
        formData?.lng,
        formData?.lat,
      );
      let port: any = portsData?.filter(
        (item: any) => item.id == getValues("port_id"),
      )[0];

      const Distance = roundtripDistance?.data?.original_val?.toFixed(2);
      let queryObj = {
        port: `${port?.state_code}-${port?.name}`,
        original_val: Distance,
        max: roundtripDistance?.data?.max,
        min: roundtripDistance?.data?.min,
      };
      Router.push({ pathname: "/rate-quotes", query: queryObj });
    };

    navigationScope(navigate, handleCreateQuote, handleFindRate);
  };

  const handelModalClick = (value: boolean) => {
    setQuoteModalOpen(value);
  };
  const [quoteNumber, setQuoteNumber] = useState<number | null | undefined>();
  const [quoteId, setQuoteId] = useState<number | null | undefined>();
  const [quoteModalOpen, setQuoteModalOpen] = useState(false);
  const [quoteBtnDisabled, setQuoteBtnDisabled] = useState(false);
  
  const [searchedSuggestions, setSearchSuggestions] = useState<Suggestion[]>([]);
  const [selectedOriginDestination, setSelectedOriginDestination] =
    useState("");
  const [selectedLocationObject, setSelectedLocationObject] = useState({});
  const [portsData, setPortsData] = useState([]);
  const [terminal, setTerminal] = useState([]);
  const [market, setMarket] = useState([]);
  useEffect(() => {
    getCreatePorts().then((response) => {  
      if (response.status == "success") {
        setPortsData(response.data);
      }
    });
    const payload = {
      market: market,
    };
    getDashboardCreateTerminals(accessToken, payload).then((response) => {
      if (response.status == "success") {
        setTerminal(response.data);
      }
    });
  }, [setPortsData, market]);

  const clearAll = () => {
    setFindErr({});
    reset();
    setSelectedOriginDestination("");
    setSelectedSpecialServices([]);
    setSelectedOriginDestination("");
    setChildCustomerIdValue("");
    setFieldValue("");
  };

  async function getAddressSuggestions(event: any) {
    try {
      const searchedString = event.target.value;
      setSelectedLocationObject({});
      if (searchedString.length > 3) {
        const searchResponse = await fetch(
          googleAddressActionUrl(searchedString),
        );
        const searchedResponseData = await searchResponse.json();
        const suggestionsArray = processResponseData(
          searchedResponseData?.results,
        );
        setSearchSuggestions(suggestionsArray);
      } else {
        setSearchSuggestions([]);
      }
    } catch (error) {
      setSearchSuggestions([]);
    }
  }

  function renderSelectOptions(options, fieldName) {
    return (
      <>
        <option value="">{`Select ${fieldName}`}</option>
        {options.map((item) => (
          <option
            key={getKey(item, fieldName)}
            value={getKey(item, fieldName)}
            data={JSON.stringify(item)}
          >
            {getLabel(item, fieldName)}
          </option>
        ))}
      </>
    );
  }
  function getKey(item, fieldName) {
    switch (fieldName) {
      case "Market":
        return item.id;
      case "Type":
        return item.value;
      case "Equipment":
      case "Size":
        return item.value;
      default:
        return item.value;
    }
  }

  function getLabel(item, fieldName) {
    switch (fieldName) {
      case "Market":
        return `${item?.market}`;
      case "Type":
      case "Equipment":
      case "Size":
        return item.name;
      default:
        return item.name;
    }
  }

  type SelectAddressType = {
    name: string;
    city: string;
    zip: number;
    state: string;
  };

  function formatDestinationAddress(
    cityName: any,
    stateCode: any,
    zipCodeNumber: any
  ): string {
    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: SelectAddressType) {
 


    const cityName = cityNameOfValue(item?.name[0]?.city, item);

    // Extract and format state code and name
    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
      : "";

    // Format the final destination address
    const finalDestinationName = formatDestinationAddress(
      cityName,
      stateCodeName,
      zipCodeNumber,
    );

    // Update form state and suggestions
    setValue("origin_destination", item.name[0]);
    formState.errors.origin_destination = undefined; // Clear any previous errors
    setSearchSuggestions([]); // Clear search suggestions

    // Set the formatted address and the selected location object
    setSelectedOriginDestination(finalDestinationName);
    setSelectedLocationObject(item);
  }

  const handleMarketChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    const selectedOption = event.target.options[event.target.selectedIndex];
    const selectedData = JSON.parse(selectedOption.getAttribute("data"));
    setMarketName(selectedData?.market);
    setMarketId(selectedData?.id);

    const selectedLat = selectedData?.lat;
    const selectedLng = selectedData?.lng;
    setMarketLat(selectedLat);
    setMarketLng(selectedLng);
    const selectedMarketName = selectedOption.textContent;
    setMarket([selectedMarketName]);
    setFindErr((prevErr) => ({
      ...prevErr,
      market: "",
    }));
    if (errors.port_id) {
      errors.port_id.message = "";
    }
  };

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

    let result = "";

    if (state_od) {
      result = state_od;
      if (zip_od) {
        result += `, `; 
      }
    }

    return result;
  }

  const handleSpecialServices=(event,SpecialServices,setSpecialServices)=>{
    event.preventDefault();
    const { name, value } = event.target;
  
    if (name === "equipment" && value === "reefer") {
      const isReeferAdded = SpecialServices.some(
        (service) => service.value === "reefer"
      );
  
      if (!isReeferAdded) {
        setSpecialServices((prevServices) => [
          ...prevServices,
          { value: "reefer", name: "REEFER" }
        ]);
      }
    }
  }

  const sortedSpecialServices = [...specialServices].sort((a, b) => a.value.localeCompare(b.value));

  const handleStreamlineInputChangeMod = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const rawInput = event.target.value;
    if (rawInput.startsWith(" ") || rawInput.length > 50) return;
    const sanitizedInput = rawInput.slice(0, 50).replace(/\s+/g, " ");
    setFieldValue(sanitizedInput);
    if (sanitizedInput === "") {
      setSuggestionsArray([]);
      setShowSuggestions(false);
      return;
    }
    const encodedInput = encodeURIComponent(sanitizedInput);

    try{
      const queryParam = `customer=${encodedInput}`;
      const response: any = await getChildCustomer(accessToken, 1, queryParam);
      if (response?.status === "success") {
        setSuggestionsArray(response.data);
        setShowSuggestions(true);
      }
    } catch (error) {
      console.error("Error fetching suggestions:", error);
      setSuggestionsArray([]);
      setShowSuggestions(false);
    }
  };
  
  const handleDropdownstreamlineClick = (item: any) => {
    setFieldValue(item.customer);
    setChildCustomerIdValue(item?.id);
    setSuggestionsArray([]);
    setShowSuggestions(false);
  };
  
  const handleCreateQuoteModalClose = ()=>{
    setmodalCloseStatus(false);
  }
  return (
    <div className="find_rate">
      <ToastContainer />
      <h3>
        {""}
        {modelType === 'create_quote_modal' ? 'Create New Rate Quote' : <>{userTypeScope1(userType)} FIND RATES</>}
      </h3>
      <div className="form_body">
        <Form onSubmit={(e) => e.preventDefault()}>
          <Row>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="port_id">Market</FormLabel>
                <FormSelect
                  {...register("port_id")}
                  className={marketClassScope(errors, findErr)}
                  id="port_id"
                  onChange={(event) => handleMarketChange(event)}
                >
                  {renderSelectOptions(portsData, "Market")}
                </FormSelect>
                <Form.Control.Feedback type="invalid">
                  {errors.port_id?.message?.toString()}
                </Form.Control.Feedback>
                <p className="addVal">
                  {findErrScope(findErr)}
                </p>
              </div>
            </Col>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="type">Type</FormLabel>
                <FormSelect
                  {...register("type")}
                  className={typeScope(errors)}
                  id="type"
                >
                  {renderSelectOptions(quoteTypes, "Type")}
                </FormSelect>
                <Form.Control.Feedback type="invalid">
                  {errors.type?.message?.toString()}
                </Form.Control.Feedback>
              </div>
            </Col>
          </Row>
          <Row>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="terminal">Terminal (If Known)</FormLabel>
                <FormSelect
                  {...register("terminal")}
                  className={knownTeminalScope(errors)}
                  id="terminal"
                >
                  <option value="">Select Terminal</option>
                  {terminal?.map((item: any) => {
                    return (
                      <option key={item.id} value={item.id}>
                        {item.name}
                      </option>
                    );
                  })}
                </FormSelect>
                <Form.Control.Feedback type="invalid">
                  {errors?.terminal?.message?.toString()}
                </Form.Control.Feedback>
              </div>
            </Col>
            <Col>
              <div className="mb-3 address-autocomplete-parent">
                <FormLabel htmlFor="origin_destination">
                  Origin/Destination
                </FormLabel>
                <FormControl
                  {...register("origin_destination")}
                  className={
                    originErrScope2(errors, findErr)
                  }
                  id="origin_destination"
                  placeholder="Zip or Address"
                  autoComplete="off"
                  onInput={(e) => {
                    e.preventDefault();
                    getAddressSuggestions(e);
                  }}
                  value={selectedOriginDestination}
                  onChange={(e) => {setSelectedOriginDestination(e.target.value);}}
                />
                <div className={searchedSuggestions.length < 1 ? "d-none" : ""}>
                  <ul className="city-listing-css">
                    {searchedSuggestions?.map((item: any, index: any) => (
                      <li
                        key={index}
                        onClick={() => {
                          setFindErr((prevErr) => ({
                            ...prevErr,
                            origin_destination: "",
                          }));
                          bindSelectedAddress({
                            name: [
                              {
                                name: item?.name[0]?.name,
                                city: item?.name[0]?.city,
                                zip_code: item?.name[0]?.zip,
                                state: item?.name[0]?.state
                                  ? item?.name[0]?.state
                                  : "",
                              },
                            ],
                            lat: item.lat,
                            lng: item.lng,
                            state_code: item.state_code,
                            post_code: item.post_code,
                          });
                        }}
                      >
                        {item?.name[0]?.city ? `${item?.name[0]?.city}, ` : ""}
                        {stateNameOriginDestination(item)}
                        {item?.name[0]?.zip ? `${item?.name[0]?.zip}` : ""}
                      </li>
                    ))}
                  </ul>
                </div>

                <Form.Control.Feedback type="invalid">
                  {errors.origin_destination?.message?.toString()
                    ? "The origin or destination value is required."
                    : ""}
                </Form.Control.Feedback>
               
              </div>
            </Col>
          </Row>
          <Row>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="size">Size</FormLabel>
                <FormSelect
                  {...register("size", {
                    onChange: (e) => handleChangeForColor(e),
                  })}
                  className={`form-select-sm ${errors.size ? "is-invalid" : ""
                    }`}
                  id="size"
                >
                  {renderSelectOptions(sizes, "Size")}
                </FormSelect>
                <Form.Control.Feedback type="invalid">
                  {errors.size?.message?.toString()
                    ? "The size value is required"
                    : ""}
                </Form.Control.Feedback>
              </div>
            </Col>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="equipment">Equipment</FormLabel>
                <FormSelect
                  {...register("equipment", {
                    onChange: (e) => 
                     { handleChangeForColor(e)
                     handleSpecialServices(e,selectedSpecialServices,setSelectedSpecialServices)}
                    ,
                  })}
                  className={`form-select-sm ${errors.equipment ? "is-invalid" : ""
                    }`}
                  id="equipment"
                >
                  {renderSelectOptions(equipments, "Equipment")}
                </FormSelect>
                <Form.Control.Feedback type="invalid">
                  {errors.equipment?.message?.toString()}
                </Form.Control.Feedback>
              </div>
            </Col>
          </Row>
          <Row>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="special_services">
                  Special Services
                </FormLabel>
                <Typeahead
                  id="special_services"
                  labelKey="name"
                  multiple
                  options={sortedSpecialServices}
                  placeholder="Select Special Services"
                  selected={selectedSpecialServices}
                  onChange={(selected) => {
                    let selectedValues = selected?.map(
                      (item: { name: string; value: string }) => item.value,
                    );
                    setValue("special_services", selectedValues);
                    setSelectedSpecialServices(selected);
                  }}
                />
              </div>
            </Col>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="quantity">Quantity</FormLabel>
                <FormControl
                  {...register("quantity", {
                    onChange: (e) => handleChangeForColor(e),
                  })}
                  className={errors?.quantity?.message ? "is-invalid" : ""}
                  id="quantity"
                  defaultValue={""}
                  type="number"
                  min="0"
                  placeholder="Enter Quantity"
                />
                <Form.Control.Feedback type="invalid">
                  {errors.quantity?.message?.toString()
                    ? "The quantity value is required"
                    : ""}
                </Form.Control.Feedback>
              </div>
            </Col>
          </Row>
          <Row>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="weight">Weight in LBS/KG</FormLabel>
                <Row>
                  <Col>
                    <FormControl
                      {...register("weight", {
                        onChange: (e) => handleChangeForColor(e),
                      })}
                      className={errors?.weight?.message ? "is-invalid" : ""}
                      id="weight"
                      defaultValue={""}
                      type="number"
                      min="0"
                      onInput={(e: any) => {
                        const value = e.target.value;
                        if (!toValidDigitNumber(value)) {
                          e.target.value = value.slice(0, 6);
                        }
                      }}
                      placeholder="Enter Weight"
                    />
                  </Col>
                  <Col className="ps-0">
                    <FormSelect
                      className="form-select-sm"
                      {...register("weight_type" as any, {
                        onChange: (e) => handleChangeForColor(e),
                      })}
                      defaultValue={"lbs"}
                      id="weight_type"
                    >
                      <option value="lbs">LBS</option>
                      <option value="kg">KG</option>
                    </FormSelect>
                  </Col>
                </Row>
                <p
                  style={{
                    fontSize: "0.875em",
                    color: "var(--bs-form-invalid-color)",
                  }}
                >
                  {errors?.weight?.message?.length === undefined
                    ? ""
                    : "Weight value is required"}
                </p>
              </div>
            </Col>
          </Row>
          <Row>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="commodity">Commodity</FormLabel>
                <FormControl
                  {...register("commodity", {
                    onChange: (e) => handleChangeForColor(e),
                  })}
                  id="commodity"
                  defaultValue={""}
                  type="text"
                  placeholder="Enter Commodity"
                />   
              </div>
            </Col>
            <Col>
              <div className="mb-3">
                <FormLabel htmlFor="customer_lead">Customer/Lead</FormLabel>
                <div className="position-relative">
                   <Form.Control
                      {...register("customer_lead", {
                        onChange: (e) => handleChangeForColor(e),
                      })}
                      className="form-field form-control"
                      name="customer_lead"
                      onChange={handleStreamlineInputChangeMod}
                      value={fieldValue}
                      maxLength={50}
                      autoComplete="off"
                      placeholder="Enter Customer/Lead"
                    />
                    {fieldValue !== '' && showSuggestions && suggestionsArray.length > 0 && (
                      <div className="suggestion-box position-absolute bg-white border rounded w-100 shadow-sm zindex-dropdown">
                        <ul className="list-unstyled mb-0">
                          {suggestionsArray.map((item, index) => (
                            <li
                              key={index}
                              onClick={() => handleDropdownstreamlineClick(item)}
                              className="p-2 cursor-pointer border-bottom hover-bg-light"
                              style={{ cursor: "pointer" }}
                            >
                              <b>{item.customer}</b>
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}
                </div>
              </div>
            </Col>
          </Row>
          <div className="btn_block my-3">
            <a onClick={() => clearAll()} className="clear_text float-right">
              Clear All
            </a>
          </div>
          <div className="btn_block my-3">
            {userData?.RateQuoteCreateQuote && userType !== "carriers" && (
              <>
              <button
                type="button"
                className="primary_btn text-uppercase"
                disabled={quoteBtnDisabled}
                onClick={() => {
                  setFindErr("");
                  handleSubmit((formData, event) =>
                    onSubmit(formData, event, "create_quote"),
                  )();
                }}
              >
                {quoteBtnDisabled ? (
                  <>
                    <span
                      className="spinner-border spinner-border-sm"
                      role="status"
                      aria-hidden="true"
                    ></span>{" "}
                    Please wait...
                  </>
                ) : (
                  "Create Quote"
                )}
              </button>
              {modelType === 'create_quote_modal' && (
                <button
                  type="button"
                  className={`secondry_btn text-uppercase ${additionalClass}`}
                  onClick={() => handleCreateQuoteModalClose()}
                >
                  Close
                </button>
              )}
              </>
            )}

            {modelType !== 'create_quote_modal' && userData?.RateQuoteFindRate && (
              <button
                type="button"
                className={`secondry_btn text-uppercase ${additionalClass}`}
                onClick={() => {
                  onSubmit(getValues(), null, "find_rate");
                }}
              >
                Find Rates
              </button>
            )}
          </div>
        </Form>
      </div>
      {modelType !== 'create_quote_modal' && (
        <QuoteCreatedModal
          quoteModalOpen={quoteModalOpen}
          quoteNumber={quoteNumber}
          quoteId={quoteId}
          handelModalClick={(value: boolean) => {
            handelModalClick(value);
          }}
          marketName={marketName}
        />
      )}
    </div>
  );
}
export default CreateQuote;

const handleChangeForColor = (event: React.ChangeEvent) => {
  const currentSelect = document.getElementById(event.target.id) as HTMLElement;

  const hasValue = (event.target as HTMLInputElement).value !== "";

  currentSelect.style.color = hasValue ? "#000" : "#a8a8a8";
};
function SuccessScope(response: any, update: update, handleQuoteError: (response: any) => void) {
  if (response?.status === "success") {
    update(true);
  }
  if (response.status === "error" && response.status_code !== 200) {
    handleQuoteError(response);
  }
}
function navigationScope(navigate: string, handleCreateQuote: () => Promise<unknown>, handleFindRate: () => Promise<void>) {
  if (navigate === "create_quote") {
    handleCreateQuote();
  } else if (navigate === "find_rate") {
    handleFindRate();
  }
}

function originErrScope2(errors, findErr: { origin_destination: string; market: string; }): string | undefined {
  return (errors.origin_destination ||
    findErr?.origin_destination) &&
    "is-invalid";
}

function knownTeminalScope(errors): string | undefined {
  return `form-select-sm ${errors.terminal ? "is-invalid" : ""}`;
}

function typeScope(errors): string | undefined {
  return `form-select-sm ${errors.type ? "is-invalid" : ""}`;
}

function findErrScope(findErr: { origin_destination: string; market: string; }): React.ReactNode {
  return findErr.market && <p>{findErr.market}</p>;
}

function marketClassScope(errors, findErr: { origin_destination: string; market: string; }): string | undefined {
  return `form-select-sm ${errors.port_id?.message || findErr?.market
    ? "is-invalid"
    : ""}`;
}

function userTypeScope1(userType: any): React.ReactNode {
  return userType == "carriers" ? <> </> : <> CREATE NEW QUOTE /</>;
}

function additionalClassScope(userType: any) {
  return userType === "carriers" ? "w-100" : "";
}

