"use client";

import { useState, useEffect } from "react";
import { FileText, User, Phone, Mail, Clock, CheckCircle, Trash2, Loader2, MessageSquare, DollarSign, Briefcase } from "lucide-react";

export default function AdminQuotesPage() {
    const [quotes, setQuotes] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [actionId, setActionId] = useState<string | null>(null);

    const fetchQuotes = async () => {
        try {
            const res = await fetch("/api/quotes");
            const data = await res.json();
            setQuotes(Array.isArray(data) ? data : []);
        } catch { }
        finally { setLoading(false); }
    };

    useEffect(() => { fetchQuotes(); }, []);

    const updateStatus = async (id: string, status: string) => {
        setActionId(id);
        try {
            await fetch(`/api/quotes/${id}`, {
                method: "PUT",
                body: JSON.stringify({ status }),
                headers: { "Content-Type": "application/json" }
            });
            setQuotes(prev => prev.map(q => q.id === id ? { ...q, status } : q));
        } catch { }
        finally { setActionId(null); }
    };

    const handleDelete = async (id: string) => {
        if (!confirm("Supprimer cette demande de devis ?")) return;
        setActionId(id);
        try {
            const res = await fetch(`/api/quotes/${id}`, { method: "DELETE" });
            if (res.ok) setQuotes(prev => prev.filter(q => q.id !== id));
        } catch { }
        finally { setActionId(null); }
    };

    const statusColors: any = {
        "En attente": { bg: "rgba(245,158,11,0.1)", color: "#d97706", border: "rgba(245,158,11,0.2)" },
        "Traité": { bg: "rgba(34,197,94,0.1)", color: "#16a34a", border: "rgba(34,197,94,0.2)" },
        "Rejeté": { bg: "rgba(239,68,68,0.1)", color: "#ef4444", border: "rgba(239,68,68,0.2)" }
    };

    return (
        <div>
            <div style={{ marginBottom: "2.5rem" }}>
                <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Demandes de Devis</h1>
                <p style={{ color: "#64748b" }}>{quotes.filter(q => q.status === "En attente").length} nouvelle(s) demande(s) en attente.</p>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                {loading ? (
                    <div style={{ display: "flex", justifyContent: "center", padding: "4rem" }}><Loader2 size={32} className="animate-spin" style={{ color: "#2563eb" }} /></div>
                ) : quotes.length === 0 ? (
                    <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "4rem", textAlign: "center" }}>
                        <FileText size={40} style={{ color: "#cbd5e1", margin: "0 auto 1rem" }} />
                        <p style={{ fontWeight: 700, color: "#64748b" }}>Aucune demande de devis pour le moment.</p>
                    </div>
                ) : quotes.map(quote => (
                    <div key={quote.id} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", overflow: "hidden", boxShadow: "0 1px 3px rgba(0,0,0,0.02)" }}>
                        {/* Header */}
                        <div style={{ padding: "1.25rem 1.5rem", borderBottom: "1px solid #f1f5f9", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "1rem", background: "#f8fafc" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
                                <div style={{ padding: "0.4rem 0.8rem", borderRadius: 50, fontSize: "0.75rem", fontWeight: 900, background: statusColors[quote.status]?.bg, color: statusColors[quote.status]?.color, border: `1px solid ${statusColors[quote.status]?.border}` }}>
                                    {quote.status}
                                </div>
                                <span style={{ display: "flex", alignItems: "center", gap: "0.4rem", color: "#64748b", fontSize: "0.85rem", fontWeight: 600 }}>
                                    <Clock size={14} /> {new Date(quote.createdAt).toLocaleDateString("fr-FR", { day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit" })}
                                </span>
                            </div>
                            <div style={{ display: "flex", gap: "0.5rem" }}>
                                {quote.status !== "Traité" && <button onClick={() => updateStatus(quote.id, "Traité")} disabled={actionId === quote.id} style={{ padding: "0.5rem 1rem", background: "#16a34a", color: "#fff", border: "none", borderRadius: 8, fontSize: "0.75rem", fontWeight: 850, cursor: "pointer", display: "flex", alignItems: "center", gap: "0.4rem" }}>Marquer Traité</button>}
                                <button onClick={() => handleDelete(quote.id)} disabled={actionId === quote.id} style={{ width: 34, height: 34, borderRadius: 8, background: "rgba(239,68,68,0.06)", border: "none", color: "#ef4444", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Trash2 size={15} /></button>
                            </div>
                        </div>

                        {/* Content */}
                        <div style={{ padding: "1.5rem", display: "grid", gridTemplateColumns: "1fr 2fr", gap: "2rem" }} className="quote-grid">
                            <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
                                <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                    <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", color: "#64748b" }}><User size={16} /></div>
                                    <div>
                                        <p style={{ fontSize: "0.75rem", color: "#94a3b8", fontWeight: 700, textTransform: "uppercase" }}>Client</p>
                                        <p style={{ fontWeight: 800, color: "#0f172a" }}>{quote.firstName} {quote.lastName.toUpperCase()}</p>
                                    </div>
                                </div>
                                <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                    <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", color: "#64748b" }}><Mail size={16} /></div>
                                    <div>
                                        <p style={{ fontSize: "0.75rem", color: "#94a3b8", fontWeight: 700, textTransform: "uppercase" }}>Email</p>
                                        <p style={{ fontWeight: 700, color: "#0f172a", fontSize: "0.9rem" }}>{quote.email}</p>
                                    </div>
                                </div>
                                <div style={{ display: "flex", gap: "1rem" }}>
                                    <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                        <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", color: "#64748b" }}><Phone size={16} /></div>
                                        <div>
                                            <p style={{ fontSize: "0.75rem", color: "#94a3b8", fontWeight: 700, textTransform: "uppercase" }}>Tel</p>
                                            <p style={{ fontWeight: 700, color: "#0f172a", fontSize: "0.9rem" }}>{quote.phone}</p>
                                        </div>
                                    </div>
                                    {quote.whatsapp && (
                                        <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                            <div style={{ width: 32, height: 32, borderRadius: "50%", background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", color: "#25d366" }}><MessageSquare size={16} /></div>
                                            <div>
                                                <p style={{ fontSize: "0.75rem", color: "#94a3b8", fontWeight: 700, textTransform: "uppercase" }}>WA</p>
                                                <p style={{ fontWeight: 700, color: "#0f172a", fontSize: "0.9rem" }}>{quote.whatsapp}</p>
                                            </div>
                                        </div>
                                    )}
                                </div>
                                {quote.service && (
                                    <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                        <div style={{ width: 32, height: 32, borderRadius: "50%", background: "rgba(37,99,235,0.1)", display: "flex", alignItems: "center", justifyContent: "center", color: "#2563eb" }}><Briefcase size={16} /></div>
                                        <div>
                                            <p style={{ fontSize: "0.75rem", color: "#94a3b8", fontWeight: 700, textTransform: "uppercase" }}>Service demandé</p>
                                            <p style={{ fontWeight: 800, color: "#2563eb", fontSize: "0.9rem" }}>{quote.service.title}</p>
                                        </div>
                                    </div>
                                )}
                            </div>

                            <div style={{ background: "#f8fafc", padding: "1.5rem", borderRadius: "1rem" }}>
                                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1rem" }}>
                                    <h3 style={{ fontSize: "0.85rem", fontWeight: 900, color: "#475569", textTransform: "uppercase" }}>Détails du projet</h3>
                                    {quote.budget && (
                                        <div style={{ display: "flex", alignItems: "center", gap: "0.4rem", color: "#16a34a", fontWeight: 850, fontSize: "0.95rem" }}>
                                            <DollarSign size={16} /> Budget : {quote.budget}
                                        </div>
                                    )}
                                </div>
                                <p style={{ color: "#334155", lineHeight: 1.7, fontSize: "0.95rem", whiteSpace: "pre-line" }}>{quote.details}</p>
                            </div>
                        </div>
                    </div>
                ))}
            </div>
            <style>{`@media(max-width:900px){.quote-grid{grid-template-columns:1fr !important;}}`}</style>
        </div>
    );
}
