"use client";

import { useState } from "react";
import { Send, Loader2, CheckCircle } from "lucide-react";
import AntiSpamCaptcha from "@/components/AntiSpamCaptcha";

export default function QuoteForm({ serviceId }: { serviceId: string }) {
    const [form, setForm] = useState({
        firstName: "", lastName: "", email: "", phone: "", whatsapp: "", budget: "", details: ""
    });
    const [loading, setLoading] = useState(false);
    const [sent, setSent] = useState(false);
    const [error, setError] = useState("");
    const [captchaValid, setCaptchaValid] = useState(false);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true); setError("");
        try {
            const res = await fetch("/api/quotes", {
                method: "POST",
                body: JSON.stringify({ ...form, serviceId }),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                setSent(true);
                setForm({ firstName: "", lastName: "", email: "", phone: "", whatsapp: "", budget: "", details: "" });
            } else {
                setError("Une erreur est survenue lors de l'envoi.");
            }
        } catch {
            setError("Erreur de connexion.");
        } finally {
            setLoading(false);
        }
    };

    if (sent) return (
        <div style={{ textAlign: "center", padding: "2rem 0" }}>
            <div style={{ width: 64, height: 64, borderRadius: "50%", background: "rgba(34,197,94,0.1)", color: "#16a34a", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 1.5rem" }}>
                <CheckCircle size={32} />
            </div>
            <h3 style={{ fontSize: "1.25rem", fontWeight: 900, marginBottom: "0.5rem" }}>Merci !</h3>
            <p style={{ color: "var(--muted-foreground)" }}>Votre demande a été envoyée avec succès. Je reviendrai vers vous très bientôt.</p>
            <button onClick={() => setSent(false)} className="btn btn-secondary" style={{ marginTop: "1.5rem" }}>Envoyer un autre message</button>
        </div>
    );

    const inputStyle = { width: "100%", padding: "0.875rem 1.1rem", border: "1.5px solid var(--border)", borderRadius: "0.75rem", background: "var(--background)", fontSize: "0.95rem", outline: "none", transition: "border-color 0.2s" };

    return (
        <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: "1.25rem" }}>
            {/* ... (existing fields) */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
                <div>
                    <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>Prénom *</label>
                    <input type="text" required value={form.firstName} onChange={e => setForm({ ...form, firstName: e.target.value })} style={inputStyle} placeholder="Jean" />
                </div>
                <div>
                    <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>Nom *</label>
                    <input type="text" required value={form.lastName} onChange={e => setForm({ ...form, lastName: e.target.value })} style={inputStyle} placeholder="Dupont" />
                </div>
            </div>

            <div>
                <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>Email *</label>
                <input type="email" required value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} style={inputStyle} placeholder="jean.dupont@email.com" />
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
                <div>
                    <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>Téléphone *</label>
                    <input type="tel" required value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} style={inputStyle} placeholder="+229 ..." />
                </div>
                <div>
                    <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>WhatsApp</label>
                    <input type="tel" value={form.whatsapp} onChange={e => setForm({ ...form, whatsapp: e.target.value })} style={inputStyle} placeholder="+229 ..." />
                </div>
            </div>

            <div>
                <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>Budget estimatif</label>
                <input type="text" value={form.budget} onChange={e => setForm({ ...form, budget: e.target.value })} style={inputStyle} placeholder="500,000 FCFA - 1,000,000 FCFA" />
            </div>

            <div>
                <label style={{ display: "block", fontSize: "0.75rem", fontWeight: 800, textTransform: "uppercase", marginBottom: "0.5rem", color: "var(--muted-foreground)" }}>Détails du projet *</label>
                <textarea required rows={5} value={form.details} onChange={e => setForm({ ...form, details: e.target.value })} style={{ ...inputStyle, resize: "vertical" }} placeholder="Décrivez votre besoin en détail..." />
            </div>

            <AntiSpamCaptcha onVerify={setCaptchaValid} />

            {error && <p style={{ color: "#ef4444", fontSize: "0.85rem", fontWeight: 700 }}>{error}</p>}

            <button type="submit" disabled={loading || !captchaValid} style={{ width: "100%", padding: "1rem", background: "var(--primary)", color: "white", border: "none", borderRadius: "1rem", fontWeight: 900, fontSize: "1rem", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: "0.75rem", boxShadow: "0 10px 25px rgba(37,99,235,0.25)" }}>
                {loading ? <Loader2 size={20} className="animate-spin" /> : <><Send size={18} /> Envoyer la demande</>}
            </button>
        </form>
    );
}
