/* eslint-disable @typescript-eslint/no-explicit-any */
import React from "react";
import {
  deleteCustomerBankDetails,
  getCustomerBankDetails,
  updateCustomerBankDetails,
} from "../../../../Api/CustomerApi";
import BottomSheetModal from "../../../Modal/BottomSheetModal";
import HourGlassLoader from "../../../Loader/Loader";
import Swal from "sweetalert2";
import { toast } from "react-toastify";
import AddBankDetailsModal from "../../../Modal/AddBankDetailsModal";

interface ComponentPropsType {
  modal?: boolean;
  toggleBankChange?: () => void;
  addBankDetails: any;
  setAddBankDetails: any;
  listOpen: boolean;
}

const BankList = ({
  modal = true,
  toggleBankChange,
  addBankDetails,
  setAddBankDetails,
  listOpen
}: ComponentPropsType) => {
  const [isLoading, setIsLoading] = React.useState(false);
  const [addresses, setAddresses] = React.useState([]);
  const [selectedAddress, setSelectedAddress] = React.useState({});
//   const [addAddress, setAddAddress] = React.useState(false);
  const [activeMenu, setActiveMenu] = React.useState<number | null>(null);
  const dropdownRef = React.useRef<HTMLDivElement | null>(null);
  const toggle = () => {
    if (addBankDetails) {
      setSelectedAddress({});
      fetchAddresses();
      setActiveMenu(null);
    }
    setAddBankDetails(!addBankDetails);
  };
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setActiveMenu(null);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  async function fetchAddresses(id?: any) {
    try {
      setIsLoading(true);
      const response: any = await getCustomerBankDetails({
        id: id || "",
        order_by: "is_primary",
      });
      if (id) return response?.data?.[0] || {};
      else setAddresses(response?.data || []);
    } catch (error) {
      console.error(error, "ERROR------>>>");
    } finally {
      setIsLoading(false);
    }
  }

  React.useEffect(() => {
    fetchAddresses();
  }, []);

  const makePrimary = async (id: number) => {
    try {
      setIsLoading(true);
      await updateCustomerBankDetails(id, { is_primary: true });
      fetchAddresses();
    } catch (error) {
      console.error(error, "ERROR");
    } finally {
      setIsLoading(false);
    }
  };
  const handleDelete = async (id: number) => {
    // Prevent form submission
    const event = window.event;
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }

    Swal.fire({
      title: "Are you sure?",
      text: "Do you really want to delete this address?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "Yes, delete it!",
      cancelButtonText: "Cancel",
      reverseButtons: true,
      customClass: {
        confirmButton: "delybell-primary px-4",
        cancelButton: "delybell-dark",
      },
    }).then(async (response) => {
      if (response?.isConfirmed) {
        await deleteCustomerBankDetails(id);
        await fetchAddresses();
        toast.success("Pickup address deleted successfully!");
      }
    });
  };

  const handleEdit = async (id: number) => {
    try {
      setIsLoading(true);
      const response: any = await fetchAddresses(id);
      setSelectedAddress(response || {});
    } catch (error) {
      console.error(error, "ERROR------>>>");
    } finally {
      setIsLoading(false);
      toggle();
    }
  };
  return (
    <>
      <style>
      {`
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .modal.show .modal-dialog { max-width: 800px; }
            .modal-content { padding: 20px 10px 0px; }
            .title-address { padding: 0 10px; }
          }
          @media only screen and (min-device-width : 100px) and (max-device-width : 767px) {
            .modal.show {
              position: fixed;              
              bottom: 0px;
              left: 0px;
              right: 0px;
              overflow: scroll;
              transition: all 300ms ease;
              transform: translate3d(0%, 20px, 0) !important;              
            }
            .modal-content { 
              padding: 20px 20px 0px; 
              border-bottom-left-radius: 0;
              border-bottom-right-radius: 0;
            }
            .modal.show .modal-dialog { 
              margin: 0;
              align-items: end;
            }
            .add-address-row {
              min-height: 30vh;
              max-height: 75vh;
              overflow-x: hidden;
              overflow-y: auto;
            }
            .divider-sm-m { 
              margin-left: 0px; 
              margin-right: 0px; 
            }
          }
          .col-lg-6.order-list-box {
            display: grid;
          }
            .add-address-row { min-height: auto; }
        `}
      </style>
      {isLoading && <HourGlassLoader />}
      {addBankDetails ? (
        <BottomSheetModal show={addBankDetails} onHide={toggle} header={false}>
          <AddBankDetailsModal
            onHide={toggle}
            data={selectedAddress}
            setData={setSelectedAddress}
          />
        </BottomSheetModal>
      ) : (
        <>
          {modal && (
            <>
              <div className="d-float-center justify-content-between mb-3 title-address">
                <div className="d-float-center">
                  <h3 className="mb-0 me-3">Pickup Address</h3>
                  <a
                    className="btn btn-s border border-primary color-primary rounded-s"
                    href="#"
                    onClick={toggle}
                  >
                    <i className="fa fa-plus" /> Add New
                  </a>
                </div>
                <div className="menu-title">
                  <a
                    href="#"
                    onClick={toggleBankChange}
                    className="close-menu w-auto"
                  >
                    <i className="fa fa-times" />
                  </a>
                </div>
              </div>
              <div className="divider tab-divider divider-margins mt-0 mb-3 divider-sm-m"></div>
            </>
          )}
          {listOpen ? (
            <div className="row add-address-row mx-0 mb-0">
                {addresses?.map((address: any) => (
                <div
                    className="col-lg-6 col-md-12 col-sm-12 col-12 order-list-box"
                    key={address.id}
                >
                    <div className="card card-style mb-4">
                    <div className="content">
                        <div className="maindiv">
                        <div className="w-100">
                            <div className="d-float-center justify-content-between address-sub-box">
                            <h6 className="font-500 font-14 mb-2 d-float-center">
                                <div className="form-check icon-check d-float-center">
                                <input
                                    className="form-check-input"
                                    type="radio"
                                    id={`check-${address.id}`}
                                    checked={address.isPrimary}
                                    onChange={() => makePrimary(address.id)}
                                />
                                <i className="icon-check-1 far fa-circle color-gray-dark font-16"></i>
                                <i className="icon-check-2 far fa-check-circle font-16 color-highlight"></i>
                                <label
                                    className="form-check-label font-500 font-14"
                                    htmlFor={`check-${address.id}`}
                                >
                                    {address.accountHolderName}
                                </label>
                                {address.isPrimary ? (
                                    <span className="badge delybell-primary rounded-xl">
                                    Primary
                                    </span>
                                ) : (
                                    ""
                                )}
                                </div>
                            </h6>
                            <a
                                className="float-end mb-2"
                                href="#"
                                onClick={(e) => {
                                e.preventDefault();
                                setActiveMenu((prev) =>
                                    prev === address.id ? null : address.id
                                );
                                }}
                            >
                                <i className="fa fa-ellipsis-v icon-30 text-end font-14 color-primary w-auto" />
                            </a>

                            {activeMenu === address.id && (
                                <div
                                ref={dropdownRef}
                                className="dropdown-menu show position-absolute end-0 mt-2"
                                style={{ zIndex: 9999 }}
                                >
                                <button
                                    className="dropdown-item d-flex align-items-center gap-2"
                                    onClick={() => handleEdit(address.id)}
                                >
                                    <i className="fa fa-edit"></i> Edit
                                </button>
                                <button
                                    className="dropdown-item d-flex align-items-center gap-2"
                                    onClick={() => handleDelete(address.id)}
                                >
                                    <i className="fa fa-trash"></i> Delete
                                </button>
                                </div>
                            )}
                            </div>
                            <h6 className="font-400 font-13 opacity-60 mb-0">
                            <span className="address-box">
                                {address.accountNumber ? (
                                <>
                                    Ac. No: {address.accountNumber}
                                    <br />
                                </>
                                ) : (
                                ""
                                )}

                                {address.bankName ? (
                                <>
                                    {address.bankName}
                                    <br />
                                </>
                                ) : (
                                ""
                                )}
                                {`${address?.branchName || ""}, ${
                                address?.country_details?.name || ""
                                }`}
                            </span>
                            </h6>
                        </div>
                        </div>
                    </div>
                    </div>
                </div>
                ))}
            </div>
          ) : ''}
          {modal && (
            <div className="col-lg-12 px-lg-2">
              <button
                type="button"
                className="btn btn-full w-100 btn-l font-600 font-13 bg-blue-dark mt-0 mb-4 rounded-s"
                onClick={toggleBankChange}
              >
                Submit
              </button>
            </div>
          )}
        </>
      )}
    </>
  );
};

export default BankList;
