"use client";

import { useEffect, useState } from "react";
import { toast } from "sonner";

const Newsletter = ({ settings }: any) => {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [setting, setSetting] = useState<any>({})

  useEffect(() => {
    const raw_settings = localStorage.getItem('general-settings')
    if(raw_settings){
      setSetting(JSON.parse(raw_settings))
    }
  }, [])
  useEffect(() => {
    // console.log('STG', setting)
  }, [setting])
  const handleSubscribe = async () => {
    // console.log("Subscribe button clicked with email:", email);
    const trimmedEmail = email.trim();

    if (!trimmedEmail) {
      toast.error("Please enter your email address");
      return;
    }
    const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
    if (!emailRegex.test(trimmedEmail)) {
      toast.error("Please enter a valid email address");
      return;
    }

    try {
      setLoading(true);
      // console.log("Subscribing email:", trimmedEmail);

      // Using fetch directly
      const response = await fetch("/clientapi/newsletter", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: trimmedEmail,
        }),
      });

      const data = await response.json();
      // console.log("API Response:", data);

      if (
        response.ok &&
        (data.success === true || data?.data?.success === true)
      ) {
        toast.success(
          data.message || data?.data?.message || "Subscribed successfully",
        );
        setEmail("");
      } else {
        toast.error(
          data.message || data?.data?.message || "Failed to subscribe",
        );
      }
    } catch (error: any) {
      console.error("Subscription error:", error);
      toast.error(error?.message || "Failed to subscribe. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
          <div className="blogbtmimg mt-10">
        <img
          alt=""
          src="/images/blog-btm-img.png"
          className="w-full"
        />
      </div>
    <section className="newslettercontainer !pt-0">
      <div className="container container-xxl px-3">
        <div className="-mx-3 flex flex-wrap">
          {/* Contact Us */}
          <div className="w-full px-3 sm:w-full md:w-full lg:w-1/4 xl:w-1/4 2xl:w-1/4">
            <div className="contactinfo text-center">
              <h3>Contact Us</h3>
              <p>
                Email:{" "}
                <a href={`mailto:${settings?.email || settings?.email}`}>{settings?.email || setting?.email}</a>
              </p>
              <p>
                Phone:{" "}
                <a href={`tel:${settings?.phoneNumber || setting?.phoneNumber}`}>
                  {settings?.phoneNumber || setting?.phoneNumber}
                </a>
              </p>
            </div>
          </div>

          {/* Newsletter */}
          <div className="w-full px-3 sm:w-full md:w-full lg:w-1/2 xl:w-1/2 2xl:w-1/2">
            <div className="newsletterbx text-center">
              <h3>Let's Get in Touch!</h3>
              <p>
                What's inside? Exclusive sales, new arrivals &amp; much more.
              </p>

              <div className="mb-2 flex">
                <input
                  className="form-control"
                  type="email"
                  placeholder="Email Address"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
                <button
                  className="subscribebtn"
                  type="button"
                  disabled={loading}
                  onClick={handleSubscribe}
                >
                  {loading ? "Subscribing..." : "Subscribe"}
                </button>
              </div>
              <p className="m-0 gray-text">
                New styles, exclusive offers &amp; more! Subscribe now
              </p>
            </div>
          </div>

          {/* Social Media */}
          <div className="w-full px-3 sm:w-full md:w-full lg:w-1/4 xl:w-1/4 2xl:w-1/4">
            <div className="socialbx text-center">
              <h3>Social Media</h3>
              <div className="socialrow">
                <a
                  className="socialbtn"
                  href={settings?.facebookLink || setting?.facebookLink ||  "#"}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <i className="icon icon-facebook"></i>
                  <span>Facebook</span>
                </a>
                <a
                  className="socialbtn"
                  href={settings?.printerestLink || setting?.printerestLink || "#"}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <i className="icon icon-pinterest"></i>
                  <span>Pinterest</span>
                </a>
                <a
                  className="socialbtn"
                  href={settings?.youtubeLink || setting?.youtubeLink || "#"}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <i>
                    <svg className="h-6 w-6" viewBox="0 -0.5 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path fillRule="evenodd" clipRule="evenodd" d="M18.168 19.0028C20.4724 19.0867 22.41 17.29 22.5 14.9858V9.01982C22.41 6.71569 20.4724 4.91893 18.168 5.00282H6.832C4.52763 4.91893 2.58998 6.71569 2.5 9.01982V14.9858C2.58998 17.29 4.52763 19.0867 6.832 19.0028H18.168Z" stroke="currentColor" stroke-width="1" strokeLinecap="round" strokeLinejoin="round"/>
                      <path fillRule="evenodd" clipRule="evenodd" d="M12.008 9.17784L15.169 11.3258C15.3738 11.4454 15.4997 11.6647 15.4997 11.9018C15.4997 12.139 15.3738 12.3583 15.169 12.4778L12.008 14.8278C11.408 15.2348 10.5 14.8878 10.5 14.2518V9.75184C10.5 9.11884 11.409 8.77084 12.008 9.17784Z" stroke="currentColor" stroke-width="1" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </i>
                  <span>You Tube</span>
                </a>
                <a
                  className="socialbtn"
                  href={settings?.instagramLink || setting?.instagramLink || "#"}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <i className="icon icon-instagram"></i>
                  <span>Instagram</span>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
    </>

  );
};

export default Newsletter;
