import Image from "next/image";
import React, { ChangeEvent, useEffect, useState } from "react";
import { AiOutlineCamera } from "react-icons/ai";
import styles from "@/styles/common/small.module.css";
import { useDispatch } from "react-redux";
import Cookies from "js-cookie";
import axios from "axios";
import toast, { Toaster } from "react-hot-toast";
import { setUser } from "@/Redux/userSlice";
import { useRouter } from "next/router";
import { motion } from "framer-motion";
import Loader from "@/components/helpers/Loader";
import { LoadingOutlined } from "@ant-design/icons";
import { Modal, Spin } from "antd";
import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng,
} from "react-places-autocomplete";
import Script from "next/script";
import { userActivity } from "@/components/commonFunctions/userActivity";
import Head from "next/head";
// import { Modal, Upload } from "antd";
const PaystackApiKey = process.env.API_KEY;
const GEOCODE_API_KEY = process.env.GEOCODE_API_KEY;

const scriptSrc = `https://maps.googleapis.com/maps/api/js?key=${GEOCODE_API_KEY}&libraries=places`;

const LoadingIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

export default function SignUp() {
  const dispatch = useDispatch();
  const router = useRouter();

  const [state, setState] = useState<any>([]);
  const [cities, setCities] = useState([]);
  const [selectedStateId, setSelectedStateId] = useState("");

  const [bankNames, setBankNames] = useState<any>([]);
  const [bankCode, setBankCode] = useState<any>("");

  const [mergeModal, setMergeModal] = useState(false);
  const [mergeModalMessage, setMergeModalMessage] = useState("");

  const [bankDetails, setBankDetails] = useState({
    account_name: "",
    account_number: "",
    bank_id: "",
  });

  const [loading, setLoading] = useState<boolean>(false);

  const [userProfile, setuserProfile] = useState({
    _id: "",
    firstName: "",
    lastName: "",
    phoneCode: "",
    phone: "",
    email: "",
    about: "",
    photo: "",
    address: "",
    bankName: "",
    bankAccount: "",
    stateId: "",
    cityId: "",
    city: { _id: "", name: "" },
    state: { _id: "", name: "" },
  });

  const [updateTriggered, setUpdateTriggered] = useState(false);
  const [scriptLoaded, setScriptLoaded] = useState(false);

  const [phoneExists, setPhoneExists] = useState(false);

  const authToken = Cookies.get("jazz_token");

  const axiosInstance = axios.create({
    baseURL: "https://api.jazzagain.com/public/index.php",
    headers: {
      authorization: `Bearer ${authToken}`,
    },
  });

  useEffect(() => {
    const getStates = async () => {
      const response = await fetch(
        "https://api.jazzagain.com/public/index.php/api/getCountryStates/160"
      )
        .then((res) => res.json())
        .then((json) => setState(json.states));
    };
    getStates();
  }, []);

  useEffect(() => {
    if (authToken) {
      getBankNames();

      // Fetch user profile and set bank account and bank code if available
      axiosInstance
        .get("api/user/getProfile")
        .then((response: any) => {
          const profileData = response.data.profile;
          setuserProfile(profileData);

          // Set the bank account and bank code if available
          if (profileData.bankAccount && profileData.bankName) {
            const selectedBank = bankNames.find(
              (bank: any) => bank.name === profileData.bankName
            );
            if (selectedBank) {
              setBankCode(selectedBank.code);
            }
          }

          if (profileData && profileData.phone) {
            setPhoneExists(true);
          }
        })
        .catch((error: any) => {
          console.error("Error fetching data:", error);
        });
    }

    return () => {};
  }, []);

  const getBankNames = async () => {
    const res = await axios.get("https://api.paystack.co/bank", {
      headers: {
        Authorization: `Bearer ${PaystackApiKey}`,
      },
    });
    setBankNames(res.data.data);
  };

  useEffect(() => {
    if (updateTriggered && userProfile) {
      UpdateProfile();
      setUpdateTriggered(!updateTriggered);
    }
    return () => {};
  }, [updateTriggered]);

  useEffect(() => {
    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);
    };

    document.head.appendChild(script);

    // Cleanup: Remove the script from the head when the component is unmounted
    return () => {
      document.head.removeChild(script);
    };
  }, []);

  const handleChange = (
    e: ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    if (name === "bankName") {
      // Validation logic for bankName
      const selectedBankName = value;
      const selectedBank = bankNames.find(
        (bank: any) => bank.name === selectedBankName
      );
      setBankCode(selectedBank.code);
      setuserProfile((prevData) => ({
        ...prevData,
        [name]: value,
      }));
    } else if (name === "stateId") {
      // Validation logic for 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();

      setuserProfile((prevData) => ({
        ...prevData,
        [name]: afterValue,
      }));
    } else if (name === "phone") {
      // Validation logic for phone
      const numericValue = value.replace(/[^0-9]/g, "");
      const maxLength = 11;

      if (numericValue.length <= maxLength) {
        setuserProfile((prevData) => ({
          ...prevData,
          [name]: numericValue,
        }));
      }
    } else {
      // Default case for other fields
      setuserProfile((prevData) => ({
        ...prevData,
        [name]: value,
      }));
    }
  };

  const UpdateProfile = async () => {
    if (
      userProfile.firstName &&
      userProfile.lastName &&
      userProfile.address &&
      userProfile.bankAccount &&
      userProfile.bankName &&
      userProfile.email &&
      userProfile.phone &&
      userProfile.stateId &&
      userProfile.cityId
    ) {
      const bankCode = bankNames.find(
        (item: any) => item.name === userProfile.bankName
      );
      setBankCode(bankCode.code);
      const isVerifiedAccount = await VerifyAccount();

      if (!isVerifiedAccount) return toast.error("Invalid Account Details !");
      if (isVerifiedAccount) {
        let _profile;
        try {
          const results = await geocodeByAddress(userProfile.address);
          const latLng = await getLatLng(results[0]);

          _profile = {
            ...userProfile,
            latitude: latLng?.lat,
            longitude: latLng?.lng,
          };
        } catch (error) {
          toast.error("Error during geocoding");
        }

        axiosInstance
          .put("/api/user/updateProfile", _profile)
          .then((response) => {
            // Check if the response includes the necessary profile data
            if (
              response.data &&
              response.data.profile &&
              response.data.profile._id
            ) {
              dispatch(
                setUser({
                  _id: response.data.profile._id,
                  phone: response.data.profile.phone,
                  photo: response.data.profile.photo,
                  email: response.data.profile.email,
                })
              );
            }

            // Display the message from the server if available
            if (response.data && response.data.message) {
              toast.success(response.data.message);
            } else {
              userActivity(
                userProfile?._id,
                "website",
                "seller signup page",
                {
                  formSubmit: "completed",
                },
                navigator.userAgent
              );
              // Fallback message if none is provided by the server
              toast.success("Profile updated successfully");
            }

            if (response.data.status === true) {
              // setLoading(false)
              router.push("/");
            }

            if (response.data.status === false) {
              setMergeModal(true);
              setMergeModalMessage(response.data.message);
            }
          })
          .catch((error) => {
            toast.error(error.response?.data?.message);
          });
      }
    } else {
      toast.error("All fields are required !");
    }
  };

  const handleProfileImage = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];

    if (file) {
      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await axios.post(
          "https://api.jazzagain.com/public/index.php/api/uploadImage",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          }
        );

        setuserProfile((prevData) => ({
          ...prevData,
          photo: response.data.file,
        }));
        setUpdateTriggered(true);
      } catch (error) {
        console.error("Error uploading file:", error);
      }
    }
  };

  const handleSelect = (address: any) => {
    setuserProfile((prevData) => ({
      ...prevData,
      address: address,
    }));

    geocodeByAddress(address)
      .then((results) => getLatLng(results[0]))
      .then((coords) => {
        setuserProfile((prevData) => ({
          ...prevData,
          latitude: coords.lat,
          longitude: coords.lng,
        }));
      })
      .catch((error) => console.error("Error", error));
  };

  const handleChange2 = (address: any) => {
    setuserProfile((prevData) => ({
      ...prevData,
      address: address,
    }));
  };

  const VerifyAccount = async () => {
    const fetchbankCode = await bankNames.find(
      (item: any) => item.name === userProfile.bankName
    );
    setBankCode(fetchbankCode.code);
    if (fetchbankCode && userProfile.bankAccount) {
      setLoading(true);
      try {
        const res = await axios.get(
          `https://api.paystack.co/bank/resolve?account_number=${userProfile.bankAccount}&bank_code=${fetchbankCode.code}`,
          {
            headers: {
              Authorization: `Bearer ${PaystackApiKey}`,
            },
          }
        );
        setBankDetails(res.data.data);
        userActivity(
          userProfile?._id,
          "website",
          "seller signup page",
          {
            formSubmit: "verify account no. completed",
          },
          navigator.userAgent
        );
        setLoading(false);
        toast.success("Account Verified");
        return true;
      } catch (error) {
        userActivity(
          userProfile?._id,
          "website",
          "seller signup page",
          {
            formSubmit: "invalid account no.",
          },
          navigator.userAgent
        );
        setLoading(false);
        toast.error("Invalid Account Details !");
        return false;
      }
    } else {
      toast.error("Enter correct bank account and bank name.");
    }
  };

  const verifyNumber = async () => {
    const data = {
      phone: userProfile?.phone,
      phoneCode: "+234",
    };
    const verifyResponse = await axiosInstance.post(
      `https://api.jazzagain.com/public/index.php/api/user/socialLoginByOtp`,
      data
    );
    router.push(`/auth/verify-mobile-otp?merge=true&ph=${userProfile?.phone}`);
  };

  return (
    <>
      <Head>
        <link rel="shortcut icon" href="/images/jazzagian-logo.png" />
        <script
          dangerouslySetInnerHTML={{
            __html: `
              !function(f,b,e,v,n,t,s)
              {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
              n.callMethod.apply(n,arguments):n.queue.push(arguments)};
              if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
              n.queue=[];t=b.createElement(e);t.async=!0;
              t.src=v;s=b.getElementsByTagName(e)[0];
              s.parentNode.insertBefore(t,s)}(window, document,'script',
              'https://connect.facebook.net/en_US/fbevents.js');
              fbq('init', '360254480441103');
              fbq('track', 'Seller');
            `,
          }}
        />
        <noscript>
          <Image
            height="1"
            width="1"
            alt=""
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=360254480441103&ev=Seller&noscript=1"
          />
        </noscript>
      </Head>

      <div
        className={"text-black grid text-xl py-[2rem] my-[1.5rem] rounded-lg mx-auto lg:w-[50%] bg-white ".concat(
          styles.shadowsmooth
        )}
      >
        <Script src={scriptSrc}></Script>

        <Toaster
          toastOptions={{
            className: "",
            duration: 2000,
          }}
        />

        <Modal
          centered={true}
          open={mergeModal}
          onCancel={() => setMergeModal(false)}
          maskStyle={{ background: "gray", opacity: 0.7 }}
          footer={null}
        >
          <div className="p-5">
            <p className="text-lg font-bold m-2">{mergeModalMessage}</p>
            <button
              type="button"
              className="inline-flex cursor-pointer items-center gap-1 rounded border border-slate-300 bg-gradient-to-b from-slate-50 to-slate-200 px-4 py-2 font-semibold hover:opacity-90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-300 focus-visible:ring-offset-2 active:opacity-100 m-2"
              onClick={verifyNumber}
            >
              Verify Number
            </button>
            <button
              type="button"
              className="inline-flex cursor-pointer items-center gap-1 rounded border border-slate-300 bg-gradient-to-b from-slate-50 to-slate-200 px-4 py-2 font-semibold hover:opacity-90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-300 focus-visible:ring-offset-2 active:opacity-100 m-2"
              onClick={() => setMergeModal(false)}
            >
              Change Number
            </button>
          </div>
        </Modal>

        <h1 className="w-[85%] mx-auto font-semibold">SELLER SIGN UP</h1>
        <hr className="border-4 border-[#FEE3E1] my-[1.5rem]" />

        <div className="w-[85%] mx-auto">
          <h2 className="py-3">Basic Information</h2>
          <div className="relative">
            <Image
              src={
                userProfile.photo
                  ? `https://api.jazzagain.com/public/${userProfile?.photo}`
                  : "https://www.jazzagain.com/images/user.png"
              }
              width={150}
              height={150}
              alt=""
              style={{ borderRadius: "5px" }}
            />
            <div
              style={{ borderRadius: " 0 0 100px 100px", left: "3px" }}
            ></div>
            <label>
              <AiOutlineCamera
                size={35}
                className="z-20 text-gray-200 absolute bottom-6 left-14"
              />
              <input
                type="file"
                onChange={handleProfileImage}
                className="hidden"
              />
            </label>
          </div>

          <div>
            <label htmlFor="firstName" className="text-xs text-gray-500">
              Enter your first name *
            </label>
            <br />
            <input
              id="firstName"
              name="firstName"
              type="text"
              maxLength={30}
              value={userProfile.firstName}
              onChange={handleChange}
              className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
            />
            <br />
            <p className="float-right text-xs text-gray-700">
              {userProfile.firstName ? userProfile.firstName?.length : 0}/30
            </p>
          </div>

          <div>
            <label htmlFor="name" className="text-xs text-gray-500">
              Enter your last name *
            </label>
            <br />
            <input
              id="lastName"
              name="lastName"
              type="text"
              maxLength={30}
              value={userProfile.lastName}
              onChange={handleChange}
              className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
            />
            <br />
            <p className="float-right text-xs text-gray-700">
              {userProfile.lastName ? userProfile.lastName?.length : 0}/30
            </p>
          </div>
        </div>

        {/* contact Information */}
        <hr className="border-4 border-[#FEE3E1] my-[1.5rem]" />

        <div className="w-[85%] mx-auto">
          <h2 className="py-3">Contact Information</h2>

          <div className="flex">
            <div className="w-full">
              <label htmlFor="phone" className="text-xs text-gray-500">
                Phone Number *
              </label>
              <br />
              <input
                type="text"
                id="phone"
                name="phone"
                value={userProfile.phone}
                onChange={handleChange}
                disabled={phoneExists}
                className={`bg-transparent border-b ${
                  phoneExists ? "border-gray-300" : "border-[#FF332B]"
                } focus:outline-none w-full`}
              />
            </div>
          </div>
          <br />
          {/* <p className="text-xs text-gray-700 mt-[-1.5rem]">
          Yay! Your number is verified.
        </p> */}

          <div className="pt-[1rem]">
            <label htmlFor="email" className="text-xs text-gray-500">
              Email *
            </label>
            <br />
            <input
              type="email"
              id="email"
              name="email"
              value={userProfile.email}
              onChange={handleChange}
              className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
            />
            {/* <p className="text-xs text-gray-700 pt-1">
            Yay! You have verified your email. It&apos;s important to allow us
            to securely communicate with you.
          </p> */}
          </div>

          {/* <div className="pt-[1rem] flex">
          <input
            type="text"
            id=""
            name=""
            disabled
            value={userProfile.state.name}
            onChange={handleChange}
            className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
          />
          <button type="button" className="bg-red-300">Change</button>
       
        </div>
        <div className="pt-[1rem]">
          <input
            type="text"
            id=""
            name=""
            disabled
            value={userProfile.city.name}
            onChange={handleChange}
            className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
          />
        </div> */}

          {/* <p>
          {
            userProfile.city && userProfile.state ?
            userProfile.city.name +", " + userProfile.state.name
            : null
          }
          <button type="button" onClick={()=>setCityStateChange(!cityStateChange)}>Change</button>
        </p> */}

          <label htmlFor="stateId" className="text-xs text-gray-500">
            State *
          </label>
          <br />
          <select
            name="stateId"
            // value={userProfile.stateId}
            onChange={handleChange}
            className="border rounded p-2 mb-2 w-full text-black text-sm my-4"
          >
            <option value="" disabled selected={true}>
              Select a state
            </option>
            {state.map((state: any) => (
              <option key={state._id} value={`${state.id}/${state._id}`}>
                {state.name}
              </option>
            ))}
          </select>

          <label htmlFor="cityId" className="text-xs text-gray-500">
            Local Government Area - LGA *
          </label>
          <br />
          <select
            name="cityId"
            value={userProfile.cityId}
            onChange={handleChange}
            className="border rounded p-2 mb-2 w-full text-black text-sm my-4"
          >
            <option value="" disabled selected={true}>
              Select Local Government Area - LGA
            </option>
            {cities.map((city: any) => (
              <option key={city._id} value={city._id}>
                {city.name}
              </option>
            ))}
          </select>

          {/* <div className="py-[1rem]">
          <label htmlFor="address" className="text-xs text-gray-500">
            Address *
          </label>
          <br />
          <input
            id="address"
            name="address"
            type="text"
            value={userProfile.address}
            onChange={handleChange}
            className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
          />
        </div> */}

          <label htmlFor="address" className="text-xs text-gray-500">
            Address *
          </label>
          {scriptLoaded && (
            <PlacesAutocomplete
              value={userProfile.address}
              onChange={handleChange2}
              onSelect={handleSelect}
            >
              {({
                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>
          )}
        </div>

        {/* account Information */}
        <hr className="border-4 border-[#FEE3E1] my-[1.5rem]" />

        <div className="w-[85%] mx-auto">
          <h2 className="py-3">Account Information</h2>
          <div className="flex justify-between">
            <label htmlFor="bankName" className="text-xs text-gray-500 my-2">
              Bank Name *
            </label>
            <select
              name="bankName"
              value={userProfile.bankName}
              onChange={handleChange}
              className="border rounded p-2 mb-2 text-black text-sm w-[80%]"
            >
              <option value="">Select a Bank</option>
              {bankNames.map((bank: any) => (
                <option key={bank.id} value={bank.name}>
                  {bank.name}
                </option>
              ))}
            </select>
            <p></p>
          </div>

          {/* <div className="py-[1rem]">
          <label htmlFor="bankName" className="text-xs text-gray-500">
            Bank Name
          </label>
          <br />
          <input
            id="bankName"
            name="bankName"
            type="text"
            value={userProfile.bankName}
            onChange={handleChange}
            className="bg-transparent border-b border-[#FF332B] focus:outline-none w-full"
          />
        </div> */}

          <div className="flex justify-between">
            <label htmlFor="bankAccount" className="text-xs text-gray-500">
              Account No: *
            </label>
            <input
              id="bankAccount"
              name="bankAccount"
              type="text"
              value={userProfile.bankAccount}
              onChange={handleChange}
              className="bg-transparent border-b border-[#FF332B] focus:outline-none w-[40%]"
            />
            <button
              type="button"
              onClick={VerifyAccount}
              className="py-2 px-5 bg-gray-800 hover:bg-black text-white rounded-lg text-sm"
            >
              {loading ? (
                <>
                  <Spin indicator={LoadingIcon} className="mr-2" />
                  <span>verifying...</span>
                </>
              ) : (
                "Verify"
              )}
            </button>
          </div>

          {bankDetails?.account_name && (
            <div className="py-[1rem] flex justify-between">
              <label htmlFor="address" className="text-xs text-gray-500">
                User Account Name
              </label>
              <input
                disabled
                type="text"
                value={bankDetails.account_name}
                className="bg-transparent border-b border-[#FF332B] focus:outline-none w-[70%]"
              />
            </div>
          )}
        </div>

        <div className="w-[85%] mx-auto my-[1rem]">
          <motion.button
            className="py-[.7rem] px-5 bg-[#FF332B] hover:bg-[#b4140f] text-white rounded-lg text-sm"
            onClick={UpdateProfile}
            whileTap={{ scale: 0.9 }}
            transition={{ duration: 0.2 }}
          >
            SAVE DETAILS
          </motion.button>
        </div>
      </div>
    </>
  );
}
