"use client";

import { useState, useEffect, useMemo } from "react";
import Image from "next/image";
import Link from "next/link";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../store"; // adjust path as needed
import { toast } from "react-toastify";
import { subscribeNewsletter } from "../api/api"; // adjust path if needed

import facebook from "../assets/facebook1.svg";
import youtube from "../assets/youtube.svg";
import twitter from "../assets/twitter1.svg";
import instagram from "../assets/instagram.svg";
// import Popup from "./ConfirmationPopUp";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
const Popup = dynamic(() => import("./ConfirmationPopUp"));

export default function Footer() {
  const router = useRouter();
  const dispatch = useDispatch<any>();
  const [showModal, setShowModal] = useState(false);
  const [emailName, setEmail] = useState("");
  const [hasMounted, setHasMounted] = useState(false);

  const { homedata } = useSelector(
    (state: RootState) => state.HomeContentReducer
  );
  const { isLoggedIn } = useSelector((state: RootState) => state.loginReducer);
  const { categories } = useSelector(
    (state: RootState) => state.CategoryListing
  );

  const { incrementData } = useSelector(
    (state: RootState) => state.MessageCountReducer
  );
  const AuctionSellerFee = useMemo(
    () => incrementData?.data?.auctionFee[0]?.seller_fee,
    [incrementData]
  );
  const { cashWalletHistoryData } = useSelector(
    (state: RootState) => state.WalletReducer
  );
  const WalletBalance = useMemo(
    () => cashWalletHistoryData?.wallet_balance,
    [cashWalletHistoryData]
  );

  const settings = homedata?.data?.settings;
  useEffect(() => {
    setHasMounted(true);
  }, []);

  const getCategoryUrl = (id: number, name: string): string => {
    const categoryName = name
      ?.replace(/[^a-zA-Z0-9\s]/g, "")
      .replace(/\s+/g, "-")
      .toLowerCase();

    return `/${id}/${categoryName}`;
  };

  const handleCategoryClick = (id: number, name: string) => {
    const url = getCategoryUrl(id, name);
    router.push(url);
  };

  const handleCategoryPrefetch = (id: number, name: string) => {
    const url = getCategoryUrl(id, name);
    router.prefetch(url);
  };

  const handlePostAdd = () => {
    //To close sidebar in small devices.
    if (isLoggedIn) {
      if (Number(WalletBalance) > Number(AuctionSellerFee)) {
        router.push("/post-ad");
      } else {
        setShowModal(true);
        console.log("Show popup");
      }
    } else {
      router.push("/auth/login");
    }
  };

  const navigateToAddWallet = () => {
    window.scroll(0, 0);
    router.push("/profile/wallet/transaction/");
  };
  const handleSubmit = async () => {
    try {
      const response = await dispatch(
        subscribeNewsletter({ email: emailName })
      );

      if (subscribeNewsletter?.fulfilled.match(response)) {
        setEmail("");
        toast.success(response?.payload?.data?.message);
      } else {
        toast.error(response?.payload || "An error occurred");
      }
    } catch {
      toast.error("Something went wrong while subscribing");
    }
  };

  // Prevent hydration mismatch by rendering after mount and if settings exist
  if (!hasMounted || !settings) return <div className="min-h-[100px]" />;

  return (
    <footer className="bg-navy text-white xs:p-6 lg:p-12 bottom-0">
      <div className="max-w-7xl mx-auto">
        <div className="flex flex-col md:flex-row justify-between gap-8 py-2">
          <div className="space-y-3 lg:w-[74%] text-start">
            <h2 className="md:text-2xl lg:text-4xl font-semibold">
              Subscribe to our Newsletter
            </h2>
            <p className="text-sm md:text-base  text-[18px] text-white">
              {settings.footer_content}
            </p>

            <div className="relative mt-2">
              <input
                type="email"
                placeholder="Email Address"
                value={emailName}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full py-2 pl-4 pr-32 rounded-md bg-gray-200 text-gray-800"
                required
              />
              <button
                onClick={handleSubmit}
                className="absolute top-0 right-0 px-6 py-2 bg-[#F8CB1F] rounded-r-md text-black transition duration-200"
              >
                Subscribe
              </button>
            </div>
          </div>

          <div className="md:flex-row gap-4  flex justify-center text-start w-full">
            <div className="w-full md:w-1/2">
              <h3 className="text-lg font-semibold lg:text-start lg:pr-16">
                Quick Links
              </h3>
              <div className="lg:flex lg:justify-center lg:text-start gap-10">
                <ul className="mt-4 space-y-2">
                  {categories?.data?.slice(0, 4).map((item: any) => (
                    <li key={item.id}>
                      <div
                        onClick={() => handleCategoryClick(item.id, item.name)}
                        onMouseEnter={() =>
                          handleCategoryPrefetch(item.id, item.name)
                        }
                        className="text-sm text-gray-300 hover:text-white transition-colors cursor-pointer"
                      >
                        {item.name}
                      </div>
                    </li>
                  ))}
                </ul>
                <ul className="mt-4 space-y-2 cursor-pointer">
                  {categories?.data?.slice(4, 8).map((item: any) => (
                    <li key={item.id}>
                      <div
                        onClick={() => handleCategoryClick(item.id, item.name)}
                        className="text-sm text-gray-300 hover:text-white transition-colors cursor-pointer"
                      >
                        {item.name}
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            </div>

            <div className="w-full md:w-1/2">
              <h3 className="text-lg lg:text-start lg:pl-[5.2rem] font-semibold">
                Info
              </h3>
              <div className="lg:flex lg:justify-center gap-10 text-start">
                <ul className="mt-4 space-y-2">
                  <li>
                    <p
                      onClick={() => router.push("/about")}
                      className="text-sm text-gray-300 hover:text-white transition-colors cursor-pointer"
                    >
                      About
                    </p>
                  </li>
                  <li>
                    <p
                      // to="auth/login"
                      onClick={handlePostAdd}
                      className="text-sm text-gray-300 hover:text-white transition-colors cursor-pointer"
                    >
                      Post Ad
                    </p>
                  </li>
                </ul>
                <ul className="mt-4 space-y-2">
                  <li>
                    <p
                      onClick={() => router.push("/terms")}
                      className="text-sm cursor-pointer text-gray-300 hover:text-white transition-colors"
                    >
                      Terms of Use
                    </p>
                  </li>
                  <li>
                    <p
                      onClick={() => router.push("/privacy")}
                      // href="/privacy"
                      className="text-sm cursor-pointer text-gray-300 hover:text-white transition-colors"
                    >
                      Privacy Policy
                    </p>
                  </li>
                  <li>
                    <p
                      onClick={() => router.push("/profile/tickets")}
                      className="text-sm cursor-pointer text-gray-300 hover:text-white transition-colors"
                    >
                      Help Desk
                    </p>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <div className="flex flex-col-reverse items-center lg:flex-row lg:justify-between gap-4 border-t border-gray-600 pt-8 mt-4 text-center lg:text-left">
          <p className="lg:text-[18px] xs:text-[12px] text-white">
            All rights reserved. Google, Google Play, YouTube and other marks
            are trademarks of Google Inc.
          </p>
          <div className="flex gap-4">
            <Link href={settings.facebook} target="_blank">
              <Image
                unoptimized
                src={facebook}
                className="h-8 w-8 hover:opacity-80"
                alt="Facebook"
              />
            </Link>
            <Link href={settings.twitter} target="_blank">
              <Image
                unoptimized
                src={twitter}
                className="h-8 w-8 hover:opacity-80"
                alt="Twitter"
              />
            </Link>
            <Link href={settings.instagram} target="_blank">
              <Image
                unoptimized
                src={instagram}
                className="h-8 w-8 hover:opacity-90"
                alt="Instagram"
              />
            </Link>
            <Link href={settings.youtube} target="_blank">
              <Image
                unoptimized
                src={youtube}
                className="h-8 w-8 hover:opacity-80"
                alt="YouTube"
              />
            </Link>
          </div>
        </div>
      </div>
      <Popup
        showPopup={showModal}
        message={
          <div>
            <p className="text-red-600">Insufficient wallet balance</p>
            <p className="mt-2 text-gray-600">
              You might need to add funds to your wallet. Minimum required
              wallet balance is {AuctionSellerFee}
            </p>
          </div>
        }
        onClose={() => {
          setShowModal(false);
        }}
        onConfirm={() => setShowModal(false)}
        onAddWallet={() => {
          setShowModal(false);
          navigateToAddWallet();
        }}
        showAddWalletButton={true}
      />
    </footer>
  );
}
