import prisma from "@/lib/db";
import Link from "next/link";
import { LayoutDashboard, FolderOpen, FileText, Mail, Plus, Cpu } from "lucide-react";
import DashboardCharts from "@/components/DashboardCharts";

export default async function DashboardPage() {
    let stats = { projects: 0, articles: 0, messages: 0, unread: 0, services: 0, quotes: 0, newQuotes: 0 };
    let recentMessages: any[] = [];
    let statusData: { name: string; value: number }[] = [];
    let monthlyData: { name: string; count: number }[] = [];

    try {
        const [projects, articles, messages, services, quotes, newQuotes, unread, quotesByStatus, allQuotes] = await Promise.all([
            prisma.project.count(),
            prisma.article.count(),
            prisma.message.findMany({ orderBy: { createdAt: "desc" }, take: 5 }),
            (prisma as any).service.count(),
            (prisma as any).quoteRequest.count(),
            (prisma as any).quoteRequest.count({ where: { status: "En attente" } }),
            prisma.message.count({ where: { read: false } }),
            (prisma as any).quoteRequest.groupBy({ by: ['status'], _count: { id: true } }),
            (prisma as any).quoteRequest.findMany({ select: { createdAt: true } }),
        ]);

        stats = { projects, articles, messages: await prisma.message.count(), unread, services, quotes, newQuotes };
        recentMessages = messages;
        statusData = quotesByStatus.map((g: any) => ({ name: g.status, value: g._count.id }));

        // Simple monthly grouping
        const months = ["Jan", "Fév", "Mar", "Avr", "Mai", "Juin", "Juil", "Août", "Sep", "Oct", "Nov", "Déc"];
        const counts = new Array(12).fill(0);
        allQuotes.forEach((q: any) => {
            const m = new Date(q.createdAt).getMonth();
            counts[m]++;
        });
        monthlyData = months.map((m, i) => ({ name: m, count: counts[i] }));
    } catch { }

    const cards = [
        { label: "Projets", value: stats.projects, icon: <FolderOpen size={24} />, color: "#2563eb", bg: "rgba(37,99,235,0.1)", href: "/admin/projects" },
        { label: "Services", value: stats.services, icon: <Cpu size={24} />, color: "#7c3aed", bg: "rgba(124,58,237,0.1)", href: "/admin/services" },
        { label: "Articles", value: stats.articles, icon: <FileText size={24} />, color: "#16a34a", bg: "rgba(34,197,94,0.1)", href: "/admin/articles" },
        { label: "Messages", value: stats.unread, icon: <Mail size={24} />, color: "#d97706", bg: "rgba(245,158,11,0.1)", href: "/admin/messages" },
        { label: "Devis Attente", value: stats.newQuotes, icon: <FileText size={24} />, color: "#dc2626", bg: "rgba(239,68,68,0.1)", href: "/admin/quotes" },
    ];

    return (
        <div>
            <div style={{ marginBottom: "2.5rem" }}>
                <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a", marginBottom: "0.4rem" }}>Dashboard</h1>
                <p style={{ color: "#64748b" }}>Bienvenue dans votre espace d'administration.</p>
            </div>

            {/* Stats */}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: "1.5rem", marginBottom: "3rem" }}>
                {cards.map((card, i) => (
                    <Link key={i} href={card.href}
                        style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "1.5rem", display: "flex", flexDirection: "column", gap: "1rem", textDecoration: "none", transition: "all 0.2s", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" }}>
                        <div style={{ width: 48, height: 48, background: card.bg, borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", color: card.color }}>{card.icon}</div>
                        <div>
                            <p style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a", lineHeight: 1 }}>{card.value}</p>
                            <p style={{ fontSize: "0.85rem", fontWeight: 700, color: "#64748b", marginTop: "0.25rem" }}>{card.label}</p>
                        </div>
                    </Link>
                ))}
            </div>

            <div style={{ marginBottom: "3rem" }}>
                <DashboardCharts statusData={statusData} monthlyData={monthlyData} />
            </div>

            {/* Quick Actions */}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: "1.5rem", marginBottom: "3rem" }}>
                {[
                    { label: "Nouveau Projet", href: "/admin/projects/new", color: "#2563eb" },
                    { label: "Nouvel Article", href: "/admin/articles/new", color: "#16a34a" },
                ].map((action, i) => (
                    <Link key={i} href={action.href}
                        style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "1rem 1.5rem", background: action.color, color: "#fff", borderRadius: "1rem", fontWeight: 800, fontSize: "0.95rem", textDecoration: "none", transition: "opacity 0.2s" }}>
                        <Plus size={20} /> {action.label}
                    </Link>
                ))}
            </div>

            {/* Recent Messages */}
            <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "1.75rem", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1.5rem" }}>
                    <h2 style={{ fontFamily: "Outfit", fontSize: "1.25rem", fontWeight: 900, color: "#0f172a" }}>Messages Récents</h2>
                    <Link href="/admin/messages" style={{ color: "#2563eb", fontWeight: 700, fontSize: "0.875rem" }}>Voir tout</Link>
                </div>
                {recentMessages.length === 0 ? (
                    <p style={{ color: "#94a3b8", textAlign: "center", padding: "2rem" }}>Aucun message pour le moment.</p>
                ) : (
                    <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
                        {recentMessages.map(msg => (
                            <div key={msg.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "1rem 1.25rem", background: msg.read ? "#f8fafc" : "rgba(37,99,235,0.04)", border: `1px solid ${msg.read ? "#e2e8f0" : "rgba(37,99,235,0.15)"}`, borderRadius: "0.875rem" }}>
                                <div>
                                    <p style={{ fontWeight: 800, color: "#0f172a", marginBottom: "0.2rem" }}>{msg.name}</p>
                                    <p style={{ fontSize: "0.85rem", color: "#64748b", fontWeight: 600 }}>{msg.subject}</p>
                                </div>
                                <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                    {!msg.read && <span style={{ width: 8, height: 8, background: "#2563eb", borderRadius: "50%" }} />}
                                    <span style={{ fontSize: "0.78rem", color: "#94a3b8", fontWeight: 600 }}>{new Date(msg.createdAt).toLocaleDateString("fr-FR")}</span>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
