import React, { useState, ChangeEvent, FormEvent, useEffect } from "react";
import classNames from "classnames";
import axios from "axios";
import Cookies from "js-cookie";
import Script from "next/script";
import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng,
} from "react-places-autocomplete";
import toast from "react-hot-toast";
import { message } from "antd";
import { userActivity } from "@/components/commonFunctions/userActivity";
import { useSelector } from "react-redux";
import { RootState } from "@/Redux/store";

const GEOCODE_API_KEY = process.env.GEOCODE_API_KEY;

const scriptSrc = `https://maps.googleapis.com/maps/api/js?key=${GEOCODE_API_KEY}&libraries=places`;

interface FormData {
  street: string;
  cityId: string;
  stateId: string;
  countryId: string;
  postalCode: string;
  name: string;
  phone: string;
  // email: string;
  city: {
    _id: string;
    name: string;
  };
}

interface ModalProps {
  onClose: (formData: FormData, actiontype: string, addID: string) => void;
  actiontype: string;
  addID: string;
}

const Modal: React.FC<ModalProps> = ({ onClose, actiontype, addID }) => {

  const _loggedIn_user = useSelector((state: RootState) => state.user.user);

  const Add_new_address  = () => {
    userActivity(
      _loggedIn_user?._id,
      "website",
      "Add new address  ",
      {
        pageVisit: `/`,
      },
      navigator.userAgent
    );
  };


  // console.log("addId", addID)
  const [isOpen, setIsOpen] = useState(false);

  const [states, setStates] = useState<any>([]);

  const [cities, setCities] = useState([]);
  const [selectedStateId, setSelectedStateId] = useState("");

  const [currentModalAddress, setCurrentModalAddress] = useState({});

  const [scriptLoaded, setScriptLoaded] = useState(false);

  const [ck, setCk] = useState("");

  const [formData, setFormData] = useState({
    street: '',
    // landmark: '',
    cityId: '',
    stateId: '',
    countryId: '160',
    postalCode: '123',
    name: '',
    phone: '',
    // email: '',
    addressType: '',
    latitude: 0,
    longitude: 0,
    city: { _id: "", name: "" },
  });

  const toggleModal = () => {
    // console.error(addID)
    if (addID) {
      getAddress(addID);
    }
    // getAddress(addID);
    setIsOpen(!isOpen);
    // console.log("=====",formData)
  };

  const handleChange = (
    event: ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value } = event.target;
    
    if (name === "stateId") {
      const parts = value.split("/");
      const beforeValue = parts[0];
      const afterValue = parts[1];
      
      setSelectedStateId(beforeValue);
  
      const getCities = async () => {
        const response = await fetch(
          `https://api.jazzagain.com/public/index.php/api/getStateCities/${beforeValue}`
        )
          .then((res) => res.json())
          .then((json) => setCities(json.cities));
      };
      
      getCities();
      
      setFormData((prevData) => ({
        ...prevData,
        [name]: afterValue,
      }));
    } else if (name === "phone") {
      // Only allow numeric values for the phone input
      const numericValue = value.replace(/[^0-9]/g, '');
      setFormData((prevData) => ({
        ...prevData,
        [name]: numericValue.slice(0, 11), // Limit to maxLength of 11
      }));
    } else {
      setFormData((prevData) => ({
        ...prevData,
        [name]: value,
      }));
    }
  };
  

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if(formData.phone.length < 11) return message.error('Number must be of 11 digit !')
    onClose(formData, actiontype, addID);
    toggleModal();
  };

  const getCountryStates = async () => {
    const response = await fetch(
      "https://api.jazzagain.com/public/index.php/api/getCountryStates/160"
    )
      .then((res) => res.json())
      .then((json) => setStates(json.states));
  };

  const getAddress = async (id: string) => {
    const authToken = Cookies.get("jazz_token");
    // console.warn(addID)
    const axiosInstance = axios.create({
      baseURL: "https://api.jazzagain.com/public/index.php",
      headers: {
        authorization: `Bearer ${authToken}`,
      },
    });
    axiosInstance
      .get(`/api/user/address/${id}`)
      .then((response) => {
        console.log("SINGLE ADDRESS:", response.data);
        setCurrentModalAddress(response.data.address);
        setFormData(response.data.address);
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
    // const response = await fetch(`https://api.jazzagain.com/public/index.php/api/user/address/${addID}`)
    // .then(res => res.json())
    // .then(json => setStates(json.states))
  };

  useEffect(() => {
    if(isOpen){
      getCountryStates();
    }

    return () => {};
  }, [isOpen]);

  useEffect(() => {
    if(isOpen){
      const script = document.createElement("script");
      script.src = `https://maps.googleapis.com/maps/api/js?key=${GEOCODE_API_KEY}&libraries=places`;
      script.async = true;
      script.onload = () => {
        setScriptLoaded(true);
        console.log("Loaded Maps Script");
      };
  
      document.head.appendChild(script);
  
      // Cleanup: Remove the script from the head when the component is unmounted
      return () => {
        document.head.removeChild(script);
      };
    }
  }, [isOpen]);

  // const [isChecked, setIsChecked] = useState(false);

  // const handleToggle = () => {
  //   setIsChecked(!isChecked);

  //   if (!isChecked) {
  //     console.log('Switch turned on');
  //
  //   } else {
  //     console.log('Switch turned off');
  //
  //   }
  // };

  const handleChange2 = (address: any) => {
    console.log(address);
    setCk(address);
    setFormData((prevData) => ({
      ...prevData,
      street: address,
    }));
  };
  const handleSelect = (address: any) => {
    setFormData((prevData) => ({
      ...prevData,
      street: address,
    }));
    console.log("HandleSelect : ", formData);
    console.log("HandleSelect add: ", address);
    geocodeByAddress(address)
      .then((results) => getLatLng(results[0]))
      .then((coords) => {
        console.log("Success", coords);
        setFormData((prevData) => ({
          ...prevData,
          latitude: coords.lat,
          longitude: coords.lng,
        }));
      })
      .catch((error) => console.error("Error", error));
  };

  return (
    <div>
      {/* <Script src={scriptSrc} strategy="beforeInteractive"></Script> */}

      {actiontype === "add" ? (
        <div onClick={Add_new_address }>

        <button
          className="p-3 w-full text-center hover:text-white rounded text-[#FF332B] hover:bg-[#383736] transition-all duration-200 border border-gray-700 my-4 "
          onClick={toggleModal} 
          >
          ADD NEW ADDRESS
        </button>
          </div>
      ) : (
        <button className="mt-3 hover:scale-110 hover:text-gray-700 hover:font-medium" onClick={toggleModal}>
          EDIT
        </button>
      )}

      <div
        className={classNames(
          "fixed inset-0 flex items-center justify-center z-50",
          {
            hidden: !isOpen,
          }
        )}
      >
        <div
          className={classNames(
            "fixed inset-0 bg-black bg-opacity-50 transition-opacity",
            {
              hidden: !isOpen,
            }
          )}
          onClick={toggleModal}
        ></div>
        <div
          className={classNames(
            "bg-[#FEE3E1] p-6 rounded-lg shadow-md z-10 max-w-md",
            {
              hidden: !isOpen,
            }
          )}
        >
          <h2 className="text-xl font-semibold mb-4 text-black">Address</h2>
          <form onSubmit={handleSubmit}>
            {/* <input
              type="text"
              name="street"
              placeholder="Street"
              value={formData.street}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            /> */}

            {scriptLoaded && (
              <PlacesAutocomplete
                value={formData.street}
                onChange={handleChange2}
                onSelect={handleSelect}
                searchOptions={{ componentRestrictions: { country: 'NG' } }}
              >
                {({
                  getInputProps,
                  suggestions,
                  getSuggestionItemProps,
                  loading,
                }):any => (
                  <div>
                    <input
                      {...getInputProps({
                        placeholder: "Search Places ...",
                        className:
                          "location-search-input border rounded p-2 mb-2 w-full text-black",
                        name: "street",
                      })}
                    />
                    <div className="autocomplete-dropdown-container bg-black text-red-500">
                      {loading && <div>Loading...</div>}
                      {suggestions.map((suggestion, index) => {
                        const className = suggestion.active
                          ? "suggestion-item--active"
                          : "suggestion-item";
                        // inline style for demonstration purpose
                        const style = suggestion.active
                          ? { backgroundColor: "#fafafa", cursor: "pointer" }
                          : { backgroundColor: "#ffffff", cursor: "pointer" };
                        return (
                          <div
                            {...getSuggestionItemProps(suggestion, {
                              className,
                              style,
                            })}
                            key={index}
                          >
                            <span>{suggestion.description}</span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}
              </PlacesAutocomplete>
            )}

            {/* <input
              type="text"
              name="landmark"
              placeholder="Landmark"
              value={formData.landmark}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            /> */}

            <input
              type="text"
              name="name"
              placeholder="Name"
              value={formData.name}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            />
            <input
              type="number"
              name="phone"
              placeholder="Phone No."
              // maxLength={11}
              value={formData.phone}
              onChange={handleChange}
              // pattern="\d*"
              className="border rounded p-2 mb-2 w-full text-black"
            />
            {/* <input
              type="text"
              name="email"
              placeholder="E-mail"
              value={formData.email}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            /> */}

            <select
              name="stateId"
              // value={formData.stateId}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            >
              <option value="" disabled>
                Select a state
              </option>
              {states.map((state: any) => (
                <option key={state._id} value={`${state.id}/${state._id}`}>
                  {state.name}
                </option>
              ))}
            </select>

            <select
              name="cityId"
              value={formData.cityId}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            >
              <option value="" disabled>
                Select Local Government Area - LGA
              </option>
              {formData.city ? <option>{formData.city?.name}</option> : null}
              {cities.map((city: any) => (
                <option key={city._id} value={city._id}>
                  {city.name}
                </option>
              ))}
            </select>

            {/* <select
              name="addressType"
              value={formData.addressType}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            >
              <option value="" disabled>
                Select address type
              </option>
              <option value="Home">Home</option>
              <option value="Office">Office</option>
            </select> */}

            {/* <input
            type="text"
            name="stateId"
            placeholder="State"
            value={formData.stateId}
            onChange={handleChange}
            className="border rounded p-2 mb-2 w-full text-black"
          /> */}

            {/* <input
            type="text"
            name="cityId"
            placeholder="City"
            value={formData.cityId}
            onChange={handleChange}
            className="border rounded p-2 mb-2 w-full text-black"
          /> */}

            <input
              readOnly
              type="text"
              name="countryId"
              placeholder="Country"
              // value={formData.countryId}
              value="Nigeria"
              // onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            />

            {/* <input
              type="text"
              name="postalCode"
              placeholder="Postal Code"
              value={formData.postalCode}
              onChange={handleChange}
              className="border rounded p-2 mb-2 w-full text-black"
            /> */}

            {/* <div className="flex items-center">
              <label htmlFor="toggleSwitch" className="flex items-center cursor-pointer">
                <div className="relative">
                  <input
                    type="checkbox"
                    id="toggleSwitch"
                    className="sr-only"
                    checked={isChecked}
                    onChange={handleToggle}
                  />
                  <div className="block bg-[#DD3D73] w-12 h-7 rounded-full"></div>
                  <div
                    className={`dot absolute left-1 top-1 bg-white w-5 h-5 rounded-full transition ${isChecked ? 'transform translate-x-full' : ''
                      }`}
                  ></div>
                </div>
              </label>
              <span className="ml-2 text-black">Set default Address ?</span>
            </div> */}
            {actiontype === "Add" ? (
              <button
                type="submit"
                className="mt-4 px-4 py-2 bg-[#FF332B] text-white rounded hover:bg-black"
              >
                Submit
              </button>
            ) : (
              <button
                type="submit"
                className="mt-4 px-4 py-2 bg-[#FF332B] text-white rounded hover:bg-black"
              >
                Save
              </button>
            )}
          </form>
        </div>
      </div>
    </div>
  );
};

export default Modal;
