/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState } from "react";
import { updateCustomerProfile } from "../../../Api/CustomerApi";
import Swal from "sweetalert2";
import HourGlassLoader from "../../Loader/Loader";
import { toast } from "react-toastify";

const PhoneEdit = ({ allData, toggleMobileChange, isReturn = false }: any) => {
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [phone, setPhone] = useState(allData?.phone || "");
  const [error, setError] = useState("");
  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    if (/^\d{0,10}$/.test(value)) {
      setPhone(value);
      setError(
        value.length === 10 ? "" : "Phone number must be exactly 10 digits"
      );
    }
  };
  const handleSubmit = async () => {
    try {
      setIsLoading(true)
      // ✅ Update session/localStorage (based on login flow)
      const existingAllData = JSON.parse(
        localStorage.getItem("ALL_DATA") || "{}"
      );
      const response = await updateCustomerProfile({phone: phone, first_name: existingAllData?.data?.firstName || '', last_name: existingAllData?.data?.lastName || '', email: existingAllData?.data?.email || '', user_type: existingAllData?.data?.userType?.id || ''});
      toggleMobileChange();
          // Handle the response from API
    if (response.status) {
      const updatedAllData = {
        ...existingAllData,
        data: {
          ...existingAllData.data,
          ...response.data, // Merge updated fields
        },
      };
      toast.success(`${isReturn ? 'Delivery' : 'Pickup'} Contact Number Updated!`)

      // Update individual items if needed
      if (response.data.firstName) {
        localStorage.setItem("USER_NAME", response.data.firstName);
      }

      // Update the full ALL_DATA blob
      localStorage.setItem("ALL_DATA", JSON.stringify(updatedAllData));
    } else {
      Swal.fire({
        icon: "error",
        title: "Error!",
        text: response.message || "Something went wrong. Please try again.",
        customClass: {
          confirmButton: "delybell-primary px-4",
          cancelButton: 'delybell-dark'
        },
      });
    }
    setIsLoading(false);
    } catch (error) {
      console.error(error)
    } finally {

    }
  }
  return (
    <>
      <style>
        {`
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .modal.show .modal-dialog { max-width: 450px; }
            .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;
            }
          }
        `}
      </style>
      {isLoading && <HourGlassLoader />}
      <div className="menu-title">        
          <h3 className="choose-order-title pt-1">Change {isReturn ? 'Delivery ' : 'Pickup '} Contact Number</h3>
          <a href="#" onClick={toggleMobileChange} className="close-menu">
            <i className="fa fa-times" />
          </a>        
      </div>

      <div className="divider tab-divider divider-margins"></div>

      <div className="col-12 px-3 choose-order-type">
        <div className="input-style input-style-always-active has-borders has-icon validate-field mb-0">          
            <label
              htmlFor="editPhone"
              className="color-theme opacity-100 text-uppercase font-700 font-10" 
              style={{ zIndex: "1" }}
            >
              Phone Number 
              {/* <b className="color-red">*</b> */}
            </label>
          <div className="position-relative input-icon-position">
            <i className="fa fa-phone color-primary" />
            <input
              type="text"
              name="editPhone"
              id="editPhone"
              className={`form-control validate-name ${
                error ? "is-invalid" : ""
              }`}
              placeholder={`Enter ${isReturn ? 'Delivery ' : 'Pickup '} Contact Number`}
              value={phone}
              onChange={handlePhoneChange}
              maxLength={10}
            />
          </div>
          {error && <div className="text-danger px-2 error-box">{error}</div>}
        </div>
      </div>
      <button
        type="button"
        onClick={handleSubmit}
        className="btn btn-full btn-l font-600 font-13 bg-blue-dark mt-4 mb-4 mx-3 rounded-s"
      >
        Submit
      </button>
    </>
  );
};

export default PhoneEdit;
