"use client";

import React, { useState } from "react";
import axios from "axios";

export default function Newsletter() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !email.includes("@")) return;

    setStatus("submitting");

    const emailData = {
      name: "Newsletter Subscriber",
      email: email,
      phone: "N/A",
      service: "Newsletter Subscription",
      message: `A new user has subscribed to the newsletter: <b>${email}</b>`,
      to: "info@vgfenceproducts.com",
      senderName: "VG Fence Newsletter",
    };

    try {
      await axios.post("https://mailserver.metatronnest.com/send", emailData, {
        headers: { "Content-Type": "application/json" },
      });
      setStatus("success");
      setEmail("");
    } catch (error) {
      console.error("❌ Error subscribing to newsletter:", error);
      setStatus("error");
    }
  };

  return (
    <section className="newsletter-section">
      <div className="newsletter-inner reveal">
        <div className="section-eyebrow center">Stay in the loop</div>
        <h2 className="newsletter-h2">Product Updates &<br /><span>Contractor Deals.</span></h2>
        <p className="newsletter-sub">
          New product arrivals, seasonal promotions, and industry tips — delivered to your inbox.<br />
          No spam, unsubscribe anytime.
        </p>
        
        {status === "success" ? (
          <div className="newsletter-success" style={{ textAlign: 'center', padding: '20px', background: 'rgba(22, 163, 74, 0.1)', borderRadius: '8px', border: '1px solid #16A34A', color: '#16A34A', fontWeight: 600 }}>
            Thank you! You've been subscribed successfully. ✓
          </div>
        ) : (
          <form className="newsletter-form" onSubmit={handleSubmit}>
            <input 
              type="email" 
              className="newsletter-input" 
              placeholder="Enter your email address" 
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required 
              disabled={status === "submitting"}
            />
            <button type="submit" className="newsletter-btn" disabled={status === "submitting"}>
              {status === "submitting" ? "Subscribing..." : "Subscribe →"}
            </button>
          </form>
        )}
        
        {status === "error" && (
          <p style={{ color: '#ef4444', fontSize: '14px', marginTop: '10px', textAlign: 'center' }}>
            Failed to subscribe. Please try again later.
          </p>
        )}
        
        <div className="newsletter-note">Join contractors and builders across Ontario · 1–6 emails per month</div>
      </div>
    </section>
  );
}

