"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import {
    Mail, Phone, MapPin, Send, Loader2, Facebook,
    Youtube, Linkedin, CheckCircle2, ArrowRight, Github,
    MessageSquare, ExternalLink, Music, Sparkles
} from "lucide-react";
import AntiSpamCaptcha from "@/components/AntiSpamCaptcha";

export default function ContactPage() {
    const [form, setForm] = useState({ name: "", email: "", subject: "", message: "" });
    const [profile, setProfile] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState("");
    const [captchaValid, setCaptchaValid] = useState(false);

    useEffect(() => {
        fetch("/api/profile").then(r => r.json()).then(setProfile).catch(() => { });
    }, []);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true); setError(""); setSuccess(false);
        try {
            const res = await fetch("/api/contact", {
                method: "POST",
                body: JSON.stringify(form),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                setSuccess(true);
                setForm({ name: "", email: "", subject: "", message: "" });
            } else {
                const d = await res.json();
                setError(d.error || "Une erreur est survenue.");
            }
        } catch { setError("Erreur réseau. Veuillez réessayer."); }
        finally { setLoading(false); }
    };

    const socials = [
        { icon: <Facebook size={20} />, href: profile?.facebook, label: "Facebook" },
        { icon: <Youtube size={20} />, href: profile?.youtube, label: "Youtube" },
        { icon: <Linkedin size={20} />, href: profile?.linkedin, label: "Linkedin" },
        { icon: <Github size={20} />, href: profile?.github, label: "Github" },
        { icon: <MessageSquare size={20} />, href: profile?.whatsapp ? `https://wa.me/${profile.whatsapp.replace(/[^0-9]/g, "")}` : null, label: "WhatsApp" },
        { icon: <ExternalLink size={20} />, href: profile?.freelance, label: "Freelance" },
        { icon: <Music size={20} />, href: profile?.tiktok, label: "TikTok" },
    ].filter(s => s.href);

    return (
        <main style={{ paddingTop: "10rem", paddingBottom: "10rem", background: "var(--background)" }}>
            <div className="container">
                <div style={{ maxWidth: "1100px", margin: "0 auto" }}>
                    <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} style={{ textAlign: "center", marginBottom: "6rem" }}>
                        <div className="badge badge-primary" style={{ marginBottom: "1.5rem" }}>Contactez-moi</div>
                        <h1 style={{ fontSize: "clamp(3rem, 6vw, 4.5rem)", marginBottom: "2rem" }}>
                            Démarrons une <span className="text-gradient">collaboration.</span>
                        </h1>
                        <p style={{ color: "var(--muted-foreground)", fontSize: "1.25rem", maxWidth: "40rem", margin: "0 auto", lineHeight: 1.7 }}>
                            Vous avez un projet en tête ou une question technique ? Je suis à votre écoute pour transformer vos idées en solutions concrètes.
                        </p>
                    </motion.div>

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: "4rem", alignItems: "start" }} className="contact-grid">
                        {/* Info Column */}
                        <motion.div initial={{ opacity: 0, x: -30 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.2 }} style={{ display: "flex", flexDirection: "column", gap: "2.5rem" }}>
                            <div className="card" style={{ padding: "3.5rem", background: "var(--primary)", border: "none", color: "white", position: "relative", overflow: "hidden" }}>
                                <div style={{ position: "absolute", top: "-2rem", right: "-2rem", width: "12rem", height: "12rem", background: "rgba(255,255,255,0.1)", borderRadius: "50%", filter: "blur(40px)" }} />

                                <h3 style={{ fontSize: "1.75rem", marginBottom: "3rem", position: "relative" }}>Coordonnées.</h3>

                                <div style={{ display: "flex", flexDirection: "column", gap: "2.5rem", position: "relative" }}>
                                    <div style={{ display: "flex", gap: "1.5rem" }}>
                                        <div style={{ width: 52, height: 52, background: "rgba(255,255,255,0.15)", borderRadius: "14px", display: "flex", alignItems: "center", justifyContent: "center", backdropFilter: "blur(10px)", flexShrink: 0 }}>
                                            <Mail size={24} />
                                        </div>
                                        <div>
                                            <p style={{ fontSize: "0.75rem", fontWeight: 900, textTransform: "uppercase", opacity: 0.8, letterSpacing: "0.1em", marginBottom: "0.25rem" }}>Email</p>
                                            <p style={{ fontSize: "1.15rem", fontWeight: 700, wordBreak: "break-all" }}>{profile?.email || "contact@sergio.tech"}</p>
                                        </div>
                                    </div>

                                    <div style={{ display: "flex", gap: "1.5rem" }}>
                                        <div style={{ width: 52, height: 52, background: "rgba(255,255,255,0.15)", borderRadius: "14px", display: "flex", alignItems: "center", justifyContent: "center", backdropFilter: "blur(10px)", flexShrink: 0 }}>
                                            <MapPin size={24} />
                                        </div>
                                        <div>
                                            <p style={{ fontSize: "0.75rem", fontWeight: 900, textTransform: "uppercase", opacity: 0.8, letterSpacing: "0.1em", marginBottom: "0.25rem" }}>Localisation</p>
                                            <p style={{ fontSize: "1.15rem", fontWeight: 700 }}>{profile?.address || "Cotonou, Bénin"}</p>
                                        </div>
                                    </div>
                                </div>

                                <div style={{ marginTop: "4rem", paddingTop: "2.5rem", borderTop: "1px solid rgba(255,255,255,0.2)", position: "relative" }}>
                                    <p style={{ fontSize: "0.85rem", fontWeight: 800, marginBottom: "1.5rem", opacity: 0.9 }}>SUIVEZ-MOI</p>
                                    <div style={{ display: "flex", gap: "1rem" }}>
                                        {socials.map((social, i) => (
                                            <a key={i} href={social.href!} target="_blank" rel="noopener noreferrer"
                                                style={{ width: 44, height: 44, borderRadius: "10px", background: "rgba(255,255,255,0.15)", display: "flex", alignItems: "center", justifyContent: "center", transition: "all 0.3s" }}
                                                className="contact-social-link">
                                                {social.icon}
                                            </a>
                                        ))}
                                    </div>
                                </div>
                            </div>

                            <div className="card" style={{ padding: "2rem", display: "flex", alignItems: "center", gap: "1.5rem", background: "var(--muted)" }}>
                                <div style={{ width: 48, height: 48, background: "var(--primary-light)", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                                    <Sparkles className="text-primary" size={22} />
                                </div>
                                <p style={{ fontSize: "0.95rem", fontWeight: 700, color: "var(--foreground)" }}>
                                    Réponse garantie sous <span className="text-primary">48 heures</span>.
                                </p>
                            </div>
                        </motion.div>

                        {/* Form Column */}
                        <motion.div initial={{ opacity: 0, x: 30 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.3 }}>
                            <div className="card" style={{ padding: "4rem" }}>
                                {success ? (
                                    <motion.div initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} style={{ textAlign: "center", padding: "2rem 0" }}>
                                        <div style={{ width: 80, height: 80, background: "#10b981", color: "white", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 2rem" }}>
                                            <CheckCircle2 size={40} />
                                        </div>
                                        <h3 style={{ fontSize: "2rem", marginBottom: "1rem" }}>Message Envoyé !</h3>
                                        <p style={{ color: "var(--muted-foreground)", fontSize: "1.1rem", marginBottom: "2.5rem" }}>
                                            Merci de m'avoir contacté. Je reviendrai vers vous très prochainement.
                                        </p>
                                        <button onClick={() => setSuccess(false)} className="btn btn-outline" style={{ margin: "0 auto" }}>
                                            Envoyer un autre message
                                        </button>
                                    </motion.div>
                                ) : (
                                    <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: "1.75rem" }}>
                                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.75rem" }} className="form-row">
                                            <div className="form-group">
                                                <label className="form-label">Nom complet</label>
                                                <input type="text" className="form-input" placeholder="Ex: Jean Dupont" required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
                                            </div>
                                            <div className="form-group">
                                                <label className="form-label">Email</label>
                                                <input type="email" className="form-input" placeholder="Ex: jean@email.com" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
                                            </div>
                                        </div>

                                        <div className="form-group">
                                            <label className="form-label">Sujet</label>
                                            <input type="text" className="form-input" placeholder="Ex: Nouveau projet IoT" required value={form.subject} onChange={e => setForm({ ...form, subject: e.target.value })} />
                                        </div>

                                        <div className="form-group">
                                            <label className="form-label">Votre Message</label>
                                            <textarea className="form-input" placeholder="Dites-m'en plus..." required rows={5} value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} style={{ resize: "none" }} />
                                        </div>

                                        <div style={{ padding: "1.5rem", background: "var(--muted)", borderRadius: "var(--radius-md)", border: "1px solid var(--border)" }}>
                                            <AntiSpamCaptcha onVerify={setCaptchaValid} />
                                        </div>

                                        {error && (
                                            <div style={{ padding: "1rem 1.5rem", background: "#fef2f2", color: "#b91c1c", borderRadius: "var(--radius-md)", fontSize: "0.9rem", fontWeight: 700, border: "1px solid #fee2e2" }}>
                                                {error}
                                            </div>
                                        )}

                                        <button type="submit" className="btn btn-primary" disabled={loading || !captchaValid} style={{ width: "100%", padding: "1.125rem", fontSize: "1.1rem", justifyContent: "center" }}>
                                            {loading ? (
                                                <>
                                                    <Loader2 className="animate-spin" size={22} /> ENVOI EN COURS...
                                                </>
                                            ) : (
                                                <>
                                                    ENVOYER LE MESSAGE <Send size={20} />
                                                </>
                                            )}
                                        </button>
                                    </form>
                                )}
                            </div>
                        </motion.div>
                    </div>
                </div>
            </div>

            <style>{`
                .contact-social-link:hover {
                    background: white !important;
                    color: var(--primary) !important;
                    transform: translateY(-3px);
                }
                @media (max-width: 991px) {
                    .contact-grid { grid-template-columns: 1fr !important; }
                    .form-row { grid-template-columns: 1fr !important; }
                }
                @media (max-width: 480px) {
                    .card { padding: 2.5rem 1.5rem !important; }
                }
            `}</style>
        </main>
    );
}
