'use client';

import { useEffect, useRef, useState } from "react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import {
  Mail,
  Phone,
  MapPin,
  MessageCircleMore,
  Loader2,
} from "lucide-react";

gsap.registerPlugin(ScrollTrigger);

export default function ContactPage() {
  const sectionRef = useRef(null);
  const formRef = useRef(null);

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    message: "",
  });

  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [successMessage, setSuccessMessage] = useState("");

  useEffect(() => {
    gsap.fromTo(
      sectionRef.current,
      { opacity: 0, y: 60 },
      {
        opacity: 1,
        y: 0,
        duration: 1,
        ease: "power3.out",
        scrollTrigger: {
          trigger: sectionRef.current,
          start: "top 85%",
        },
      }
    );
  }, []);

  const validate = () => {
    const newErrors = {};
    if (!formData.name.trim()) newErrors.name = "Name is required.";
    if (!formData.email.trim()) {
      newErrors.email = "Email is required.";
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = "Email is invalid.";
    }
    if (!formData.message.trim()) newErrors.message = "Message is required.";
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
    setErrors({ ...errors, [e.target.name]: "" });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSuccessMessage("");

    if (!validate()) return;

    setLoading(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        setSuccessMessage("Message sent successfully!");
        setFormData({ name: "", email: "", message: "" });
      } else {
        setErrors({ form: "Failed to send message. Please try again." });
      }
    } catch (error) {
      console.error("Error sending message:", error);
      setErrors({ form: "Something went wrong. Please try again later." });
    } finally {
      setLoading(false);
    }
  };

  const whatsappButton = (number) => (
    <a
      href={`https://wa.me/${number}`}
      target="_blank"
      rel="noopener noreferrer"
      className="inline-flex items-center gap-1 mt-1 text-white bg-green-600 hover:bg-green-700 text-xs px-3 py-1 rounded-md transition"
    >
      <MessageCircleMore className="w-4 h-4" />
      WhatsApp
    </a>
  );

  return (
    <section
      ref={sectionRef}
      className="bg-white py-20 px-6 text-center overflow-hidden"
    >
      <h2 className="text-3xl md:text-4xl font-bold text-blue-900">
        Contact Support
      </h2>
      <p className="mt-3 text-gray-700 text-lg max-w-2xl mx-auto">
        Need help or have a question? Reach out and we’ll respond as soon as possible.
      </p>

      <div className="mt-12 grid md:grid-cols-2 gap-12 max-w-5xl mx-auto text-left">
        {/* Contact Details */}
        <div className="space-y-6">
          <div className="flex items-start gap-4">
            <Mail className="text-blue-800 w-6 h-6 mt-1" />
            <div>
              <h4 className="font-semibold text-blue-800">Email</h4>
              <p className="text-gray-600">contact@medbridgeafrik.com</p>
              <a
                href="mailto:contact@medbridgeafrik.com"
                target="_blank"
                rel="noopener noreferrer"
                className="inline-block text-white bg-green-600 hover:bg-green-700 text-xs px-3 py-1 rounded-md mt-1 transition"
              >
                Mail Us Today
              </a>
            </div>
          </div>

          {[["2349157729328", "+234 915 772 9328"], ["447415834130", "+44 7415 834130"], ["254711314358", "+254 711 314358"]].map(
            ([number, label]) => (
              <div key={number} className="flex items-start gap-4">
                <Phone className="text-blue-800 w-6 h-6 mt-1" />
                <div>
                  <h4 className="font-semibold text-blue-800">Phone</h4>
                  <p className="text-gray-600">{label}</p>
                  {whatsappButton(number)}
                </div>
              </div>
            )
          )}

          <div className="flex items-start gap-4">
            <MapPin className="text-blue-800 w-6 h-6 mt-1" />
            <div>
              <h4 className="font-semibold text-blue-800">Location</h4>
              <p className="text-gray-600">Lagos, Nigeria</p>
            </div>
          </div>
        </div>

        {/* Contact Form */}
        <form
          ref={formRef}
          onSubmit={handleSubmit}
          className="text-black bg-blue-50 p-8 rounded-2xl shadow-lg border border-blue-100 space-y-6"
        >
          {errors.form && (
            <p className="text-red-600 font-medium">{errors.form}</p>
          )}
          {successMessage && (
            <p className="text-green-600 font-medium">{successMessage}</p>
          )}

          <div>
            <label className="block text-sm font-medium text-blue-900 mb-1">
              Name
            </label>
            <input
              name="name"
              value={formData.name}
              onChange={handleChange}
              className={`w-full p-3 rounded-md border ${
                errors.name ? "border-red-400" : "border-blue-200"
              } focus:ring-2 focus:ring-blue-400`}
              type="text"
              placeholder="Your Name"
            />
            {errors.name && (
              <p className="text-red-500 text-sm mt-1">{errors.name}</p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-blue-900 mb-1">
              Email
            </label>
            <input
              name="email"
              value={formData.email}
              onChange={handleChange}
              className={`w-full p-3 rounded-md border ${
                errors.email ? "border-red-400" : "border-blue-200"
              } focus:ring-2 focus:ring-blue-400`}
              type="email"
              placeholder="you@example.com"
            />
            {errors.email && (
              <p className="text-red-500 text-sm mt-1">{errors.email}</p>
            )}
          </div>

          <div>
            <label className="block text-sm font-medium text-blue-900 mb-1">
              Message
            </label>
            <textarea
              name="message"
              value={formData.message}
              onChange={handleChange}
              className={`w-full p-3 rounded-md border ${
                errors.message ? "border-red-400" : "border-blue-200"
              } focus:ring-2 focus:ring-blue-400`}
              rows="5"
              placeholder="Type your message here..."
            ></textarea>
            {errors.message && (
              <p className="text-red-500 text-sm mt-1">{errors.message}</p>
            )}
          </div>

          <button
            type="submit"
            disabled={loading}
            className={`w-full flex items-center justify-center gap-2 bg-blue-800 text-white font-semibold py-3 px-6 rounded-lg hover:bg-blue-900 transition duration-300 ${
              loading ? "opacity-70 cursor-not-allowed" : ""
            }`}
          >
            {loading && <Loader2 className="w-5 h-5 animate-spin" />}
            {loading ? "Sending..." : "Send Message"}
          </button>
        </form>
      </div>
    </section>
  );
}
