import React, { useState, useEffect } from "react";
import { getMyFavCarriers, favList } from "../../../services/customers";
import {
  CarrierMapForSendToCarrier,
  SendCarriers,
  getFavCarriersStatus,
  getMapCarriers,
} from "../../../services/public";
import { useSession } from "next-auth/react";
import { ScaleLoader } from "react-spinners";
import CustomSearchDropdown from "./CustomSearchDropdown";
import { ToastContainer, toast } from "react-toastify";
import { useRouter } from "next/router";

import {
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Button,
  FormLabel,
  Form,
  Row,
  Col,
  Table,
} from "react-bootstrap";
import MultiSelectInputFields from "./MultiSelectInputFields";
import CustomSendEmail from "./CustomSendEmail";

interface CarrierInfo {
  include: boolean;
  sent: string;
  carrier_id: number | null;
  carrierName: string;
  phoneNumber: string;
  email: string;
  isNew: boolean;
}

interface AddRateModalProps {
  id: any;
  show: boolean;
  handleClose: () => void;
  marketData: any;
  portsData: any;
}

const SendCarriersModal: React.FC<AddRateModalProps> = ({
  id,
  show,
  handleClose,
  marketData,
  portsData,
}) => {
  const [loading, setLoading] = useState(false);
  const [buttonDisabled, setButtonDisabled] = useState(true);
  const [dropdornList, setDropdownList] = useState<any[]>([]);
  const [marketFilter,setMarketFilter] = useState([])
  const { data } = useSession();
  const router = useRouter()
  const [carrierInfo, setCarrierInfo] = useState<CarrierInfo[]>([
    {
      include: false,
      sent: "",
      carrier_id: 0,
      carrierName: "",
      phoneNumber: "",
      email: "",
      isNew: true,
    },
  ]);
  const accessToken = data?.user?.image;
  const [selectedCarrierIds, setSelectedCarrierIds] = useState<number[]>([]);
  const [selectedNewCarrierEmails, setSelectedNewCarrierEmails] = useState<
    string[]
    >(new Array(carrierInfo.length).fill(""));
  const selectChange=(event:any) => {
    const isChecked = event.target.checked;
    const updatedCarrierInfo = carrierInfo?.map((info) => ({
      ...info,
      include: isChecked,
    }));
    setCarrierInfo(updatedCarrierInfo);
  }
  const handleSelectAllChange = (event:any) => {
    selectChange(event)
  };

  const formatPhoneNumber = (phoneNumber:any) => {
    const numericValue = phoneNumber?.replace(/[^0-9]/g, "");
    return numericValue?.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
  };

  const [newData, setNewData] = useState(false)
  const [defaultSelected, setDefaultSelected] = useState(false);
  const names = marketFilter?.map((item:any) => item?.market);

  useEffect(() => {
      setMarketFilter(portsData?.filter((item:any) => (
        marketData?.data?.port_name === item?.name
      )));
  }, [portsData, marketData]);

  const getDataFav = () => {
    if (show !== true) return;

    const fetchFavListData = async () => {
      const res = await favList(accessToken, names, marketData?.data?.terminal_id ?? "", router?.query?.id);
      if (res?.status === "success" && res?.data?.length > 0) {
        return res.data.map((itemFavList: { email: any; additional_emails: any[]; phone: any; other_emails: any; }) => ({
          ...itemFavList,
          selected_carrier_emails: itemFavList?.email,
          selected_emails: itemFavList?.additional_emails.map((emailItem) => ({ ...emailItem, is_send: 1 })),
          phone: formatPhoneNumber(itemFavList?.phone),
          optional_emails: itemFavList?.other_emails,
        }));
      }
      return [];
    };

    const fetchCarrierInfo = async (response: { status: string; data: any[]; }) => {
      if (response?.status === "success" && response?.data?.length > 0) {
        return response.data.map((info) => ({
          ...info,
          phone: formatPhoneNumber(info?.phone),
          is_subscribed: 1,
          selected_emails: info?.additional_emails,
          optional_emails: info?.other_emails,
          selected_carrier_emails: info?.email,
        }));
      }
      return [];
    };

    const fetchData = async () => {
      try {
        const response = await getMyFavCarriers(accessToken, id);
        const favListData = await fetchFavListData();
        const carrierInfoData = await fetchCarrierInfo(response);

        if (favListData.length > 0 || carrierInfoData.length > 0) {
          const combinedData = [...favListData, ...carrierInfoData];
          setCarrierInfo(combinedData);
          setNewData(true);
        } else {
          setCarrierInfo([{
            include: false,
            sent: "",
            carrier_id: 0,
            carrierName: "",
            phoneNumber: "",
            email: "",
            isNew: true,
          }]);
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  };


  useEffect(() => {
    getDataFav()
  }, [show, newData]);

  const CarrierMapListing = () => {
    CarrierMapForSendToCarrier(accessToken).then((response) => {
      if (response.status === "success") {
        setDropdownList(response.data);
      }
    });
  }

  useEffect(() => {
    CarrierMapListing()
  }, [show]);

  const handleAddMoreClickData = () => {
    setHide(true)
    setCarrierInfo((prevInfo) => [
      ...prevInfo,
      {
        include: false,
        sent: "",
        carrier_id: 0,
        carrierName: "",
        phoneNumber: "",
        email: "",
        isNew: true,
      },
    ]);
    setSelectedCarrierIds((prevIds:any) => [...prevIds, null]);
    setSelectedNewCarrierEmails((prevEmails) => [...prevEmails, ""]);
  };

  useEffect(() => {
    const hasSelectedCarrier = carrierInfo.some(
      (info) => info?.include && info?.carrier_id !== null
    );
    setButtonDisabled(!hasSelectedCarrier);
  }, [carrierInfo]);

  const checkData = async (carrierId:any, carrierIndex:any) => {
    const datas = await getFavCarriersStatus(accessToken, carrierId, id);
    const checkDataUpdatedCarrierInfo:any = [...carrierInfo];
    checkDataUpdatedCarrierInfo[carrierIndex]['is_subscribed'] = datas?.data?.is_subscribed;
    setCarrierInfo(checkDataUpdatedCarrierInfo);
  };
 
 const handleInputChanges = (
    index: number,
    field: string,
    value: any,
    carrierId: any
  ) => {
    if(field !== "other_emails"){
      checkData(carrierId, index);
    }
    if (field === "include") {
      const includeUpdatedCarrierInfo = [...carrierInfo];
      includeUpdatedCarrierInfo[index][field] = value;
      setCarrierInfo(includeUpdatedCarrierInfo);
    }
    setDefaultSelected(false);
    switch(field){

      case "billing_company":

        if (!value) {
          const resetCarrierInfo: any = [...carrierInfo];
          resetCarrierInfo[index]["billing_company"] = "";
          resetCarrierInfo[index]["phone"] = "";
          resetCarrierInfo[index]["email"] = null;
          resetCarrierInfo[index]["additional_emails"] = [];
          resetCarrierInfo[index]["other_emails"] = "";
          resetCarrierInfo[index]["selected_carrier_emails"] = null;
          resetCarrierInfo[index]["is_subscribed"] = false;
          resetCarrierInfo[index]["selected_emails"] = [];
          resetCarrierInfo[index]["carrier_id"] = null;
          setCarrierInfo(resetCarrierInfo);
          const updatedCarrierIds: any = [...selectedCarrierIds];
          updatedCarrierIds[index] = null;
          setSelectedCarrierIds(updatedCarrierIds);
          setDefaultSelected(false);
          if (carrierInfo[index].isNew) {
            const updatedNewCarrierEmails = [...selectedNewCarrierEmails];
            updatedNewCarrierEmails[index] = "";
            setSelectedNewCarrierEmails(updatedNewCarrierEmails);
          }
          return;
        }

        const selectedCarrier = dropdornList.find(
          (item) => item.billing_company === value
        );
        if (selectedCarrier) {
          const billingCompanyUpdatedCarrierInfo:any = [...carrierInfo];
          billingCompanyUpdatedCarrierInfo[index]["carrier_id"] = selectedCarrier.carrier_id;
          billingCompanyUpdatedCarrierInfo[index]["billing_company"] = value;
          billingCompanyUpdatedCarrierInfo[index]["phone"] = formatPhoneNumber(selectedCarrier.phone);
          billingCompanyUpdatedCarrierInfo[index]["additional_emails"] = selectedCarrier?.additional_emails;
          billingCompanyUpdatedCarrierInfo[index]["email"] = selectedCarrier.email;
          billingCompanyUpdatedCarrierInfo[index]["selected_carrier_emails"] = selectedCarrier.email;
          billingCompanyUpdatedCarrierInfo[index]["is_subscribed"] = selectedCarrier.is_subscribed;
          billingCompanyUpdatedCarrierInfo[index]['selected_emails'] = selectedCarrier?.additional_emails;
          setCarrierInfo(billingCompanyUpdatedCarrierInfo);
          const updatedCarrierIds = [...selectedCarrierIds];
          updatedCarrierIds[index] = selectedCarrier.carrier_id;
          setSelectedCarrierIds(updatedCarrierIds);
          setDefaultSelected(true);
          if (carrierInfo[index].isNew) {
            const updatedNewCarrierEmails = [...selectedNewCarrierEmails];
            updatedNewCarrierEmails[index] = selectedCarrier.email;
            setSelectedNewCarrierEmails(updatedNewCarrierEmails);
          }
        }
        break;

      case "email":
        handleEmailRelatedChanges(value, carrierInfo, index, field);
        break;

      case "phone":
        const isDefaultValue = value === 1;
        const maxLength = 12;
        const truncatedPhoneNumber = value.slice(0, maxLength);
        const formattedPhoneNumber = isDefaultValue
          ? truncatedPhoneNumber
          : formatPhoneNumber(truncatedPhoneNumber);
        const phoneUpdatedCarrierInfo:any = [...carrierInfo];
        phoneUpdatedCarrierInfo[index][field] = formattedPhoneNumber;
        setCarrierInfo(phoneUpdatedCarrierInfo);
        break;

      case "other_emails":
        const otherEmailUpdatedCarrierInfo:any = [...carrierInfo];
        otherEmailUpdatedCarrierInfo[index]['other_emails'] = value;
        setCarrierInfo(otherEmailUpdatedCarrierInfo);
        break;

      default: 
        const defaultUpdatedCarrierInfo:any = [...carrierInfo];
        defaultUpdatedCarrierInfo[index][field] = value;
        setCarrierInfo(defaultUpdatedCarrierInfo);
    }
  };
  
  const handleEmailRelatedChanges = (value:any, carrierInfoData:any, index:any, field:any)=>{
    let allCarrierEmails:any;
    let allAdditionalEmails:any = [];
    value?.map((items:any)=>{
      let selectedValue = items.split("_");
      let selectedEmails = selectedValue[0];
      let selectedIds = selectedValue[1];
      let selectedEmailType = selectedValue[2];
      if(selectedEmailType === 'additionalEmails'){
        const makeObj = {
          id: selectedIds,
          email: selectedEmails
        }
        allAdditionalEmails.push(makeObj);
      }else{
        allCarrierEmails = selectedEmails;
      }
    });
    const emailUpdatedCarrierInfo:any = [...carrierInfoData];
    emailUpdatedCarrierInfo[index]['selected_emails'] = allAdditionalEmails;
    if(allCarrierEmails){
      emailUpdatedCarrierInfo[index][field] = allCarrierEmails;
    }
    emailUpdatedCarrierInfo[index]['selected_carrier_emails'] = allCarrierEmails;
    setCarrierInfo(emailUpdatedCarrierInfo);
  }

  const [hide,setHide]=useState(false);

  const handleDelete = (index: number) => {
    setCarrierInfo((prevInfo) => {
      const updatedInfo = [...prevInfo];
      updatedInfo.splice(index, 1);
      return updatedInfo;
    });
    setHide(true)
  };

  const handleCancel = () => {
    setCarrierInfo([
      {
        include: false,
        sent: "",
        carrier_id: null,
        carrierName: "",
        phoneNumber: "",
        email: "",
        isNew: true,
      },
    ]);
    setDropdownOptionsList([]);
    setSelectedCarrierIds([]);
    setSelectedNewCarrierEmails([]);
  };

  const handleSubmit = async () => {
    setLoading(true);
    const carriersWithEmptyName = carrierInfo.filter(
      (info:any) => info?.include && !info?.billing_company
    );
    if (carriersWithEmptyName.length > 0) {
      toast.error("Please select a carrier", {
        position: toast.POSITION.TOP_CENTER,
      });
      setLoading(false);
    } else {
      const invalidEmails = carrierInfo.filter(
        (info:any) => {
          return info?.include && !isValid(info?.selected_carrier_emails?.trim()) && (info?.other_emails?.length <= 0) && (info?.selected_emails?.length <= 0)
        } 
      );
      
      if (invalidEmails.length > 0) {
        toast.error("Please enter a valid email address", {
          position: toast.POSITION.TOP_CENTER,
        });
        setLoading(false);
      } else {
        const selectedCarriers = carrierInfo.filter((info) => info.include);
        const selectedCarrierIdss = selectedCarriers.map(
          (info) => info.carrier_id
        );
        const selectedCarrierEmails = selectedCarriers.map(
          (info:any) => { 
            return selectedEmailsFns(info);
          }
        );
        const selectedCarrierPhones = selectedCarriers.map(
          (info:any) => info.phone
        );

        const additionalEmails = selectedCarriers.map(
          (info:any) => info.selected_emails
        )

        const otherEmails = selectedCarriers.map(
          (info:any) => info.other_emails
        )

        const payload = {
          quote_id: id,
          carrier_id: selectedCarrierIdss,
          carrier_email: selectedCarrierEmails,
          carrier_phone: selectedCarrierPhones,
          additional_emails: additionalEmails,
          other_emails: otherEmails
        };
        let res = await SendCarriers(accessToken, payload);
        if (res?.status === "success") {
          
          toast.success(res?.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        
          setLoading(false);
          handleClose();
          handleCancel();
          setDropdownOptionsList([]);
        } else {
          toast.error("Submission failed", {
            position: toast.POSITION.TOP_CENTER,
          });
          setLoading(false);
        }
      }
    }
  };

  const selectedEmailsFns = (infoData:any)=>{
    let emailSelected:any;
    if(infoData?.is_subscribed === 1){
      emailSelected = (infoData.selected_carrier_emails) ? infoData.selected_carrier_emails 
      : ""
    }else{
      emailSelected = ""
    }
    return  emailSelected
  }

  const isValid = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const loadOptions = async (inputValue11:any, callback:any, dropdownIndex:any) => {
    if (inputValue11?.length) {
      let data1 = await getMapCarriers(accessToken, inputValue11,"","");
      const formattedOptions = data1?.data?.map((item:any) => ({
        value: item.billing_company,
        label: item.billing_company,
        dataId: item.carrier_id,
        additional_emails: item.additional_emails,
        is_subscribed: item.is_subscribed,
      }));
      const updatedDropdownOptionsList = [...dropdownOptionsList];
      updatedDropdownOptionsList[dropdownIndex] = formattedOptions;
      setDropdownOptionsList(updatedDropdownOptionsList);
      const updatedInputValues = [...dropdownInputValues];
      updatedInputValues[dropdownIndex] = inputValue11;
      setDropdownInputValues(updatedInputValues);
    }
  };

  const [dropdownInputValues, setDropdownInputValues] = useState(
    new Array(carrierInfo.length).fill("")
  );

  const [dropdownOptionsList, setDropdownOptionsList] = useState(
    new Array(carrierInfo.length).fill([])
  );

  const modal = () => {
    const onShow = () => {
      let selectAllCheckbox: any = document.querySelector(
        ".p-multiselect-header > .p-checkbox"
      );
      selectAllCheckbox.style.marginRight = "8px";
      selectAllCheckbox.after(" Select All");
    };
    return (<>
      <Modal
        className='modal_main modal-xl modal_main'
        show={show}
        centered
        backdrop='static'
        onHide={handleClose}
      >
        {loading && (
          <div id='loader_table'>
            <ScaleLoader color='#3180f3' className='table_loader' />
          </div>
        )}
        <ModalHeader className='border-bottom-0 justify-content-end'></ModalHeader>
        <ModalBody>
          <div className='text-center mb-3'>
            <div>
              <h4 className='modal_h4'>
                E-mail Spot Quote Request to Your Carriers
              </h4>
            </div>
          </div>
          <div className='main_modal mt-3'>
            <Form>
              <Row>
                <Col>
                  <Col>
                    <div className='modal-table-div responsive-table-wrapper-update-carrier-table'>
                      <Table borderless size='sm'>
                        <thead>
                          <tr>
                            <th className='th_class w-10-per'>
                              <div>
                                <input
                                  className='form-check-input checkbox-modal border border-dark'
                                  type='checkbox'
                                  value=''
                                  id='flexCheckDefault'
                                  onChange={handleSelectAllChange}
                                />
                                <label htmlFor='port_ramp'>Include</label>
                              </div>
                            </th>
                            <th className='th_class w-8-per'>Sent?</th>
                            <th className='th_class w-20-per'>Carrier Name</th>
                            <th className='th_class w-20-per'>Phone#</th>
                            <th className='th_class w-20-per'>Email</th>
                            <th className='th_class w-20-per'>Other Email</th>
                            <th className='th_class w-3-per'></th>
                          </tr>
                        </thead>
                        <tbody>
                          {carrierInfo.map((info:any, index:any) => (
                            <tr key={index}>
                              <td>
                                <input
                                  className='form-check-input checkbox-modal border border-dark'
                                  type='checkbox'
                                  checked={info.include}
                                  onChange={(e) =>
                                    handleInputChanges(
                                      index,
                                      "include",
                                      e.target.checked,
                                      info.carrier_id
                                    )
                                  }
                                />
                              </td>
                              <td
                                className={`text-uppercase ${info.is_sent
                                    ? "text-success"
                                    : "text-danger"
                                  }`}
                              >
                                <b>
                                  {info.is_sent

                                    ? "Yes"
                                    : "No"}
                                </b>
                              </td>
                              <td>
                                <div className='position-relative'>
                                  <CustomSearchDropdown
                                    options={dropdownOptionsList[index]}
                                    value={
                                      info.billing_company
                                        ? info.billing_company
                                        : null
                                    }
                                    onChange={(selectedOption:any) => {
                                      const carrierId = selectedOption?.dataId || null;
                                      handleInputChanges(
                                        index,
                                        "billing_company",
                                        selectedOption?.value || "",
                                        carrierId
                                      );
                                    }}
                                    isDisabled={!info.isNew}
                                    placeholder='Carrier Name / DOT#'
                                    onInputChange={(inputValue22:any) => {
                                      if (inputValue22?.length) {
                                        loadOptions(
                                          inputValue22,
                                          (options:any) => {
                                            const updatedDropdownOptionsList = [
                                              ...dropdownOptionsList,
                                            ];
                                            updatedDropdownOptionsList[index] =
                                              options;
                                            setDropdownOptionsList(
                                              updatedDropdownOptionsList
                                            );
                                          },
                                          index
                                        );
                                      }
                                    }}
                                    loadOptions={loadOptions}
                                    hidden={hide}
                                  />
                                </div>
                              </td>
                              <td className='lable-info'>
                                <div>
                                  <Form.Control
                                    className='form-field'
                                    value={info.phone}
                                    placeholder='phone'
                                    onChange={(e) =>
                                      handleInputChanges(
                                        index,
                                        "phone",
                                        e.target.value,
                                        info.carrier_id
                                      )
                                    }
                                    disabled
                                  />
                                </div>
                              </td>
                              <td>
                                <div>
                                  <MultiSelectInputFields 
                                    carrierInfo={info}
                                    carrierIndex={index}
                                    defaultSelected={defaultSelected}
                                    handleChangeDrop = {handleInputChanges}
                                    onShow={onShow}
                                  />
                                </div>
                              </td>
                              <td>
                                <div className="position-relative">
                                  <CustomSendEmail 
                                    carrierInfo={info}
                                    carrierIndex={index}
                                    handleChangeDrop = {handleInputChanges}
                                  />
                                </div>
                              </td>
                              <td>
                                <div className="position-relative">
                                  {info.isNew && (
                                    <div
                                      className=''
                                      style={{ cursor: "pointer" }}
                                      onClick={() => handleDelete(index)}
                                    >
                                      <i className='bi bi-x-lg delete-icon'></i>
                                    </div>
                                  )}
                                </div>
                              </td>
                            </tr>
                          ))}
                          <tr>
                            <td></td>
                            <td></td>
                            <td>
                              <div className='mb-2'>
                                <FormLabel
                                  htmlFor='port_ramp'
                                  onClick={handleAddMoreClickData}
                                >
                                  Add More{" "}
                                  <span className='span-add icon-css'>
                                    <i style={{height:"20px"}} className='bi bi-plus-circle-fill'></i>
                                  </span>
                                </FormLabel>
                              </div>
                            </td>
                          </tr>
                        </tbody>
                      </Table>
                    </div>
                  </Col>
                </Col>
              </Row>
            </Form>
          </div>
        </ModalBody>
        <ModalFooter className='quote_btn_block'>
          <Button
            type='button'
            disabled={buttonDisabled}
            className='btn btn-success w-25 btn-modal'
            onClick={handleSubmit}
          >
            Submit
          </Button>
          <Button
            type='button'
            className='btn btn-secondary w-25 btn-close-modal'
            data-dismiss='modal'
            onClick={() => {
              handleClose();
              handleCancel();
            }}
          >
            Cancel
          </Button>
        </ModalFooter>
        <div className='info-icon-modal'>
          <i className='bi bi-info-circle-fill'></i>
        </div>
      </Modal>
    </>)
  }
  
  return (
    <>
      <ToastContainer />
      {modal()}
    </>
  );
  
};

export default SendCarriersModal;
