"use client";

import { FormEvent, useState } from "react";
import {
    sendNewsletterSubscription,
    isValidEmail,
} from "@/lib/emailjs";

export default function ThankYouNewsletter() {
    const [email, setEmail] = useState("");
    const [loading, setLoading] = useState(false);
    const [status, setStatus] = useState<{
        type: "success" | "error";
        message: string;
    } | null>(null);

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();
        setStatus(null);

        if (!email.trim() || !isValidEmail(email)) {
            setStatus({
                type: "error",
                message: "Please enter a valid email address.",
            });
            return;
        }

        setLoading(true);
        try {
            await sendNewsletterSubscription({ email });
            setStatus({
                type: "success",
                message: "Successfully subscribed to the newsletter.",
            });
            setEmail("");
        } catch {
            setStatus({
                type: "error",
                message: "Something went wrong. Please try again later.",
            });
        } finally {
            setLoading(false);
        }
    };

    return (
        <section className="bg-white py-12 px-4 border-t border-slate-100">
            <div className="max-w-4xl mx-auto flex flex-col md:flex-row items-center justify-between gap-8 bg-slate-50 rounded-2xl p-8 border border-slate-100">
                <div className="flex-1">
                    <h3 className="text-xl font-bold text-thankyou-slate-900 mb-2">
                        Subscribe to our newsletter
                    </h3>
                    <p className="text-thankyou-slate-600 text-sm">
                        Get the latest updates and resources delivered to your inbox weekly.
                    </p>
                </div>
                <div className="w-full md:w-auto">
                    <form
                        onSubmit={handleSubmit}
                        className="w-full flex flex-col sm:flex-row gap-3"
                    >
                        <input
                            className="w-full sm:w-64 px-4 py-2.5 rounded-lg border border-slate-200 focus:outline-none focus:ring-2 focus:ring-thankyou-primary focus:border-transparent text-sm"
                            placeholder="Enter your email"
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            disabled={loading}
                            required
                        />
                        <button
                            type="submit"
                            className="bg-thankyou-slate-900 hover:bg-slate-800 text-white font-medium px-5 py-2.5 rounded-lg text-sm transition-colors whitespace-nowrap flex items-center justify-center gap-2 disabled:opacity-60 disabled:cursor-not-allowed"
                            disabled={loading}
                        >
                            {loading ? (
                                <>
                                    <svg
                                        className="animate-spin h-4 w-4"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                    >
                                        <circle
                                            className="opacity-25"
                                            cx="12"
                                            cy="12"
                                            r="10"
                                            stroke="currentColor"
                                            strokeWidth="4"
                                        />
                                        <path
                                            className="opacity-75"
                                            fill="currentColor"
                                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                                        />
                                    </svg>
                                    Subscribing...
                                </>
                            ) : (
                                "Subscribe"
                            )}
                        </button>
                    </form>
                    {status && (
                        <div
                            className={`mt-3 flex items-center gap-1.5 text-sm font-medium ${status.type === "success" ? "text-green-600" : "text-red-600"
                                }`}
                        >
                            <span className="material-symbols-outlined text-base">
                                {status.type === "success" ? "check_circle" : "error"}
                            </span>
                            {status.message}
                        </div>
                    )}
                </div>
            </div>
        </section>
    );
}
