/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from "react";
import {
  Modal,
  ModalBody,
  ModalFooter,
  Button,
  Form,
  Row,
  Col,
  Table,
} from "react-bootstrap";
import { ScaleLoader } from "react-spinners";
import { useSession } from "next-auth/react";
import { ToastContainer, toast } from "react-toastify";
import {
  addCost,
  SpotRateQuoteDetails,
  CustomerLead,
  CsvData,
  CloseRateData,
  AddRatesNotificationCarrier,
  toUpdateAccessorialsData
} from "@/services/public";
import { useRouter } from "next/router";
import useAuthProvider from "@/useAuthProvider";
import {toCheckUserTypeSubscreption} from "../../../helpers/toCheckUserType"
import SubscriptionPlansModal from "./SubscriptionPlansModal";
import { toValidateCostAndDigit } from "@/helpers/projectHelper";
interface AddRateModalProps {
  show: boolean;
  handleClose: () => void;
  data: any[];
}
const SubmitRateModal: React.FC<AddRateModalProps> = ({
  show,
  handleClose,
  datas,
  newid,
  queryid,
  isButtonShow,
  propData,
  setNotify,
  CarrId
}) => {

  
  const [linehaul, setLinehaul] = useState("");
  const [fsc, setFsc] = useState("");
  const [chassis, setChassis] = useState("");
  const [validationErrors, setValidationErrors] = useState({
    linehaul: "",
    fsc: "",
    chassis: "",
  });
  const { Permission: userData } = useAuthProvider();

  const [isloading, setIsloading] = useState();
  const [email, setEmail] = useState('');
  const [emailError, setEmailError] = useState<string>("");
  const [lead, setLead] = useState();
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [list, setList] = useState([]);
  const [grossValue, setGrossValue] = useState(0);
  const { data } = useSession();
  const [leadCustomer, setleadCustomer] = useState();
  const accessToken = data?.user?.image;
  const [totalCost, setTotalCost] = useState();
  const [estimatedCost, setEstimatedCost] = useState();
  const termsWeb = list[0]?.web_terms?.terms;
  const [accessorialCost, setAccessorialCost] = useState(Array(datas?.length));
  const [SumCostUpdate, SetSumCostUpdate] = useState(Array(datas?.length));
  const [carrierNotes, setCarrierNotes] = useState("");
  const [customerNotes, setCustomerNotes] = useState("");
  const [customerNotesError, setCustomerNotesError] = useState("");
  const [accessorialChargeSelectionStatus, setAccessorialChargeSelectionStatus] = useState(false);

  const checssisMod = list[0]?.per_day;
  const formData = useRouter();
  const ids = formData?.query?.id;
  const extractRateIds = (datai) => {
    return datai.map((item) => ({
      rate_id: item.id,
    }));
  };
  const GetCustomerLead = async () => {
    let response = await CustomerLead(accessToken, queryid);
    setleadCustomer(response?.data);
  };
  const fetchData = async () => {
    if(accessorialChargeSelectionStatus == false){
      GetCustomerLead();
    }
    setIsloading(true);
    await SpotRateQuoteDetails(accessToken, queryid, newid).then((response) => {
      if (response.status === "success") {
        setIsloading(false);
        if (response?.data?.assential_service?.length) {
          const clean = (arr: any[]) => arr.filter((v) => v != null && v !== "").join(",");
          const services = response.data.assential_service;
          response.data.accessorial_id = clean(services.map((item: { id: any; }) => item?.id));
          response.data.accessorial_cost = clean(services.map((item: { cost: any; }) => item?.cost));
          response.data.accessorial_original_cost = clean(services.map((item: { original_cost: any; }) => item?.original_cost));
          response.data.special_services = clean(services.map((item: { name: any; }) => item?.name));
          response.data.required_for_move = clean(services.map((item: { required_for_move: any; }) => item?.required_for_move));
        }
        setList([response?.data]);
        setCarrierNotes(response?.data?.rate_notes);
      }
    });
  };
  const [dis, setDis] = useState()
  useEffect(() => {

    if (Array.isArray(SumCostUpdate)) {
      const hasNonEmptyValue = SumCostUpdate.some(item => item !== "");
      setDis(!hasNonEmptyValue); 
    } else {
      setDis(false); 
    }
  }, [formSubmitted, SumCostUpdate]);




  useEffect(() => {
    if (Array.isArray(accessorialCost) && accessorialCost.length === 0) {
      setDis(false);
    } else if (Array.isArray(SumCostUpdate) && SumCostUpdate.length === 1) {
      if (SumCostUpdate[0] === 0 || SumCostUpdate[0] === "") {
        setDis(true);
      } else {
        setDis(false);
      }
    } else {
      setDis(false);
    }



  }, [formSubmitted, SumCostUpdate, accessorialCost]);


  useEffect(() => {
    fetchData();
    GetCustomerLead();
  }, [queryid, newid, accessToken, show]);

  const validateForm = () => {
    let isValid = true;
    const errors = {};

    if (!linehaul) {
      errors.linehaul = "Linehaul is required";
      isValid = false;
    } else if (isNaN(parseFloat(linehaul)) || !isFinite(linehaul)) {
      errors.linehaul = "Linehaul must be a valid number";
      isValid = false;
    }
    if (!fsc) {
      errors.fsc = "FSC is required";
      isValid = false;
    } else if (isNaN(parseFloat(fsc)) || !isFinite(fsc)) {
      errors.fsc = "FSC must be a valid number";
      isValid = false;
    }

    if (!chassis) {
      errors.chassis = "Chassis is required";
      isValid = false;
    } else if (isNaN(parseFloat(chassis)) || !isFinite(chassis)) {
      errors.chassis = "Chassis must be a valid number";
      isValid = false;
    }

    setValidationErrors(errors);

    return isValid;
  };

  const handleClear = () => {
    handleClose();
    setLinehaul("");
    setFsc("");
    setChassis("");
    setAccessorialCost(Array(datas?.length));
    SetSumCostUpdate(Array(datas?.length));
    setEmail("");
    setLead([]);
    setFormSubmitted(false);
    setValidationErrors({});

    setTotalCost(0);
    setGrossValue(0);
    setCarrierNotes("");
    setCustomerNotes("");
    setCustomerNotesError("");
    setEmailError("");
    setAccessorialChargeSelectionStatus(false);
  };

  const createPayload = (
    jsonObjects,
    linehauls,
    fscs,
    chassiss,
    accessorialCosts,
    accessorialIdArrays,
    accessorialName,
  ) => {
    const emailsArray = (email || "").split(",").map(e => e.trim()).filter(e => e !== "");
    const payload = {
      rate_id: jsonObjects?.rate_id,
      linehaul,
      fuelSurcharge: fscs,
      chassiss,
      accessorial_cost: accessorialCosts,
      accessorial_id: accessorialIdArrays,
      accessorialName: accessorialName,
      emailsArray,
      lead,
      estimatedCost,
      grossValue,
    };

    payload.accessorial_cost = payload.accessorial_cost?.map((value) =>
      value === "" || value === undefined ? 0 : value,
    );
    return payload;
  };

  const mergeArrayData = (dataObj: any, accessorialCostData: any)=>{
    const essentialService = dataObj?.accessorial_others?.essential_service;
    const Specialservices = dataObj?.special_services?.split(",");
    const Accessorialcost = dataObj?.accessorial_original_cost?.split(",");
    const essentialArray = Array.isArray(essentialService) && essentialService.length > 0
      ? essentialService.map((item: any) => ({
          essential_name: item?.name,
          essential_cost: item?.cost,
          essential_dataType: 'other',
          essential_dataItem: item,
        }))
      : [];
    const specialArray = Specialservices?.map((item1: any, index1: number) => ({
      essential_name: item1,
      essential_cost: Accessorialcost[index1],
      essential_dataType: 'exist',
      essential_dataItem: item1,
    })) || [];
    const finalArray =essentialArray.length > 0 ? [...specialArray, ...essentialArray] : specialArray;
    finalArray.forEach((item: { essential_cost: any; }, index: string | number) => {
      item.essential_cost = accessorialCostData[index];
    });
    return finalArray.filter((item: { essential_dataType: string; }) => item.essential_dataType === "other");
  }

  const toCheckValidationInput = (value: any, name: string, type: string) => {
    const trimmedValue = typeof value === 'string' ? value.trim() : '';
    if (type === 'customer_notes') {
      if (trimmedValue.length > 600) {
        return `${name} cannot exceed 600 characters.`;
      }
      return "";
    }
    if (!trimmedValue) {
      return `${name} is required`;
    }
    return "";
  };

  const handleSubmit = async () => {
    const rateIds = extractRateIds(datas);
    setFormSubmitted(true);
    const jsonObject = rateIds[0];
    const item = datas[0];
    const otherAccessorialData = mergeArrayData(item, accessorialCost);
    const accessorialIdArray = item?.accessorial_id?.split(",")?.map(Number);
    const accessorialName = item?.special_services
      ?.split(",")
      ?.map((name) => name?.trim());
    const move = list[0]?.required_for_move?.split(",")?.map(Number) || "";
    const isValid = validateForm();
    const linehaulError = validateInput(linehaul, "Linehaul");
    const fscError = validateInput(fsc, "FSC");
    const chassisError = validateInput(chassis, "Chassis");
    const customerNoteError: any = toCheckValidationInput(customerNotes, "Customer notes", "customer_notes");
    if(customerNoteError){
      setCustomerNotesError(customerNoteError);
      return;
    }
    
    if (linehaulError || fscError || chassisError) {
      setValidationErrors({
        linehaul: linehaulError,
        fsc: fscError,
        chassis: chassisError,
      });
      return
    } else {
      const emailsArray = (email || "").split(",").map(e => e.trim()).filter(e => e !== "");

      const payload = createPayload(
        jsonObject,
        linehaul,
        fsc,
        chassis,
        accessorialCost,
        accessorialIdArray,
        accessorialName,
        emailsArray,
        lead,
        estimatedCost,
        grossValue,
      );
      const accessorials = accessorialIdArray?.map((id, index) => ({
        id: id,
        name: accessorialName[index] || "",
        value: accessorialCost[index],
        required_move: move[index],
      }));

      const accessorial_others = otherAccessorialData?.map((dataItem: any) => ({
        id: dataItem?.essential_dataItem?.id,
        name: dataItem?.essential_dataItem?.name,
        value: (dataItem?.essential_cost) ? dataItem?.essential_cost : null,
        required_move: (dataItem?.essential_dataItem?.required_for_move) ? 1 : 0,
      }));

      const finalAccessorialData = [...(accessorials || []), ...(accessorial_others || [])];
      const isFormValidStatus = (finalAccessorialData.length > 0) ? !finalAccessorialData.some(item => {
        if (item.required_move !== 1) return false;
        const normalizedValue = item.value != null ? Number(item.value) : null;
        return normalizedValue === 0 || normalizedValue === null || item.value === '';
      }) : true;
      
      if (isValid && isFormValidStatus) {
        setIsloading(true);
        const  notifyPayload={
          user_id:propData?.data?.user_id,
          quote_id:ids,
          type:"rate_select",
          carrier_id:CarrId,
          rate_id:jsonObject?.rate_id
          }
           
        await AddRatesNotificationCarrier(accessToken,notifyPayload)
        setNotify(true)
        let response = await addCost(accessToken, payload, ids, accessorials, accessorial_others, customerNotes);
        if (response?.status === "success") {
          toast.success(response?.message, {
            position: toast.POSITION.TOP_CENTER,
          });
          setIsloading(false);

          setFormSubmitted(false);
          setValidationErrors({});
          resetForm();
          handleClear();
        }
        if (response?.status === "error") {
          setIsloading(false);

          toast.error(response?.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      }
    }
  };
  useEffect(() => {
    const filteredAccessorialCost = SumCostUpdate.filter(
      (value) => value !== null,
    );
    let total = 0;

    for (const value of filteredAccessorialCost) {
      total += parseFloat(value) || 0;
    }
    let fcspercent = (linehaul * fsc) / 100;
    const totalCosts =
      parseFloat(linehaul) + parseFloat(fsc) + parseFloat(chassis) + total;
    const a = Number(total);
    const b =
      Number(linehaul) + Number(fcspercent) + Number(chassis * checssisMod);
    setTotalCost(a ? a + b : (b as any));
    const totalPrice = list?.length > 0 ? list[0]?.original_total : 0;

    setGrossValue(totalPrice - totalCosts);
  }, [chassis, fsc, linehaul, SumCostUpdate]);

  useEffect(() => {
    const totalPrice = list?.length > 0 ? list[0]?.original_total : 0;
    setEstimatedCost(totalCost);
    setGrossValue(totalCost !== 0 ? totalCost - totalPrice : 0);
  }, [chassis, fsc, linehaul, accessorialCost, totalCost]);
  //Reset Form Value
  const resetCommonState = (
    linehaulValue,
    fscValue,
    chassisValue,
    datasLength,
  ) => {
    handleClose();
    setLinehaul(linehaulValue);
    setFsc(fscValue);
    setChassis(chassisValue);
    setAccessorialCost(Array(datasLength).fill(0));
    setEmail("");
    setLead([]);
  };

  const resetForm = () => {
    resetCommonState("", "", "", datas?.length);
  };
  const validateInput = (name, value) => {
    let error = "";
    if (!value) {
      error = `${name} is required`;
    }

    return error;
  };
  const handleFormChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, dataset } = event.target;

    let move = dataset?.move;
    let numericValue = value.replace(/[^\d.]/g, "");
    const parts = numericValue.split(".");
    if (parts.length > 2) {
      numericValue = parts.slice(0, 2).join(".");
    } else if (parts.length === 2) {
      numericValue = `${parts[0]}.${parts[1].slice(0, 2)}`;
    }
    if (name === "Lead") {
      setLead(numericValue);
    }

    if (name === "accessorial_cost" && move == 1) {
      SetSumCostUpdate((prevAccessorialCost) => {
        const updatedCosts = [...prevAccessorialCost];
        updatedCosts[index] = numericValue;
        return updatedCosts;
      });
    }
    const index = parseInt(dataset.index, 10);
    setValidationErrors((prevErrors) => ({
      ...prevErrors,
      [name]: validateInput(name, numericValue),
    }));
    setAccessorialCost((prev) => {
      const Costs = [...prev];
      Costs[index] = numericValue;
      return Costs;
    });

    const trimmedValue = numericValue.trim();

    if (name !== "accessorial_cost") {
      handleOtherFieldChange(name, trimmedValue);

      if (name === "email") {
        setEmail(value); 
        const emailsArray = value.split(",").map(e => e.trim()).filter(e => e !== "");

        const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$/;
        const invalidEmails = emailsArray.filter(emailReg => !emailRegex.test(emailReg));

        if (invalidEmails.length > 0) {
          setEmailError("Please enter valid email address.");
        } else {
          setEmailError("");
        }
      }
    }

    if(name == "customer_notes"){
      setCustomerNotes(value);
      if (value.trim().length > 600) {
        setCustomerNotesError('Customer notes cannot exceed 600 characters.');
      } else {
        setCustomerNotesError('');
      }
    }
  };

  const isAccessorialCostValid = (value, requiredForMove) => {
    return !isNaN(parseFloat(value)) && parseFloat(value) > 0;
  };

  const handleOtherFieldChange = (name: string, value: string) => {
    const fieldValue = value === "" ? "" : value;
    switch (name) {
      case "linehaul":
        setLinehaul(fieldValue);
        break;
      case "fsc":
        setFsc(fieldValue);
        break;
      case "chassis":
        setChassis(fieldValue);
        break;
      default:
        break;
    }
  };

  function convertDataToCSV(datass) {
    if (
      datass &&
      datass.length > 0 &&
      datass[0] !== null &&
      typeof datass[0] === "object"
    ) {
      const headers = Object.keys(datass[0]).join(",");
      const rows = datass.map((item) => Object.values(item).join(","));
      return `${headers}\n${rows.join("\n")}`;
    }
  }
  const downloadCSV = async (idss) => {
    let res = await CsvData(idss);

    if (res?.data?.length > 0) {
      const csvData = convertDataToCSV(res?.data);
      const blob = new Blob([csvData], { type: "text/csv" });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "Accessorials.csv";
      a.click();
      window.URL.revokeObjectURL(url);
    } else {
      toast.error("No data available to download.", {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };
  const terms = (e) => {
    e.preventDefault();
    toast.error("No Website Available.", {
      position: toast.POSITION.TOP_CENTER,
    });
  };
  useEffect(() => {
    setLead(
      leadCustomer?.find((customer) => customer.is_active === 1)?.customer,
    );
    setEmail(
      leadCustomer?.find(
        (customer) => customer.is_active === 1 && customer?.is_sent_rate === 1,
      )?.email,
    );
  }, [leadCustomer]);
  let backgroundColorClass: any;

  if (isButtonShow?.is_rate_send === 1) {
    backgroundColorClass = "success-class";
  } else {
    backgroundColorClass = "other-color-class";
  }
  useEffect(() => {
    const updatedCosts = list.map((item) =>
      item?.assential_service
        .filter((service) => service.required_for_move === 1)
        .reduce(
          (sum, service) => sum + Number(service?.service_customer_cost),
          0,
        ),
    );

    SetSumCostUpdate(updatedCosts);
  }, [list]);

  useEffect(() => {
    const newAccessorialCost = list?.map((item) =>
      item?.assential_service.map((i: any) => i?.service_customer_cost),
    );
    const flattenedAccessorialCost = newAccessorialCost.flat();
    setAccessorialCost(flattenedAccessorialCost);
  }, [list]);

  const [modalStatus, setModalStatus] = useState(false);
  const [hoveredPlan, setHoveredPlan] = useState(null)
  const handlePlanHover = (plan) => {
    setHoveredPlan(plan);
  }

  const handlePlanLeaveEvent = (e) => {
    setHoveredPlan(null);
  }


  const CloseRate = async () => {
    setIsloading(true)
    let res = await CloseRateData(newid, accessToken)
    if (res?.status === "success") {
      toast.success(res?.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      setIsloading(false)
      setFormSubmitted(false);
      setValidationErrors({});
      resetForm();
      handleClear();
    }
    
  }

  const listDatafn = ()=>{
    const finalListData = [ ...(list[0]?.assential_service || []), ...(list[0]?.accessorial_others?.essential_service || [])];
    return finalListData.some((item) => item.required_for_move === 0 || item.required_for_move === false) ? false : true;
  }

  const submitDisabled =  dis || emailError  !== "" ? listDatafn() : false;
  return (
    <Modal
      className="modal_main modal-xl modal_main"
      show={show}
      centered
      backdrop="static"
      onHide={handleClose}
    >
      <ModalBody>
        <ToastContainer />
        {isloading && (
          <div id="loader_table">
            <ScaleLoader color="#3180f3" className="table_loader" />
          </div>
        )}
        <SubscriptionPlansModal modalStatus={modalStatus} SetModalStatus={setModalStatus} userDetails={data?.user}/>
        <div className="filter_block border-0">
          <div className="tabel_top my-3 table-responsive">
            <table className="table table-bordered">
              <thead className="table_light">
                <tr>
                  <th scope="col">
                    Carrier <i className="bi bi-arrow-down-up"></i>
                  </th>
                  <th scope="col">Rate Summary</th>
                  <th scope="col">Accessorials</th>
                  <th scope="col">
                    Estimated Total <i className="bi bi-arrow-down-up"></i>
                  </th>
                  <th scope="col">Capacity?</th>
                </tr>
              </thead>
              <tbody>
                {listFunc()}
              </tbody>
              <div className="mb-3">
                <div>
                  <p className="send-rate-tag lable-info th_class customer_lead_padding">
                    Customer/Lead
                  </p>
                </div>
                <div>
                  <Form.Control
                    disabled={true}
                    className="form-field"
                    type="text"
                    name="text"
                    placeholder="No Customer Lead Available"
                    value={lead}
                  />
                </div>
              </div>
            </table>
          </div>
          <div className="mb-3">
            <div>
              <p className="send-rate-tag lable-info th_class">
                Carrier Notes
              </p>
            </div>
            <div>
              <Form.Control
                as={!carrierNotes ? undefined : "textarea"}
                type={!carrierNotes ? "text" : undefined}
                disabled={true}
                className={`form-field ${carrierNotes ? 'carrier-notes-auto-height w-100' : 'w-25'}`}
                name="text"
                placeholder="No notes provided"
                value={!carrierNotes ? "" : carrierNotes}
              />
            </div>
          </div>
        </div>
        <div className="main_modal">
          <Form>
            <Row>
              <Col>
                {list1Func()}
              </Col>
            </Row>
          </Form>

          <div className="d-flex justify-content-between mb-2">
            <div>
              <p className="send-rate-tag lable-info">
                Notes to Customer:
              </p>
            </div>
          </div>
          <div>
            <div className="mb-4">
              <Form.Control
                as="textarea"
                className="form-field w-100 mb-1"
                name="customer_notes"
                onChange={handleFormChange}
                placeholder={'Type your message here'}
                readOnly={false}
                value={customerNotes || ""}
              />
              {customerNotesError !== "" && (
                <div className="text-danger">{customerNotesError}</div>
              )}
            </div>
          </div>

          <div className="d-flex justify-content-between mb-2">
            <div>
              <p className="send-rate-tag lable-info">
                Emails to Send Marked-Up Quote to:
              </p>
            </div>
          </div>

          <div>
            <div className="mb-4">
              <Form.Control
                className="form-field w-50 mb-1"
                type="text"
                name="email"
                onChange={handleFormChange}
                placeholder={'Please make sure emails are separated by a comma ","'}
                readOnly={false}
                value={email || ""} 
              />
              {emailError && <div className="text-danger">{emailError}</div>}
            </div>
          </div>
          {termsWeb ? (
            <>
              {" "}
              <div className="d-flex justify-content-between mb-2">
                <div>
                  <p className="send-rate-tag lable-info ">
                    Terms & Conditions To Place In Emails To Clients:
                  </p>
                </div>
              </div>
              <div>
                <Form.Control
                  disabled={true}
                  className="form-field w-50"
                  type="text"
                  name="text"
                  placeholder="Terms & Conditions To Place In Emails To Clients:"
                  value={termsWeb || ""}
                />
              </div>{" "}
            </>
          ) : (
            ""
          )}
        </div>
      </ModalBody>
      <ModalFooter className="quote_btn_block">
        {userData?.SendMarkedUpRatetoClient ? <Button
          type="button"
          className="btn btn-success w-25 btn-modal divStylecss-update"
          onClick={handleSubmit}
          disabled={submitDisabled}
        >
          Submit
        </Button> : <Button
          disabled={false}
          type="button"
          className="btn btn-success w-25 btn-modal divStylecss-update"
          onClick={()=>CloseRate()}
        >
          Submit
        </Button>}
      
        <Button
          type="button"
          className="btn btn-secondary w-25 btn-close-modal divStylecss-update"
          data-dismiss="modal"
          onClick={() => {
            handleClear();
            handlePlanLeaveEvent();
          }}
          
        >
          Cancel
        </Button>
      </ModalFooter>
    </Modal>
  );

  function list1Func(): React.ReactNode {
    return list?.map((item, index) => {
      const essentialService = item?.accessorial_others?.essential_service;
      const essentialMoveArray = Array.isArray(essentialService) && essentialService.length > 0
        ? essentialService.map((item: any) => (item?.required_for_move ? 1 : 0))
        : [];
      const requiredMoveArray = item?.required_for_move
        ? item.required_for_move.split(",").map(Number)
        : [];

      const requiredForMoveArray = essentialMoveArray.length > 0
        ? [...requiredMoveArray, ...essentialMoveArray]
        : requiredMoveArray;
      const Specialservices = item?.assential_service;
      const resultAccorialss = resultAccorialss1Func();
      const costData = item?.assential_service.map(
        (i: any) => i?.service_customer_cost
      );

      const handleAccessorialChargeSelection = async (data: any, index: number, value: string) => {
        const makePayload: any = {
          id: data?.accessorialData?.id,
          type: data?.accessorialType,
          required_for_move: (value == 'yes') ? 1 : 0,
        }
        let responseData = await toUpdateAccessorialsData(makePayload); 
        if(responseData?.status == 'success'){
          setAccessorialChargeSelectionStatus(true);
          fetchData();
        }else{
          setAccessorialChargeSelectionStatus(false);
        }
      };      

      return (
        funcGen1({ handlePlanLeaveEvent, handleFormChange, item, handlePlanHover, lienhaul1Fun, DisabledFun, linehaul, lienFunction, fscVal, fsc, fscVal1, chassis, chassisFunc, resultAccorialss, chassisCheck, crossChecked, cost1Class, requiredForMoveArray, costValue, hoverFunc, formFunc, accessorialFunc, accessorialcostFunc, grossFunc, grossfuncValue, handleAccessorialChargeSelection, accessorialChargeSelectionStatus })
      );

      function resultAccorialss1Func() {
        const essentialArray = Array.isArray(essentialService) && essentialService.length > 0
          ? essentialService.map((item: any) => ({
              [item?.name]: item?.original_cost,
              'accessorialType': 'accessorial_others',
              'accessorialData': item,
            }))
          : [];
        const specialArray = Specialservices?.map((item1: any, index1: number) => ({
          [item1.name]: item1.original_cost,
          'accessorialType': 'accessorials',
          'accessorialData': item1,
        })) || [];
        return essentialArray.length > 0 ? [...specialArray, ...essentialArray] : specialArray;
      }

      function formFunc(index3: any): React.ReactNode {
        return newFunction_1(formSubmitted, requiredForMoveArray, index3, isAccessorialCostValid, accessorialCost);
      }

      function cost1Class(): string | undefined {
        return `form-field w-50 subscreption_plan_status_${(toCheckUserTypeSubscreption(data)) && "free"}`;
      }

      function hoverFunc(): React.ReactNode {
        return hoverFscFunc();
      }

      function hoverFscFunc(): React.ReactNode {
        return hoveredPlan === "one" && (toCheckUserTypeSubscreption(data)) && "free" && data?.user?.is_child !== 1 && (

          <div
            onMouseLeave={() => handlePlanLeaveEvent()}
            className="hover-box"
            onClick={() => setModalStatus(true)}
            x-placement="bottom-start" aria-labelledby="nav-dropdown"
            className="dropdown-menu show dropdown-menu-lights Hover-boxes"
            data-popper-reference-hidden="false" data-popper-escaped="false"
            data-popper-placement="bottom-start"
            bis_skin_checked="1"><a data-rr-ui-dropdown-item="" class="dropdown-item" role="button" tabindex="0" href="#">Available in Draydex Premium</a>

          </div>
        );
      }

      function formatCurrency(value: number | undefined): string {
        return currencyFormatFunc({ value });
      }

      function currencyFormatFunc({ value }: { value: number | undefined; }): string {
        return newFunction_2(value);
      }

      function generateClassName(baseClass: string): string | undefined {
        return generateFunc(baseClass);
      }

      function generateFunc(baseClass: string): string | undefined {
        return funcGen(baseClass, data);
      }

      function grossfuncValue(): string {
        return formatCurrency(grossValue);
      }

      function grossFunc(): string | undefined {
        return generateClassName("form-field w-50 form-control");
      }

      function accessorialcostFunc(): string {
        return formatCurrency(totalCost);
      }

      function accessorialFunc(): string | undefined {
        return generateClassName("form-field w-50 form-control");
      }

      function costValue(index3: any): string | number | string[] | undefined {
        return accessorialCost[index3] ?? costData[index3] ?? "";
      }

  

      function crossChecked(index3: any): boolean | undefined {
        return CrossFunCheckC(requiredForMoveArray, index3);
      }

      function chassisCheck(index3: any): boolean | undefined {
        return chassisCheckFunC(requiredForMoveArray, index3);
      }

      function chassisFunc(): React.ReactNode {
        return validationErrors.chassis && (
          <div className="text-danger">
            {validationErrors.chassis}
          </div>
        );
      }

      function fscVal1(): React.ReactNode {
        return validationErrors.fsc && (
          <div className="text-danger">
            {validationErrors.fsc}
          </div>
        );
      }

      function fscVal(): string | undefined {
        return fscValFunc();
      }

      function fscValFunc(): string | undefined {
        return `form-field w-50 subscreption_plan_status_${(toCheckUserTypeSubscreption(data)) && "free"}`;
      }

      function costFunc() {
        return !item?.accessorial_original_cost
          ? ""
          : item?.accessorial_original_cost?.split(",");
      }

      function lienFunction(): React.ReactNode {
        return validationErrors.linehaul && (
          lienhaulFun()
        );
      }

      function lienhaul1Fun(): string | undefined {
        return `form-field w-50 subscreption_plan_status_${toCheckUserTypeSubscreption(data) && "free"}`;
      }
      function DisabledFun(): string | undefined {
        return toCheckUserTypeSubscreption(data) && "free" ?true:false;
      }

      function lienhaulFun(): React.ReactNode {
        return <div className="text-danger">
          {validationErrors.linehaul}
        </div>;
      }
    });
  }

  function listFunc(): React.ReactNode {
    return list?.map((item, index) => {
      const websiteLink = item?.website?.startsWith("http")
        ? item?.website
        : `http://${item?.website}`;

      const Specialservices = item?.special_services?.split(",");
      const Accessorialcost = item?.assential_service?.length == 0
        ? ""
        : item?.assential_service;
      const essentialService = item?.accessorial_others?.essential_service;
      const essentialArray = Array.isArray(essentialService) && essentialService.length > 0
      ? essentialService.map((item: any) => ({
          [item?.name]: item?.cost,
        }))
      : [];
      const specialArray = Specialservices?.map((item1: any, index1: number) => ({
        [item1]: (Accessorialcost[index1].cost == 0) ? "" : Accessorialcost[index1].cost,
      })) || [];
      const resultAccorials = essentialArray.length > 0 ? [...specialArray, ...essentialArray] : specialArray;
      return (
        <tr key={index}>
          <td className={backgroundColorClass}>
            <a
              target="_blank"
              href={`/carriers/${item?.carrier_id}`}
            >
              {item?.carrier_name}
            </a>
          </td>
          <td className={backgroundColorClass}>
            <div>
              <Row>
                <Col className="d-flex text-end flex-column span-text-market">
                  <span>
                    Linehaul:
                    <span>
                      ${Number(item?.linehaul).toFixed(2)}
                    </span>
                  </span>
                  <span>
                    Fuel (
                    {Number(item?.fuel_surcharge_percent).toFixed(
                      2
                    )}
                    %):
                    <span>
                      {" "}
                      $
                      {Number(
                        item?.linehaul_fuel_percent_price
                      ).toFixed(2)}
                    </span>{" "}
                  </span>
                  <span>
                    Chassis ({item?.per_day} day minium):
                    <span>
                      ${Number(item?.chessis_price).toFixed(2)}
                    </span>
                  </span>
                </Col>
              </Row>
            </div>
          </td>
          <td className={backgroundColorClass}>
            <div>
              <div>
                <Col className="d-flex text-end flex-column span-text-market">
                  {resultAccorials?.map((item1, index3) => {
                    const [label, value] = Object.entries(item1)[0];
                    const numberValue = parseFloat(value);
                    return (
                      <div key={index3}>
                        <span>
                          {label.trim()}:
                          <span>
                            {" "}
                            {isNaN(numberValue) ? "No Cost Found" : `$${Number(numberValue).toFixed(2)}`}
                          </span>
                        </span>
                      </div>
                    );
                  })}
                </Col>
              </div>
              <div className="d-flex">
                <Col>
                  <div className="span-div">
                    <i className="bi bi-tag-fill"></i>
                    <span
                      onClick={() => downloadCSV(item?.carrier_id)}
                    >
                      Accessorials
                    </span>
                  </div>
                </Col>
                {item?.website ? (
                  <div className="span-div">
                    <a
                      className="bi bi-journal-richtext badge_block_modalInput"
                      href={websiteLink}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <span>Terms</span>
                    </a>
                  </div>
                ) : (
                  <p
                    className="bi bi-journal-richtext badge_block_modalInput"
                    onClick={(e) => terms(e)}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <span className="logo-cursor">Terms</span>
                  </p>
                )}
              </div>
            </div>
          </td>
          <td className={`${backgroundColorClass} align-middle`}>
            <p className="totalprice">
              ${Number(item.total_price).toFixed(2)}
            </p>{" "}
          </td>
          <td className={backgroundColorClass}>
            <div>
              {item.capacity}
              <br />
              <p>
                {item.has_capacity === 0 ? "No" : "Yes"} <br></br>{" "}
                {item.earliest_capacity}
              </p>
            </div>
          </td>
        </tr>
      );
    });
  }
};

export default SubmitRateModal;
const newLocal = <thead>
  <tr>
    <th className="th_class w-25">Charge Type</th>
    <th className="th_class w-25">Carrier Charge</th>
    <th className="th_class w-25">
      Required For This Move?
    </th>
    <th className="th_class w-25">Your Charge</th>
  </tr>
</thead>;
function chassisCheckFunC(requiredForMoveArray: any, index3: any): boolean | undefined {
  return requiredForMoveArray &&
    requiredForMoveArray[index3] === 1;
}

function CrossFunCheckC(requiredForMoveArray: any, index3: any): boolean | undefined {
  return requiredForMoveArray &&
    requiredForMoveArray[index3] === 0;
}

function funcGen(baseClass: string, data): string | undefined {
  return `${baseClass} subscreption_plan_status_${toCheckUserTypeSubscreption(data) ? "free" : ""}`;
}

function newFunction_2(value: number | undefined): string {
  return `$${value ? value.toFixed(2) : "0.00"}`;
}

function newFunction_1(formSubmitted: boolean, requiredForMoveArray: any, index3: any, isAccessorialCostValid: (value: any, requiredForMove: any) => boolean, accessorialCost: any[]): React.ReactNode {
  if(formSubmitted && (requiredForMoveArray[index3] === 1) && (accessorialCost[index3] == '' || accessorialCost[index3] == undefined || accessorialCost[index3] == null)){
    return (
      <div className="text-danger">
        Cost is required
      </div>
    )
  }else{
    return formSubmitted &&
      requiredForMoveArray &&
      requiredForMoveArray[index3] === 1 &&
      !isAccessorialCostValid(
        accessorialCost[index3],
        requiredForMoveArray[index3]
      ) && (
        <div className="text-danger">
          Cost must be greater than 0
        </div>
      );
  }
}

function funcGen1
  
  
  (
    
    { handlePlanLeaveEvent, handleFormChange, item, handlePlanHover, lienhaul1Fun, DisabledFun, linehaul, lienFunction, fscVal, fsc, fscVal1, chassis, chassisFunc, resultAccorialss, chassisCheck, crossChecked, cost1Class, requiredForMoveArray, costValue, hoverFunc, formFunc, accessorialFunc, accessorialcostFunc, grossFunc, grossfuncValue, handleAccessorialChargeSelection }: {
  handlePlanLeaveEvent: (e: any) => void; handleFormChange: (
    event: React.ChangeEvent<HTMLInputElement>) => void; item: never; handlePlanHover: (plan: any) => void; lienhaul1Fun: () => string | undefined; DisabledFun:()=>string, linehaul: string; lienFunction: () => React.ReactNode; fscVal: () => string | undefined; fsc: string; fscVal1: () => React.ReactNode; chassis: string; chassisFunc: () => React.ReactNode; resultAccorialss: any; chassisCheck: (index3: any) => boolean | undefined; crossChecked: (index3: any) => boolean | undefined; cost1Class: () => string | undefined; requiredForMoveArray: any; costValue: (index3: any) => string | number | string[] | undefined; hoverFunc: () => React.ReactNode; formFunc: (index3: any) => React.ReactNode; accessorialFunc: () => string | undefined; accessorialcostFunc: () => string; grossFunc: () => string | undefined; grossfuncValue: () => string; handleAccessorialChargeSelection: any;
}
): JSX.Element {
  return <div onMouseLeave={() => handlePlanLeaveEvent()} className="rate_qoute_select_modal modal-table-div">
    {listDiv()}
  </div>;

  function listDiv() {
    return <Table borderless size="sm">
      {newLocal}
      <tbody>
        <tr>
          <td className="lable-info">Linehaul($)</td>
          <td>
            <div>
              <Form.Control
                className="form-field w-50"
                type="text"
                placeholder=""
                disabled={true}
                onChange={handleFormChange}
                value={`$${Number(
                  item?.original_linehaul
                ).toFixed(2)}`} />
            </div>
          </td>
          <td></td>
          <td>
            <div>
              <Form.Control
                onMouseOver={() => handlePlanHover("one")}
                className={lienhaul1Fun()}
                disabled={DisabledFun()}
                type="text"
                name="linehaul"
                onChange={(e) => {
                  if(e.target.value == "" || toValidateCostAndDigit(e.target.value)){
                    handleFormChange(e)
                  }
                }}
                value={linehaul}
                placeholder="Enter Linehaul" />
            </div>

            {lienFunction()}
          </td>
        </tr>
        <tr>
          <td className="lable-info">FSC (%)</td>
          <td>
            <div>
              <Form.Control
                className="form-field w-50"
                value={`${Number(item?.original_fsc).toFixed(
                  2
                )}%`}
                type="text"
                disabled={true}
                placeholder="" />
            </div>
          </td>
          <td></td>
          <td>
            <div>
              <Form.Control
                onMouseOver={() => handlePlanHover("one")}
                className={fscVal()}
                type="text"
                name="fsc"
                disabled={DisabledFun()}
                onChange={(e) => {
                  if(e.target.value == "" || toValidateCostAndDigit(e.target.value)){
                    handleFormChange(e)
                  }
                }}
                placeholder="Enter FSC %"
                value={fsc} />
            </div>
            {fscVal1()}
          </td>
        </tr>
        <tr></tr>
        <tr>
          <td className="lable-info">Chassis ($/day)</td>
          <td>
            <div>
              <Form.Control
                className="form-field w-50"
                type="text"
                placeholder=""
                disabled={true}
                name="chassis"
                value={`$${Number(item?.original_chasis).toFixed(2)}`}
                onChange={handleFormChange} />
            </div>

          </td>
          <td></td>
          <td>
            <div>
              <Form.Control
                onMouseOver={() => handlePlanHover("one")}
                className={lienhaul1Fun()}
                type="text"
                disabled={DisabledFun()}
                placeholder="Enter Chassis"
                name="chassis"
                onChange={(e) => {
                  if(e.target.value == "" || toValidateCostAndDigit(e.target.value)){
                    handleFormChange(e)
                  }
                }}
                value={chassis} />
            </div>
            {chassisFunc()}
          </td>
        </tr>
        {resultAccorialss?.map((item1, index3) => (
          <tr key={index3}>
            <td className="lable-info">
              {Object.keys(item1)[0]}:
            </td>
            <td>
              <div>
                <Form.Control
                  className="form-field w-50"
                  type="text"
                  disabled={true}
                  value={`$${Number(
                    item1[Object.keys(item1)[0]]
                  ).toFixed(2)}`}
                  placeholder="" />
              </div>
            </td>
            <td>
              <div className="badge_block_modal badge_block_modalcss">
                <div className="float-right ">
                  <input
                    value="1"
                    type="radio"
                    className="btn-check"
                    autoComplete="off"
                    checked={chassisCheck(index3)}
                    id={`option-table-yes-${index3}`} 
                    onClick={() => handleAccessorialChargeSelection(item1, index3, 'yes')}
                    name={`accessorial-charge-selection-${index3}`} 
                  />
                  <label
                    className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                    htmlFor={`option-table-yes-${index3}`}
                  >
                    Yes
                  </label>
                </div>

                <span className="span-cross-rate">/</span>

                <div>
                  <input
                    value="0"
                    type="radio"
                    className="btn-check"
                    autoComplete="off"
                    checked={crossChecked(index3)}
                    id={`option-table-no-${index3}`}
                    onClick={() => handleAccessorialChargeSelection(item1, index3, 'no')}
                    name={`accessorial-charge-selection-${index3}`} 
                  />
                  <label
                    className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                    htmlFor={`option-table-no-${index3}`}
                  >
                    No
                  </label>
                </div>
              </div>
            </td>

            <td>
              <div>
                <Form.Control
                  onMouseOver={() => handlePlanHover("one")}
                  className={cost1Class()}
                  disabled={DisabledFun()}
                  type="text"
                  name="accessorial_cost"
                  data-index={index3}
                  data-move={requiredForMoveArray[index3]}
                  onChange={(e) => {
                    if(e.target.value == "" || toValidateCostAndDigit(e.target.value)){
                      handleFormChange(e)
                    }
                  }}
                  value={costValue(index3)}
                  placeholder="Enter Cost" />

                {formFunc(index3)}
              </div>
            </td>
          </tr>
        ))}
        {hoverFunc()}

        <tr>
          <td></td>
          <td className="lable-info etotal">
            Estimated Total:
          </td>
          <td></td>
          <td>
            <div>
              <input
                onMouseOver={() => handlePlanHover("one")}
                name="accessorial_cost"
                disabled={true}
                data-index="0"
                placeholder="ESTIMATED TOTAL"
                type="text"
                className={accessorialFunc()}
                value={accessorialcostFunc()} />
            </div>
          </td>
        </tr>
        <tr>
          <td></td>
          <td className="lable-info etotal">Gross Margin:</td>
          <td></td>
          <td>
            <div>
              <input
                onMouseOver={() => handlePlanHover("one")}
                name="accessorial_cost"
                disabled={true}
                data-index="0"
                placeholder="GROSS MARGIN"
                type="text"
                className={grossFunc()}
                value={grossfuncValue()} />
            </div>
          </td>
        </tr>
      </tbody>
    </Table>;
  }
}

