"use client";

import { useState, useEffect } from "react";
import { Mail, User, Clock, CheckCircle, Trash2, Loader2, MailQuestion } from "lucide-react";

export default function AdminMessagesPage() {
    const [messages, setMessages] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [actionId, setActionId] = useState<string | null>(null);

    const fetchMessages = async () => {
        try {
            const res = await fetch("/api/messages");
            const data = await res.json();
            setMessages(Array.isArray(data) ? data : []);
        } catch { }
        finally { setLoading(false); }
    };

    useEffect(() => { fetchMessages(); }, []);

    const toggleRead = async (id: string, currentRead: boolean) => {
        setActionId(id);
        try {
            await fetch(`/api/messages/${id}`, {
                method: "PUT",
                body: JSON.stringify({ read: !currentRead }),
                headers: { "Content-Type": "application/json" }
            });
            setMessages(prev => prev.map(m => m.id === id ? { ...m, read: !currentRead } : m));
        } catch { }
        finally { setActionId(null); }
    };

    const handleDelete = async (id: string) => {
        if (!confirm("Supprimer ce message ?")) return;
        setActionId(id);
        try {
            const res = await fetch(`/api/messages/${id}`, { method: "DELETE" });
            if (res.ok) fetchMessages();
        } catch { }
        finally { setActionId(null); }
    };

    return (
        <div>
            <div style={{ marginBottom: "2.5rem" }}>
                <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Messages</h1>
                <p style={{ color: "#64748b" }}>{messages.filter(m => !m.read).length} message(s) non lu(s).</p>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                {loading ? (
                    <div style={{ display: "flex", justifyContent: "center", padding: "4rem" }}><Loader2 size={32} className="animate-spin" style={{ color: "#2563eb" }} /></div>
                ) : messages.length === 0 ? (
                    <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "4rem", textAlign: "center" }}>
                        <MailQuestion size={40} style={{ color: "#cbd5e1", margin: "0 auto 1rem" }} />
                        <p style={{ fontWeight: 700, color: "#64748b" }}>Aucun message pour le moment.</p>
                    </div>
                ) : messages.map(msg => (
                    <div key={msg.id} style={{ background: "#fff", border: `1px solid ${msg.read ? "#e2e8f0" : "rgba(37,99,235,0.25)"}`, borderLeft: `4px solid ${msg.read ? "#cbd5e1" : "#2563eb"}`, borderRadius: "1rem", padding: "1.5rem", boxShadow: "0 1px 4px rgba(0,0,0,0.04)", opacity: msg.read ? 0.8 : 1 }}>
                        <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "space-between", alignItems: "flex-start", gap: "1rem", marginBottom: "1rem" }}>
                            <div>
                                <div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
                                    <p style={{ fontWeight: 900, color: "#0f172a", fontSize: "1rem" }}>{msg.name}</p>
                                    {!msg.read && <span style={{ padding: "0.2rem 0.6rem", background: "rgba(37,99,235,0.1)", color: "#2563eb", borderRadius: 50, fontSize: "0.7rem", fontWeight: 900 }}>Nouveau</span>}
                                </div>
                                <div style={{ display: "flex", flexWrap: "wrap", gap: "1rem", marginTop: "0.35rem" }}>
                                    <span style={{ display: "flex", alignItems: "center", gap: "0.4rem", color: "#64748b", fontSize: "0.82rem" }}><Mail size={13} /> {msg.email}</span>
                                    <span style={{ display: "flex", alignItems: "center", gap: "0.4rem", color: "#94a3b8", fontSize: "0.82rem" }}><Clock size={13} /> {new Date(msg.createdAt).toLocaleDateString("fr-FR", { day: "numeric", month: "long" })}</span>
                                </div>
                            </div>

                            <div style={{ display: "flex", gap: "0.5rem" }}>
                                <button onClick={() => toggleRead(msg.id, msg.read)} disabled={actionId === msg.id}
                                    style={{ padding: "0.5rem 0.75rem", background: msg.read ? "#f8fafc" : "rgba(34,197,94,0.08)", color: msg.read ? "#94a3b8" : "#16a34a", border: `1px solid ${msg.read ? "#e2e8f0" : "rgba(34,197,94,0.3)"}`, borderRadius: 8, fontSize: "0.75rem", fontWeight: 800, cursor: "pointer", display: "flex", alignItems: "center", gap: "0.4rem" }}>
                                    <CheckCircle size={14} /> {msg.read ? "Lu" : "Marquer lu"}
                                </button>
                                <button onClick={() => handleDelete(msg.id)} disabled={actionId === msg.id}
                                    style={{ width: 34, height: 34, borderRadius: 8, background: "rgba(239,68,68,0.06)", border: "1px solid rgba(239,68,68,0.15)", color: "#ef4444", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
                                    <Trash2 size={15} />
                                </button>
                            </div>
                        </div>
                        <div style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
                            <p style={{ fontWeight: 800, color: "#334155", fontSize: "0.9rem" }}>Sujet : {msg.subject}</p>
                            <p style={{ color: "#475569", lineHeight: 1.7, background: "#f8fafc", padding: "1.25rem", borderRadius: "0.75rem", fontSize: "0.92rem", whiteSpace: "pre-line" }}>{msg.message}</p>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
