import React, { useState, useEffect, useRef } from "react";
import { useSession } from "next-auth/react";
import "react-bootstrap-typeahead/css/Typeahead.css";
import { ToastContainer, toast } from "react-toastify";
import { sub_specialServices } from "@/helpers/constants/static/values";

import {
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  Form,
  Row,
  Col,
  FormLabel,
  Table,
  Accordion,
} from "react-bootstrap";
import {
  AddSpotRates,
  AddRatesNotificationCarrier,
  getMapCarriers,
  GetAccesorCustomerAmount,
  GetallAccesorCustomerAmount,
  CustomersDieselprice,
} from "@/services/public";
import ProtectedRoute from "@/ProtectedRoute";
import Toaster from "../../../assets/common/Toaster";
import { ScaleLoader, ClipLoader} from "react-spinners";
import { formatPhoneNumber } from "@/utils/regex/regex";
import { toValidateCostAndDigit } from "@/helpers/projectHelper";
interface Accessorial {
  move?: string;
  name: string;
  code: string;
  cost: number;
}
const minChassisDay = [1, 2, 3];
interface MyCarrier {
  label: string;
  value: number;
}

interface AddRateModalProps {
  show: boolean;
  handleClose: () => void;
  rateQuotesId: number | null;
}

const AddRateModal: React.FC<AddRateModalProps> = ({
  selectedSpecialServices,
  dieselprice,
  show,
  handleClose,
  rateQuotesId,
  refresh,
  propData,
  setNotify,
}) => {
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [costValidationErrors, setCostValidationErrors] = useState([""]);
  const [showDropdown, setShowDropdown] = useState(false);
  const [subnewService, setsubnewService] = useState([""]);
  const [namesToRemove, setNamesToRemove] = useState([""]);
  const [disabledServices, setDisabledServices] = useState<string[]>([""]);
  const [selectedMinChassisDay, setSelectedMinChassisDay] = useState("");
  const [table, setTable] = useState(false);
  const [carrierId, setCarrierId] = useState("");

  const [isListVisible, setListVisible] = useState(false);
  const [status, setstatus] = useState(false);

  const [rows, setRows] = useState<Accessorial[]>([]);
  const [isloading, setIsloading] = useState();
  const [disable, setDisable] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [options, setOptions] = useState([]);
  const [selectedOption, setSelectedOption] = useState(null);
  const [fetchedAmounts, setFetchedAmounts] = useState([]);
  const [validationStatus, setValidationStatus] = useState(
    new Array(rows.length).fill(false),
  );
  const [preloaderStatus, setPreloaderStatus] = useState(false);

  const selectRef = useRef<HTMLSelectElement>(null);

  const handleRadioChange1 = (newValue: boolean) => {
    setDisable(newValue);
    setFormValues({
      ...formValues,
      earliest_capacity: "",
    });
  };

  const [selectedSpecialServiceValues, setSelectedSpecialServiceValues] =
    useState(
      selectedSpecialServices.map((_, indexx) => {
        return fetchedAmounts[indexx] !== null ? fetchedAmounts[indexx] : "";
      }),
    );
  useEffect(() => {
    const initialSpecialServiceValues = selectedSpecialServices.map((_, i) => {
      return fetchedAmounts[i] !== null ? fetchedAmounts[i] : "";
    });
    setSelectedSpecialServiceValues(initialSpecialServiceValues);
  }, [fetchedAmounts, selectedSpecialServices]);

  const handleRadioChange = (index: number, value: string) => {

    const newRows = [...rows];
    newRows[index].move = value;
    setRows(newRows);
  };

  const [validationErrors, setValidationErrors] = useState({
    carrier: "",
    linehaul: "",
    fsc: "",
    chassis: "",
    accessorials: "",
    has_capacity: "",
    earliest_capacity: "",
    minChassisDay: "",
  });

  const [accessorialCostValidationErrors, setAccessorialCostValidationErrors] = useState([""]);
  const [accessorialNameValidationErrors, setAccessorialNameValidationErrors] = useState([""]);
  const [viewAllMarketsHoverIndex, setViewAllMarketsHoverIndex] = useState<number | null>(null);

  const formValuesInitialState = {
    carrier: "",
    linehaul: "",
    fsc: dieselprice || "",
    chassis: "",
    minChassisDay: "",
    accessorials: [] as Accessorial[],
    has_capacity: "",
    earliest_capacity: "",
    note: "",
  };

  const { data } = useSession();

  const accessToken = data?.user?.image;
  const [formValues, setFormValues] = useState(formValuesInitialState);
  const validateForm = (index) => {
    let isValid = true;
    const errors = {
      carrier: "",
      linehaul: "",
      fsc: "",
      chassis: "",
      accessorials: "",
      has_capacity: "",
      earliest_capacity: "",
    };

    if (!searchTerm && !(data?.user?.name && data?.user?.group_type === "carriers")) {
      errors.carrier = "Carrier is required";
    }

    if (!formValues.linehaul) {
      errors.linehaul = "Linehaul is required";
      isValid = false;
    }
    if (!formValues.fsc) {
      errors.fsc = "FSC is required";
      isValid = false;
    }
    if (disable ? !formValues.earliest_capacity : "") {
      errors.earliest_capacity = "Earliest Capacity date is required";
      isValid = false;
    }
    if (!formValues.chassis) {
      errors.chassis = "Chassis is required";
      isValid = false;
    }

    if (!selectedMinChassisDay) {
      errors.minChassisDay = "Min. Chassis Day is required";
      isValid = false;
    }
    setValidationErrors(errors);
    return isValid;
  };

  useEffect(() => {
    if (dieselprice !== undefined) {
      setFormValues((prevValues) => ({
        ...prevValues,
        fsc: dieselprice,
      }));
    }
  }, [dieselprice]);
  const handleClearValues = () => {
    setFormValues(formValuesInitialState);
    setValidationErrors({
      carrier: "",
      linehaul: "",
      fsc: "",
      chassis: "",
      accessorials: "",
      has_capacity: "",
      earliest_capacity: "",
    });
    setSearchTerm("");
    setRows([]);

    setSelectedSpecialServiceValues("");
    setValidationStatus("");
    setCostValidationErrors("");
  };

  const handleDropdownChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
    
    const selectedCode = e.target.value;
    if (selectRef.current) {
      selectRef.current.value = "";
    }
    if (
      !carrierId &&
      data?.user?.name &&
      data?.user?.group_type === "customers"
    ) {
      toast.error("Please Select Carrier Name/DOT#", {
        position: toast.POSITION.TOP_CENTER,
      });
      return;
    }
    setValidationErrors({
      ...validationErrors,
      accessorials: "",
    });
    try {
      const res = await GetAccesorCustomerAmount(
        accessToken,
        selectedCode,
        data?.user?.group_type === "carriers"
          ? data?.user?.carrier_id
          : carrierId,
      );
  
      if (res?.data) {
        const costFromApi = res.data[0]?.amount;
        const selectedAccessory = subnewService.find(
          (item) => item.service_code === selectedCode,
        );
        if (!selectedAccessory) return;

        if (disabledServices.includes(selectedAccessory.service_name)) {
          toast.warn("Selected Option already exists..", {
            position: "top-center",
            autoClose: 5000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "light",
          });
        } else {
          const newRow = {
            name: selectedAccessory.service_name,
            code: selectedAccessory.service_code,
            cost: data?.user?.group_type === "super_admin" ? "" : costFromApi,
            move: "no",
          };
          setTable(true);
          setRows([...rows, newRow]);
        }
      }
    } catch (error) {
      return error;
    }
  };

  useEffect(() => {
    if (selectedSpecialServices) {
      const disabledServiceNames = selectedSpecialServices.map(
        (item) => item?.service_name,
      );
      setDisabledServices(disabledServiceNames);
    }
  }, [selectedSpecialServices]);

  const handleAccessorialsCostChange = (index: number, cost: string) => {
    if (formSubmitted) {
      const updatedErrors: any = [...accessorialCostValidationErrors];
      if (parseFloat(cost) === 0) {
        updatedErrors[index] = {
          message: "Require a number greater than $0",
          type: "manual"
        };
      } else if(cost === ''){
        updatedErrors[index] = {
          message: "Cost is required",
          type: "manual"
        };
      } else {
        updatedErrors[index] = "";
      }
      const updatedRows = [...rows];
      updatedRows[index].cost = parseFloat(cost);
      setRows(updatedRows);
      setAccessorialCostValidationErrors(updatedErrors);
    }
  };

  useEffect(() => {
    const sortedSpecialServices = [...sub_specialServices].sort((a, b) => 
      a.service_code.localeCompare(b.service_code)
    );
    setsubnewService(sortedSpecialServices);
  }, [sub_specialServices]);

  const showing = (row) => {
    const shouldRemoveName = row?.name;
    if (shouldRemoveName) {
      if (!namesToRemove.includes(row.name)) {
        setNamesToRemove([...namesToRemove, row.name]);
      }
    }
  };

  useEffect(() => {
    if (namesToRemove.length > 0) {
      setNamesToRemove(namesToRemove.slice(1));
    }
  }, [namesToRemove, subnewService]);

  useEffect(() => {
    if (rows?.length === 0) {
      setShowDropdown(!showDropdown);
    }
  }, [rows]);

  const hideRow = (rowToRemove: Accessorial, indexToRemove: number) => {
    setRows(rows.filter((row, index) => {
      return !(row.code === rowToRemove.code && index === indexToRemove);
    }));
  };

  useEffect(() => {
    if (rows?.length === 0) {
      setTable(false);
    }
    if (selectedSpecialServices?.length > 0) {
      setTable(true);
    }
  }, [hideRow]);
  const handleAddMoreClick = () => {
    setShowDropdown(!showDropdown);
  };

  useEffect(() => {
    setFormSubmitted(true);
  }, []);
  const val = () => {
    const numServices = selectedSpecialServices.length;
    const numRows = rows.length;
    const initialServiceValues = Array(numServices).fill("");
    setSelectedSpecialServiceValues(initialServiceValues);
    const validationErrors = Array(numServices).fill("");
    const rowValidationErrors = Array(numRows).fill("");
    const nameValidationErrors = Array(numRows).fill("");
    let hasError = false;
    let statusFlag = true;
    const validateCost = (value: any, type: 'selected' | 'manual') => {
      const cost = parseFloat(value);
      if (cost === 0) {
        return { message: "Require a number greater than $0", type };
      }
      if (isNaN(cost) || !isFinite(cost)) {
        return { message: "Cost is required", type };
      }
      return null;
    };
    const sanitizeAndValidateName = (value: string, index: number) => {
      const sanitized = value.replace(/[^a-zA-Z\s]/g, '').slice(0, 40);
      if (sanitized.trim() === "") {
        nameValidationErrors[index] = "Accessorial is required";
        hasError = true;
      } else {
        nameValidationErrors[index] = "";
      }
    };
    // Validate selected special service values
    for (let i = 0; i < numServices; i++) {
      const value = selectedSpecialServiceValues[i];
      const error = validateCost(value, 'selected');
      if (error) {
        validationErrors[i] = error;
        hasError = true;
        statusFlag = error.type === 'manual';
      }
      handleSpecialServiceValueChange(i, value);
    }
    // Validate rows: cost and name
    for (let i = 0; i < numRows; i++) {
      const row = rows[i];
      const costError = validateCost(row.cost, 'manual');
      if (costError) {
        rowValidationErrors[i] = costError;
        hasError = true;
        statusFlag = costError.type === 'manual';
      }
  
      sanitizeAndValidateName(row.name, i);
    }
    setCostValidationErrors(validationErrors);
    setAccessorialCostValidationErrors(rowValidationErrors);
    setAccessorialNameValidationErrors(nameValidationErrors);
    setstatus(statusFlag);
    return hasError ? "failed" : "successful";
  };

  useEffect(() => {
    if (rows?.length === 0) {
      setShowDropdown(false);
    } else {
      setShowDropdown(true);
    }
  }, [rows]);

  const fetchVaild = async () => {

    const otherItems = rows.filter(item => item.code === "other").map((item, index) => ({
                          ...item,
                          code: `other${index + 1}`,
                          move: (item?.move === 'yes') ? 1 : 0
                        }));
    const differentItems = rows.filter(item => item.code !== "other");
    const payloadRows = differentItems
      .map((row) => ({
        name: row.name,
        cost: row.cost,
      }));
    const prevAccess = payloadRows?.map((row) => row.name);
    const newAccess = selectedSpecialServices?.map((row) => row.service_name);
    const access = prevAccess?.concat(newAccess);
    const payload = {
      carrier_name:
        data?.user?.billing_company && data?.user?.group_type === "carriers"
          ? data?.user?.billing_company
          : searchTerm,
      carrier_id:
        data?.user?.name && data?.user?.group_type === "carriers"
          ? data?.user?.carrier_id
          : selectedOption?.id,
      quote_id: rateQuotesId || null,
      linehaul: formValues.linehaul || 0,
      fsc: formValues.fsc,
      chassis: formValues.chassis,
      rate_notes: formValues?.note,
      accessorial_name: access,
      accessorial_cost: [
        ...payloadRows.map((row) => row.cost),
        ...(Array.isArray(selectedSpecialServiceValues)
          ? selectedSpecialServiceValues.map((value) => parseFloat(value))
          : []),
      ],
      accessorial_charges_code: [
        ...differentItems.map((row: any) => {
          return row.code;
        }),
        ...selectedSpecialServices?.map((service: any) => {
          return service.service_code;
        }) || [],
      ],
      per_day: selectedMinChassisDay || "",
      required_for_move:[
        ...differentItems.map((row: any) => {
          return row.move === 'yes' ? 1 : 0;
        }),
        ...selectedSpecialServices?.map(() => 1) || [],
      ],
      earliest_capacity: formValues?.earliest_capacity,
      has_capacity: disable ? 1 : 0,
      others: otherItems
    };

    setPreloaderStatus(true);
    const res = await AddSpotRates(accessToken, payload);
    if (res.status === "success") {
      const  notifyPayload={
        user_id:propData?.data?.user_id,
        quote_id:payload?.quote_id,
        carrier_id:payload?.carrier_id,
        rate_id:res?.data?.rate_id,
        type:data?.user?.group_type === "carriers" ? "add_rate_by_carrier":"rate_create"
        }
         
       await AddRatesNotificationCarrier(accessToken,notifyPayload);
      setNotify(true)
      validateForm("");
      
      setIsloading(false);
      handleClearValues();
      toast.success(res?.message, {
        position: toast.POSITION.TOP_CENTER,
      });
      setFetchedAmounts([]);
      setCarrierId("");
      handleClearValues();
      refresh(true)
      setTable(false);
      setPreloaderStatus(false);
      handleClose();
    }
    if (res?.status_code === 500) {
      setIsloading(false);
      setPreloaderStatus(false);
      toast.error(res?.message, {
        position: toast.POSITION.TOP_CENTER,
      });
    }
    setIsloading(false);
  };
  const handleSubmit = async () => {
    let valid = validateForm();
    let validator = val();
    if (validator === "failed") {
      return;
    }
    setFormSubmitted(true);
    if (valid) {
      fetchVaild();
    }
  };

  useEffect(() => {
    if (rows?.length === 0) {
      setTable(true);
    }
  }, [rows]);
  useEffect(() => {
    if (selectedSpecialServices?.length > 0) {
      setTable(true);
    } else {
      setTable(false);
    }
  }, [selectedSpecialServices]);

  const isSpecialServiceSelected = (service) => {
    if (rows.some(row => row.code === "other" && row.code === service.service_code)) {
      return false;
    }

    return (
      rows.some((row) => row.name === service.service_name) ||
      disabledServices.includes(service.service_name)
    );
  };

  const handleSpecialServiceValueChange = (index: number, value: string) => {
    if (selectedSpecialServices?.length > 0 && formSubmitted) {
      const updatedErrors: any = [...costValidationErrors];
      if (parseFloat(value) === 0) {
        updatedErrors[index] = {
          message: "Require a number greater than $0",
          type: "selected",
        };
      }else if(value === ""){
        updatedErrors[index] = {
          message: "Cost is required",
          type: "selected"
        };
      }else {
        updatedErrors[index] = "";
      }
      setSelectedSpecialServiceValues((prevValues: any) => {
        const updatedValues = [...prevValues];
        updatedValues[index] = value;
        return updatedValues;
      });
      setCostValidationErrors(updatedErrors);
    }
  };

  const handleInputChange = (value) => {
    setSearchTerm(value);
    data?.user?.group_type === "carriers"
      ? setListVisible(false)
      : setListVisible(true);
  };
  const fetchAmounts = async (id: any) => {
    try {
      const amounts = [];
      const serviceCodes = selectedSpecialServices.map(
        (item) => item.service_code,
      );

      const res = await GetallAccesorCustomerAmount(
        accessToken,
        serviceCodes,
        data?.user?.group_type === "carriers" ? data?.user?.carrier_id : id,
      );

      const amountMap = {};
      res?.data.forEach((item) => {
        amountMap[item.accessorial_charges_code] = parseFloat(item.amount);
      });

      selectedSpecialServices.forEach((service) => {
        const amount = amountMap[service.service_code];
        amounts.push(amount !== undefined ? amount : null);
      });

      setFetchedAmounts(amounts);
    } catch (error) {
      return error;
    }
  };

  const Diesel = async (option: any) => {
    setIsloading(true)
    let res = await CustomersDieselprice(
      accessToken,
      data?.user?.group_type === "carriers"
        ? data?.user?.carrier_id
        : option?.id,
    );
    if (res?.status === "success") {
      setIsloading(false)
    }

    setFormValues({
      ...formValues,
      fsc: res?.data,
    });
  }
  
  const handleOptionSelect =  (option) => {
    fetchAmounts(option?.id);
    setCarrierId(option?.id);
    Diesel(option)
    setSelectedOption(option);
    setValidationErrors({ ...validationErrors, carrier: "" });
    setSelectedOption(option);
    setListVisible(false);
    setSearchTerm(option.label);
  };
  useEffect(() => {
    const fetchPrice = async () => {
      setIsloading(true)
      let res = await CustomersDieselprice(accessToken, data?.user?.carrier_id);
      setFormValues((prevValues) => ({
        ...prevValues,
        fsc: res?.data,
      }));
      if (res?.status === "success") {
        setIsloading(false)

      }
    };
    if (data?.user?.group_type === "carriers" && show) {
      fetchPrice();
      fetchAmounts();
    }
  }, [show, data?.user?.group_type]);
  const fetchdata = () => {
    getMapCarriers(accessToken, searchTerm, "", "").then((response) => {
      if (response.status === "success") {
        const formattedCarriers = response.data.map((carrier) => ({
          id: carrier?.carrier_id,
          label: carrier?.billing_company,
          value: carrier?.carrier_id?.toString(),
          phone: carrier?.phone,
          markets: carrier?.markets
        }));

        setOptions(formattedCarriers);
      }
    });
  };
  useEffect(() => {
    fetchdata();
  }, [searchTerm]);

  useEffect(() => {
    if (searchTerm.trim() === "") {
      setListVisible(false);
      setOptions([]);
    }
  }, [searchTerm]);

  const handleOtherFieldChange = (rowIndex: number, rowData: any, allRowData: any)=>{
    const lettersOnly = rowData.replace(/[^a-zA-Z\s]/g, '');
    const finalData = lettersOnly.slice(0, 40);
    const updatedRows = [...rows];
    updatedRows[rowIndex].name = finalData;
    setRows(updatedRows);
  
    const updatedErrors: any = [...accessorialNameValidationErrors];
    if(finalData === ''){
      updatedErrors[rowIndex] = "Accessorial is required";
    } else {
      updatedErrors[rowIndex] = "";
    }
    setAccessorialNameValidationErrors(updatedErrors);
  }

  return (
    <Modal
      className="modal_main modal-lg modal_main"
      show={show}
      centered
      backdrop="static"
      onHide={handleClose}
    >
      <ToastContainer />
      {isloading && (
        <div id="loader_table">
          <ScaleLoader color="#3180f3" className="table_loader" />
        </div>
      )}
      <ModalHeader className="border-bottom-0 justify-content-end" />
      <Form>
        <ModalBody>
          <div className="text-center mb-3">
            <h4 className="modal_h4">Manually Add Carrier Spot Rate</h4>
          </div>
          <div className="main_modal">
            <Row>
              <Col>
                <div className="mb-2">
                  <FormLabel htmlFor="port_ramp">Carrier Name / DOT#</FormLabel>
                  <div className="searchable-list">
                    <input
                      className="form-field form-control"
                      type="text"
                      placeholder="Enter Carrier Name / DOT#"
                      value={
                        data?.user?.billing_company &&
                        data?.user?.group_type === "carriers"
                          ? data?.user?.billing_company
                          : searchTerm
                      }
                      onChange={(e) => handleInputChange(e.target.value)}
                    />
                    {isListVisible && (
                      <ul className="searchable-list-options">
                        {options.length > 0 ? (
                          options.map((option: any, index: number) => (
                            <li
                              key={option.id}
                              onClick={() => {
                                handleOptionSelect(option);
                              }}
                            >
                              <div className="d-flex justify-content-between">
                                <div className="col-5">
                                  {option?.label ?? 'N/A'}
                                </div>
                                <div className="col-5 d-flex justify-content-between manual-add-spot-rate-modal-market">
                                  <div className="col-6">
                                    {option?.markets?.length > 0 ? option.markets[0] : 'N/A'}
                                  </div>
                                  <div
                                    className="col-6 text-center position-relative"
                                    onMouseEnter={() => setViewAllMarketsHoverIndex(index)}
                                    onMouseLeave={() => setViewAllMarketsHoverIndex(null)}
                                  >
                                    {option?.markets?.length > 1 && (
                                      <a 
                                        href="#" 
                                        onClick={(e) => e.preventDefault()}
                                      >
                                        View Markets
                                      </a>
                                    )}
                                    {option?.markets?.length > 1 && viewAllMarketsHoverIndex === index && (
                                       <div className="market-hover-content">
                                        {option?.markets?.slice(1).map((marketData: string, marketIndex: number) => (
                                          <div key={marketIndex}>
                                            {marketData}
                                          </div>
                                        ))}
                                      </div>
                                    )}
                                  </div>
                                </div>
                                <div className="col-2 text-end">
                                  {(option?.phone) ? formatPhoneNumber(option?.phone) : 'N/A'}
                                </div>
                              </div>
                            </li>
                          ))
                        ) : (
                          <li>No record found</li>
                        )}
                      </ul>
                    )}
                  </div>

                  {validationErrors.carrier && (
                    <div className="text-danger">
                      {validationErrors.carrier}
                    </div>
                  )}
                </div>
              </Col>
            </Row>
            <Row>
              <Col>
                <Col>
                  <div className="mb-2 d-flex gap-3">
                    <Col>
                      <div className="quote_inputBlock">
                        <div className="mb-2">
                          <FormLabel htmlFor="port_ramp">
                            Linehaul ($)
                          </FormLabel>
                          <Form.Control
                            type="number"
                            className="form-field"
                            placeholder="Enter Linehaul"
                            value={formValues.linehaul}
                            onChange={(e) => {
                              const value = e.target.value;
                              if (value == "" || toValidateCostAndDigit(value)) {
                                setFormValues({
                                  ...formValues,
                                  linehaul: value,
                                });
                                setValidationErrors({
                                  ...validationErrors,
                                  linehaul: "",
                                });
                              }
                            }}
                          />
                          {validationErrors.linehaul && (
                            <div className="text-danger">
                              {validationErrors.linehaul}
                            </div>
                          )}
                        </div>
                      </div>
                    </Col>
                    <Col>
                      <div className="quote_inputBlock">
                        <div className="mb-2">
                          <FormLabel htmlFor="port_ramp">FSC (%)</FormLabel>
                          <Form.Control
                            type="text"
                            className="form-field"
                            placeholder="Enter FSC"
                            value={formValues.fsc}
                            onChange={(e) => {
                              const inputValue = e.target.value;
                              const validInput = /^\d+(\.\d{0,2})?$/.test(
                                inputValue,
                              );

                              if (inputValue === "") {
                                setFormValues({
                                  ...formValues,
                                  fsc: "",
                                });
                                setValidationErrors({
                                  ...validationErrors,
                                  fsc: "",
                                });
                              } else {
                                if(toValidateCostAndDigit(inputValue)){
                                  setFormValues({
                                    ...formValues,
                                    fsc: validInput ? inputValue : formValues.fsc,
                                  });
                                  setValidationErrors({
                                    ...validationErrors,
                                    fsc: validInput,
                                  });
                                }
                              }
                            }}
                          />

                          {validationErrors.fsc && (
                            <div className="text-danger">
                              {validationErrors.fsc}
                            </div>
                          )}
                        </div>
                      </div>
                    </Col>
                    <Col>
                      <div className="quote_inputBlock">
                        <div className="mb-2">
                          <FormLabel htmlFor="port_ramp">
                            Chassis ($/day)
                          </FormLabel>
                          <Form.Control
                            type="number"
                            className="form-field"
                            placeholder="Enter Chassis"
                            value={formValues.chassis}
                            onChange={(e) => {
                              if(e.target.value == '' || toValidateCostAndDigit(e.target.value)){
                                setFormValues({
                                  ...formValues,
                                  chassis: e.target.value,
                                });
                                setValidationErrors({
                                  ...validationErrors,
                                  chassis: "",
                                });
                              }
                            }}
                          />
                          {validationErrors.chassis && (
                            <div className="text-danger">
                              {validationErrors.chassis}
                            </div>
                          )}
                        </div>
                      </div>
                    </Col>
                    <Col>
                      <FormLabel htmlFor="port_ramp">
                        Min. Chassis Day
                      </FormLabel>
                      <div className="badge_block">
                        {minChassisDay?.map((item, index) => (
                          <React.Fragment key={item}>
                            <div className={index < 1 ? "float-right" : ""}>
                              <input
                                type="radio"
                                className="btn-check"
                                name="options-chassis-day"
                                id={`option-day0${index}`}
                                autoComplete="off"
                                checked={selectedMinChassisDay === item}
                                onChange={() => {
                                  setSelectedMinChassisDay(item);
                                  setValidationErrors({
                                    ...validationErrors,
                                    minChassisDay: "",
                                  });
                                }}
                              />
                              <label
                                className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                                htmlFor={`option-day0${index}`}
                                style={{ width: "25px" }}
                              >
                                {item}
                              </label>
                            </div>
                            <span
                              className={`${
                                minChassisDay.length - 1 === index
                                  ? "d-none"
                                  : ""
                              } span-cross-rate`}
                            >
                              /
                            </span>
                          </React.Fragment>
                        ))}
                      </div>
                      {validationErrors.minChassisDay && (
                        <div className="text-danger">
                          {validationErrors.minChassisDay}
                        </div>
                      )}
                    </Col>
                  </div>
                </Col>
                <Col>
                  <div className="mb-2">
                    <FormLabel htmlFor="port_ramp" onClick={handleAddMoreClick}>
                      Add Accessorials{" "}
                      <span className="span-add mx-3 icon-css">
                        <i className="bi bi-plus-circle-fill"></i>
                      </span>
                    </FormLabel>
                    {validationErrors.accessorials && (
                      <div className="text-danger">
                        {validationErrors.accessorials}
                      </div>
                    )}
                    {showDropdown && (
                      <div className="d-flex gap-3 justify-content-between">
                        <div className="w-50">
                          <Accordion>
                            <Accordion.Item eventKey="0">
                              <select
                                ref={selectRef}
                                className="form-field"
                                onChange={handleDropdownChange.bind(this)}
                              >
                                <option disabled selected value="">
                                  Select Accessorials
                                </option>
                                {subnewService?.map((item: any, index: number) => (
                                  <option
                                    key={index}
                                    value={item?.service_code}
                                    disabled={isSpecialServiceSelected(item)}
                                  >
                                    {item?.service_name}
                                  </option>
                                ))}
                              </select>
                            </Accordion.Item>
                          </Accordion>
                        </div>
                      </div>
                    )}
                  </div>
                </Col>
                <Col>
                  <div className="modal-table-div add_rate_table_modal">
                    <Table borderless size="sm">
                      {table ? (
                        <thead>
                          <tr>
                            <th className="th_class w-25">Accessorial Name</th>
                            <th className="th_class w-25">Cost</th>
                            <th className="th_class w-25">
                              Required For This Move?
                            </th>
                            <th className="th_class w-25">Action</th>
                          </tr>
                        </thead>
                      ) : (
                        ""
                      )}
                      <tbody>
                        {selectedSpecialServices.map((specialService, index) => (
                          <tr key={`specialService-${index}`}>
                            <td>
                              {(specialService?.service_code === 'other') ? 
                                <input 
                                  type="text"
                                  className="form-control"
                                  pattern="[A-Za-z]+"
                                  inputMode="text"
                                  onChange={(e)=>handleOtherFieldChange(index, e.target.value, specialService)}
                                  value={specialService.name}
                                /> 
                                : specialService.service_name 
                              }
                            </td>
                            <td>
                              <input
                                type="number"
                                className="form-control manually_add_carrier_spot_rate_cost"
                                defaultValue={fetchedAmounts[index]}
                                value={selectedSpecialServiceValues[index]}
                                onChange={(e) =>{
                                    if(e.target.value == '' || toValidateCostAndDigit(e.target.value)){
                                      handleSpecialServiceValueChange(
                                        index,
                                        e.target.value,
                                      )
                                    }
                                }}
                              />
                              {(!fetchedAmounts[index] ||
                                selectedSpecialServiceValues[index] === "") &&
                                costValidationErrors[index]?.type === 'selected' && (
                                  <div className="text-danger">
                                    {costValidationErrors[index]?.message}
                                  </div>
                                )}
                            </td>
                            <td>
                              <div
                                className="badge_block_modal"
                                style={{ backgroundColor: "#30b7f7" }}
                              >
                                <div className="float-right">
                                  <input
                                    value="yes"
                                    type="radio"
                                    className="btn-check"
                                    autoComplete="off"
                                    disabled={true}
                                    checked={true}
                                  />
                                  <label
                                    className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                                    htmlFor={`option-table-yes-${index}`}
                                  >
                                    Yes
                                  </label>
                                </div>
                                <span className="span-cross-rate">/</span>
                                <div>
                                  <input
                                    value="no"
                                    type="radio"
                                    className="btn-check"
                                    disabled={true}
                                    autoComplete="off"
                                  />
                                  <label
                                    className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                                    htmlFor={`option-table-no-${index}`}
                                  >
                                    No
                                  </label>
                                </div>
                              </div>
                            </td>
                          </tr>
                        ))}
                        {rows?.map((row, index) => (
                          <tr key={index}>
                            <td>
                              {(row?.code === 'other') ? 
                                <div>
                                  <input 
                                    type="text"
                                    className="form-control"
                                    onChange={(e)=>{
                                      handleOtherFieldChange(index, e.target.value, row);
                                    }}
                                    value={row.name}
                                  />
                                  {accessorialNameValidationErrors[index] && (
                                    <div className="text-danger">
                                      {accessorialNameValidationErrors[index]}
                                    </div>
                                  )}
                                </div>
                                : row.name 
                              }
                            </td>
                            <td>
                              <input
                                type="number"
                                className="form-control manually_add_carrier_spot_rate_cost"
                                value={row.cost}
                                onChange={(e) => {
                                  if(e.target.value == '' || toValidateCostAndDigit(e.target.value)){
                                    handleAccessorialsCostChange(
                                      index,
                                      e.target.value,
                                    )
                                  }
                                }}
                              />
                              {accessorialCostValidationErrors[index]?.type === 'manual' && (
                                <div className="text-danger">
                                  {accessorialCostValidationErrors[index]?.message}
                                </div>
                              )}
                            </td>
                            <td>
                              <div
                                className="badge_block_modal"
                                style={{ backgroundColor: "#30b7f7" }}
                              >
                                <div className="float-right">
                                  <input
                                    value="yes"
                                    type="radio"
                                    className="btn-check"
                                    name={`options-table-radio${index}`}
                                    id={`option-table-yes-${index}`}
                                    autoComplete="off"
                                    checked={
                                      row.move === "yes"
                                    }
                                    onChange={() =>
                                      handleRadioChange(index, "yes")
                                    }
                                  />
                                  <label
                                    className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                                    htmlFor={`option-table-yes-${index}`}
                                  >
                                    Yes
                                  </label>
                                </div>
                                <span className="span-cross-rate">/</span>
                                <div>
                                  <input
                                    value="no"
                                    type="radio"
                                    className="btn-check"
                                    name={`options-table-radio${index}`}
                                    id={`option-table-no-${index}`}
                                    autoComplete="off"
                                    checked={
                                      row.move !== "yes"
                                    }
                                    onChange={() => {
                                      handleRadioChange(index, "no");
                                    }}
                                  />
                                  <label
                                    className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                                    htmlFor={`option-table-no-${index}`}
                                  >
                                    No
                                  </label>
                                </div>
                              </div>
                            </td>

                            <td>
                              <div
                                onClick={() => {
                                  hideRow(row, index);
                                  showing(row);
                                }}
                                className="cancle-icon"
                              >
                                <i className="bi bi-x"></i>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </Table>
                    <Toaster />
                  </div>
                </Col>
                <Col>
                  <div className="d-flex gap-2">
                    <Col>
                      <div className="d-flex gap-2">
                        <div>
                          <FormLabel
                            htmlFor="port_ramp"
                            className="text-center-css"
                          >
                            Carrier has Capacity?
                          </FormLabel>
                        </div>
                        <div className="badge_block w-25">
                          <div className="float-right">
                            <input
                              type="radio"
                              className="btn-check"
                              name="options-carrier"
                              id="option-carrier01-yes"
                              autoComplete="off"
                              checked={disable}
                              onChange={() => {
                                handleRadioChange1(true);
                              }}
                            />
                            <label
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                              htmlFor="option-carrier01-yes"
                            >
                              Yes
                            </label>
                          </div>
                          <div className="float-right">
                            <input
                              type="radio"
                              className="btn-check"
                              name="options-carrier"
                              id="option-carrier01-no"
                              autoComplete="off"
                              checked={!disable}
                              onChange={() => {
                                handleRadioChange1(false);
                                setValidationErrors({
                                  ...validationErrors,
                                  earliest_capacity: "",
                                });
                              }}
                            />
                            <label
                              className="btn btn-outline-warning radio-button-quote border-0 radio-button-bg text-light"
                              htmlFor="option-carrier01-no"
                            >
                              No
                            </label>
                          </div>
                        </div>
                      </div>
                    </Col>
                    <Col>
                      <div className="d-flex gap-2">
                        <div>
                          <FormLabel
                            htmlFor="port_ramp"
                            className="text-center-css"
                          >
                            Earliest Capacity?
                          </FormLabel>
                        </div>
                        <div>
                          <Form.Control
                            disabled={!disable}
                            type="date"
                            className="form-field"
                            placeholder=""
                            value={formValues.earliest_capacity}
                            min={new Date().toISOString().split("T")[0]}
                            onChange={(e) => {
                              setFormValues({
                                ...formValues,
                                earliest_capacity: e.target.value,
                              });
                              setValidationErrors({
                                ...validationErrors,
                                earliest_capacity: "",
                              });
                            }}
                          />

                          {validationErrors.earliest_capacity && (
                            <div className="text-danger">
                              {validationErrors.earliest_capacity}
                            </div>
                          )}
                        </div>
                      </div>
                    </Col>
                  </div>
                </Col>
              </Col>

              <div className="p-1">
                <FormLabel htmlFor="port_ramp" className="text-center-css">
                  Note{" "}
                </FormLabel>
                <Form.Control
                  as="textarea"
                  style={{ width: "96%" }}
                  className="form-control m-1  "
                  id="exampleFormControlTextarea1"
                  name="notes_for_carrier"
                  value={formValues.note}
                  onChange={(e) => {
                    setFormValues({
                      ...formValues,
                      note: e.target.value,
                    });
                  }}
                  rows={5}
                  placeholder="Note"
                  maxLength={250}
                />
              </div>
            </Row>
          </div>
        </ModalBody>
        <ModalFooter className="quote_btn_block mt-3">
          <Button
            disabled={preloaderStatus}
            type="button"
            className="btn btn-success w-25 btn-modal"
            onClick={!preloaderStatus ? () => handleSubmit() : undefined}
          >
            <span className="d-flex justify-content-center align-items-center gap-2">
              {preloaderStatus && (
                <ClipLoader 
                  size={23}
                />
              )} Submit
            </span>
          </Button>

          <Button
            type="button"
            className="btn btn-secondary w-25 btn-close-modal"
            data-dismiss="modal"
            onClick={() => {
              handleClearValues();
              handleClose();
              setListVisible(false);
              setShowDropdown(!showDropdown);
              setFetchedAmounts([]);
              setCarrierId("");
            }}
          >
            Cancel
          </Button>
        </ModalFooter>
      </Form>
    </Modal>
  );
};

export default ProtectedRoute(AddRateModal);