"use client";

import { useState, useEffect } from "react";
import { Mail, MapPin, Clock, Send, CheckCircle, ChevronDown, Phone } from "lucide-react";

type ContactInfo = {
  email: string;
  phone: string;
  address: string;
  registration: string;
  availability: string;
  hours: string;
};

const CONTACT_DEFAULTS: ContactInfo = {
  email: "anedong94@gmail.com",
  phone: "",
  address: "Nouakchott, Mauritanie",
  registration: "Récépissé N°086/DAPLP/SLP",
  availability: "Lundi – Vendredi",
  hours: "08h00 – 17h00 (GMT)",
};

export default function ContactPage() {
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({ name: "", email: "", subject: "", message: "" });
  const [info, setInfo] = useState<ContactInfo>(CONTACT_DEFAULTS);

  useEffect(() => {
    fetch("/api/contact-info")
      .then((r) => r.json())
      .then((data) => setInfo({ ...CONTACT_DEFAULTS, ...data }))
      .catch(console.error);
  }, []);

  function handleChange(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) {
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));
    setError(""); // Clear error on change
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError("");

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to send message");
      }

      setSent(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      {/* Page Hero - Full Contact Section */}
      <section className="relative bg-linear-to-br from-[#F7F8F5] via-white to-[#E8F5E9] min-h-screen overflow-hidden">
        {/* Background Pattern */}
        <div className="absolute inset-0 opacity-[0.03]">
          <div className="absolute inset-0" style={{
            backgroundImage: `radial-gradient(circle at 2px 2px, #4A7C59 1px, transparent 0)`,
            backgroundSize: '32px 32px'
          }}></div>
        </div>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 sm:py-20 relative z-10">
          <div className="grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-16">

            {/* Left — Header & Info */}
            <div className="lg:col-span-2 space-y-8">
              {/* Page Header */}
              <div>
                <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest mb-4">Entrer en contact</p>
                <h1 className="font-serif text-4xl sm:text-5xl lg:text-6xl font-black text-[#2C3E50] leading-tight mb-6">
                  Contact
                </h1>
                <p className="text-lg text-gray-600 leading-relaxed">
                  Partenariat, bénévolat, demande d&apos;information — nous sommes à votre écoute pour collaborer ensemble vers un avenir plus résilient.
                </p>
              </div>

              {/* Contact Info */}
              <div>
                <h2 className="font-serif text-2xl font-bold text-[#2C3E50] mb-6">Coordonnées</h2>
                <ul className="space-y-5">
                  <li className="flex items-start gap-4">
                    <div className="w-11 h-11 bg-[#4A7C59]/20 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5">
                      <Mail size={20} className="text-[#3d6849]" />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Email</p>
                      <a
                        href={`mailto:${info.email}`}
                        className="text-sm font-semibold text-[#2C3E50] hover:text-[#4A7C59] transition-colors break-all"
                      >
                        {info.email}
                      </a>
                    </div>
                  </li>

                  <li className="flex items-start gap-4">
                    <div className="w-11 h-11 bg-[#4A7C59]/20 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5">
                      <Phone size={20} className="text-[#3d6849]" />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Téléphone</p>
                      {info.phone ? (
                        <a href={`tel:${info.phone}`} className="text-sm font-semibold text-[#2C3E50] hover:text-[#4A7C59] transition-colors">
                          {info.phone}
                        </a>
                      ) : (
                        <span className="text-sm text-gray-400 italic">Non renseigné</span>
                      )}
                    </div>
                  </li>

                  <li className="flex items-start gap-4">
                    <div className="w-11 h-11 bg-[#4A7C59]/20 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5">
                      <MapPin size={20} className="text-[#3d6849]" />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Adresse</p>
                      <p className="text-sm font-semibold text-[#2C3E50]">{info.address}</p>
                      {info.registration && <p className="text-xs text-gray-500 mt-1 font-medium">{info.registration}</p>}
                    </div>
                  </li>

                  <li className="flex items-start gap-4">
                    <div className="w-11 h-11 bg-[#4A7C59]/20 rounded-xl flex items-center justify-center flex-shrink-0 mt-0.5">
                      <Clock size={20} className="text-[#3d6849]" />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Disponibilité</p>
                      <p className="text-sm font-semibold text-[#2C3E50]">{info.availability}</p>
                      {info.hours && <p className="text-xs text-gray-500 mt-1 font-medium">{info.hours}</p>}
                    </div>
                  </li>
                </ul>
              </div>

            </div>

            {/* Right — Contact Form */}
            <div className="lg:col-span-3">
              <div className="bg-white/80 backdrop-blur-sm rounded-2xl border-2 border-gray-200 p-6 shadow-lg">
                <h2 className="font-serif text-xl font-bold text-[#2C3E50] mb-4">Envoyez-nous un message</h2>
                {sent ? (
                <div className="flex flex-col items-center justify-center h-full min-h-[300px] text-center gap-3">
                  <div className="w-16 h-16 bg-[#4A7C59]/20 rounded-2xl flex items-center justify-center">
                    <CheckCircle size={32} className="text-[#4A7C59]" />
                  </div>
                  <h2 className="font-serif text-2xl font-bold text-[#2C3E50]">Message envoyé !</h2>
                  <p className="text-gray-600 max-w-md leading-relaxed font-medium text-sm">
                    Merci pour votre message. Notre équipe vous répondra dans les plus brefs délais.
                  </p>
                  <button
                    onClick={() => { setSent(false); setForm({ name: "", email: "", subject: "", message: "" }); }}
                    className="text-sm text-[#4A7C59] hover:text-[#3d6849] font-semibold mt-1 hover:underline transition-colors"
                  >
                    ← Envoyer un autre message
                  </button>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="space-y-4">
                  {error && (
                    <div className="bg-red-50 border-2 border-red-200 text-red-700 px-4 py-3 rounded-xl text-sm font-medium">
                      {error}
                    </div>
                  )}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold text-gray-700 uppercase tracking-wider mb-1.5" htmlFor="name">
                        Nom complet <span className="text-red-500">*</span>
                      </label>
                      <input
                        id="name"
                        name="name"
                        type="text"
                        required
                        value={form.name}
                        onChange={handleChange}
                        placeholder="Votre nom"
                        className="w-full border-2 border-gray-200 rounded-xl px-4 py-2.5 text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#4A7C59]/30 focus:border-[#4A7C59] transition"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-gray-700 uppercase tracking-wider mb-1.5" htmlFor="email">
                        Email <span className="text-red-500">*</span>
                      </label>
                      <input
                        id="email"
                        name="email"
                        type="email"
                        required
                        value={form.email}
                        onChange={handleChange}
                        placeholder="votre@email.com"
                        className="w-full border-2 border-gray-200 rounded-xl px-4 py-2.5 text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#4A7C59]/30 focus:border-[#4A7C59] transition"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-bold text-gray-700 uppercase tracking-wider mb-1.5" htmlFor="subject">
                      Objet <span className="text-red-500">*</span>
                    </label>
                    <div className="relative">
                      <select
                        id="subject"
                        name="subject"
                        required
                        value={form.subject}
                        onChange={handleChange}
                        className="w-full border-2 border-gray-200 rounded-xl px-4 py-2.5 pr-10 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-[#4A7C59]/30 focus:border-[#4A7C59] transition bg-white appearance-none cursor-pointer"
                      >
                        <option value="" disabled>Sélectionnez un objet</option>
                        <option value="partenariat">Partenariat / Projet</option>
                        <option value="information">Demande d&apos;information</option>
                        <option value="benevolat">Bénévolat</option>
                        <option value="presse">Presse / Communication</option>
                        <option value="autre">Autre</option>
                      </select>
                      <ChevronDown size={16} className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-bold text-gray-700 uppercase tracking-wider mb-1.5" htmlFor="message">
                      Message <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      id="message"
                      name="message"
                      required
                      rows={4}
                      value={form.message}
                      onChange={handleChange}
                      placeholder="Décrivez votre demande..."
                      className="w-full border-2 border-gray-200 rounded-xl px-4 py-2.5 text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#4A7C59]/30 focus:border-[#4A7C59] transition resize-none"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={loading}
                    className="w-full bg-[#4A7C59] hover:bg-[#3d6849] text-white py-3 rounded-xl font-bold transition-all hover:shadow-lg flex items-center justify-center gap-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {loading ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                        Envoi en cours...
                      </>
                    ) : (
                      <>
                        <Send size={16} />
                        Envoyer le message
                      </>
                    )}
                  </button>

                  <p className="text-xs text-gray-500 text-center font-medium mt-3">
                    Vos données ne seront utilisées que pour répondre à votre demande.
                  </p>
                </form>
              )}
              </div>
            </div>

          </div>
        </div>
      </section>
    </>
  );
}
