import React, { useState, useEffect } from "react";
import { getMyFavCarriers } from "../../../services/customers";
import { useRouter } from "next/router";
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 {
  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 UpdateQuteModalProps {
  show: boolean;
  handleClose: () => void;
}
const UpdateQuteModal: React.FC<UpdateQuteModalProps> = ({
  load,
  id,
  key,
  show,
  handleClose,
}) => {
  const [isLoading, setIsLoading] = useState(false);
  const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
  const [dropdornList, setDropdownList] = useState<DropdownItem[]>([]);
  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 [defaultSelected, setDefaultSelected] = useState(false);

  const handleSelectAllChange = (event: any) => {
    const isChecked = event.target.checked;

    const updatedCarrierInfo = carrierInfo?.map((info) => ({
      ...info,
      include: isChecked,
    }));
    setCarrierInfo(updatedCarrierInfo);
  };

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

  useEffect(() => {
    if (show === true) {
      getMyFavCarriers(accessToken, id).then((response) => {
        if (response?.status === "success") {
          if (response?.data?.length > 0) {
            const formattedCarrierInfo = response?.data?.map((info: any) => ({
              ...info,
              phone: formatPhoneNumber(info?.phone),
              is_subscribed: 1,
              selected_emails: info?.additional_emails,
              optional_emails: info?.other_emails,
              selected_carrier_emails: info?.email,
            }));
            setCarrierInfo(formattedCarrierInfo);
          } else {
            setCarrierInfo([
              {
                include: false,
                sent: "",
                carrier_id: 0,
                carrierName: "",
                phoneNumber: "",
                email: "",
                isNew: true,
              },
            ]);
          }
        }
      });
    }
  }, [show]);

  useEffect(() => {
    CarrierMapForSendToCarrier(accessToken).then((response) => {
      if (response.status === "success") {
        setDropdownList(response.data);
      }
    });
  }, [accessToken]);

  const handleAddMoreClick = () => {
    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,
    );
    setSubmitButtonDisabled(!hasSelectedCarrier);
  }, [carrierInfo]);

  const checkStatus = 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 handleInputChange = (
    index: number,
    field: string,
    value: any,
    carrierId: any,
  ) => {
    if (field !== "other_emails") {
      checkStatus(carrierId, index);
    }
    if (field === "include") {
      const includeUpdatedCarrierInfo = [...carrierInfo];
      includeUpdatedCarrierInfo[index][field] = value;
      setCarrierInfo(includeUpdatedCarrierInfo);
    }
    setDefaultSelected(false);
    switch (field) {
      case "billing_company":
        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;
          setDefaultSelected(true);
          setSelectedCarrierIds(updatedCarrierIds);
          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 handleDeleteRow = (index: number) => {
    setCarrierInfo((prevInfo) => {
      const updatedInfo = [...prevInfo];
      updatedInfo.splice(index, 1);
      return updatedInfo;
    });
    setHide(true);
  };

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

    setDropdownOptionsList([]);
    setSelectedCarrierIds([]);
    setSelectedNewCarrierEmails([]);
  };

  const handleSubmit = async () => {
    setIsLoading(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,
      });
      setIsLoading(false);
    } else {
      const invalidEmails = carrierInfo?.filter((info: any) => {
        return (
          info?.include &&
          !isValidEmail(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,
        });
        setIsLoading(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,
          });
          router.push("/dashboard");
          setIsLoading(false);
          handleClose();
          handleCancelClick();
          setDropdownOptionsList([]);
        } else {
          toast.error("Submission failed", {
            position: toast.POSITION.TOP_CENTER,
          });
          setIsLoading(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 isValidEmail = (email: any) => {
    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([]),
  );

  return (
    <>
      <ToastContainer />
      <Modal
        className="modal_main modal-xl modal_main"
        show={show}
        centered
        backdrop="static"
        onHide={handleClose}
      >
        {isLoading && (
          <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 className=" heading_svg d-flex justify-content-between align-items-center">
              <p></p>
              <div className="icon_text d-flex align-items-flex-start">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  id="alert"
                >
                  <g data-name="Layer 2">
                    <path
                      d="M22.56 16.3 14.89 3.58a3.43 3.43 0 0 0-5.78 0L1.44 16.3a3 3 0 0 0-.05 3A3.37 3.37 0 0 0 4.33 21h15.34a3.37 3.37 0 0 0 2.94-1.66 3 3 0 0 0-.05-3.04zM12 17a1 1 0 1 1 1-1 1 1 0 0 1-1 1zm1-4a1 1 0 0 1-2 0V9a1 1 0 0 1 2 0z"
                      data-name="alert-triangle"
                    ></path>
                  </g>
                </svg>
                <h4>You Have Updated the Details of This Quote!</h4>
              </div>
              <button
                onClick={() => {
                  load(true);
                  handleClose();
                  handleCancelClick();
                }}
                className="btn map-btn btn_log"
              >
                <i className="bi bi-x-lg"></i> Close
              </button>
            </div>

            <div className="u_want text-center">
              <h5>
                Would you like to send revised details to your carriers for them
                to re-quote?
              </h5>
              <mark>
                NOTE : THIS WILL VOID All PREVIOUS CARRIER&apos;S SUBMISSIONS
              </mark>
            </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">Re-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: any) =>
                                    handleInputChange(
                                      index,
                                      "include",
                                      e.target.checked,
                                      info.carrier_id,
                                    )
                                  }
                                />
                              </td>
                              <td className={`text-uppercase text-danger`}>
                                <b>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
                                        ? selectedOption.dataId
                                        : null;
                                      handleInputChange(
                                        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) =>
                                      handleInputChange(
                                        index,
                                        "phone",
                                        e.target.value,
                                        info?.carrier_id,
                                      )
                                    }
                                  />
                                </div>
                              </td>
                              <td>
                                <div>
                                  <MultiSelectInputFields
                                    carrierInfo={info}
                                    carrierIndex={index}
                                    defaultSelected={defaultSelected}
                                    handleChangeDrop={handleInputChange}
                                  />
                                </div>
                              </td>
                              <td>
                                <div className="position-relative">
                                  <CustomSendEmail
                                    carrierInfo={info}
                                    carrierIndex={index}
                                    handleChangeDrop={handleInputChange}
                                  />
                                </div>
                              </td>
                              <td>
                                <div className="position-relative">
                                  {info.isNew && (
                                    <div
                                      className=""
                                      style={{ cursor: "pointer" }}
                                      onClick={() => handleDeleteRow(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={handleAddMoreClick}
                                >
                                  Add More{" "}
                                  <span className="span-add icon-css">
                                    <i 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={submitButtonDisabled}
            className="btn btn-success w-25 btn-modal"
            onClick={handleSubmit}
          >
            Submit
          </Button>
        </ModalFooter>
        <div className="info-icon-modal">
          <i className="bi bi-info-circle-fill"></i>
        </div>
      </Modal>
    </>
  );
};
export default UpdateQuteModal;
