import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import db from "../db.server";
import { RULES, RULE_CATEGORIES } from "../lib/rules";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const [totalShops, activeShops, inactiveShops, totalEnabledRules, lastInstall, lastSync, recentErrors] =
    await Promise.all([
      db.shop.count(),
      db.shop.count({ where: { isActive: true } }),
      db.shop.count({ where: { isActive: false } }),
      db.shopRule.count({ where: { enabled: true } }),
      db.shop.findFirst({ orderBy: { installedAt: "desc" } }),
      db.shop.findFirst({ orderBy: { lastSyncedAt: "desc" }, where: { lastSyncedAt: { not: null } } }),
      db.adminLog.count({ where: { level: "error", createdAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } } }),
    ]);

  // Rule distribution per category
  const ruleDistribution: { category: string; total: number; enabled: number }[] = [];
  for (const cat of RULE_CATEGORIES) {
    const categoryRules = RULES.filter((r) => r.category === cat.key);
    const keys = categoryRules.map((r) => r.key);
    const enabledCount = await db.shopRule.count({
      where: { ruleKey: { in: keys }, enabled: true },
    });
    ruleDistribution.push({
      category: cat.label,
      total: categoryRules.length * (totalShops || 1),
      enabled: enabledCount,
    });
  }

  // Top rules — most activated across all shops
  const ruleUsage: { key: string; label: string; count: number; percentage: number }[] = [];
  for (const rule of RULES) {
    const count = await db.shopRule.count({
      where: { ruleKey: rule.key, enabled: true },
    });
    ruleUsage.push({
      key: rule.key,
      label: rule.label,
      count,
      percentage: totalShops > 0 ? Math.round((count / totalShops) * 100) : 0,
    });
  }
  ruleUsage.sort((a, b) => b.count - a.count);

  return json({
    totalShops,
    activeShops,
    inactiveShops,
    totalEnabledRules,
    lastInstall: lastInstall?.installedAt.toISOString() ?? null,
    lastSync: lastSync?.lastSyncedAt?.toISOString() ?? null,
    recentErrors,
    ruleDistribution,
    ruleUsage,
  });
};

function StatCard({ label, value, tone }: { label: string; value: string | number; tone?: string }) {
  const color = tone === "success" ? "#16a34a" : tone === "critical" ? "#dc2626" : "#111";
  return (
    <div style={{ background: "white", padding: "1.25rem", borderRadius: "8px", boxShadow: "0 1px 3px rgba(0,0,0,0.1)" }}>
      <div style={{ fontSize: "0.75rem", color: "#6b7280", textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</div>
      <div style={{ fontSize: "1.75rem", fontWeight: 700, color, marginTop: "0.25rem" }}>{value}</div>
    </div>
  );
}

export default function AdminDashboard() {
  const data = useLoaderData<typeof loader>();

  return (
    <div>
      <h1 style={{ margin: "0 0 1.5rem", fontSize: "1.5rem" }}>Dashboard</h1>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: "1rem", marginBottom: "2rem" }}>
        <StatCard label="Total shops" value={data.totalShops} />
        <StatCard label="Actifs" value={data.activeShops} tone="success" />
        <StatCard label="Inactifs" value={data.inactiveShops} />
        <StatCard label="Règles activées" value={data.totalEnabledRules} />
        <StatCard label="Erreurs (24h)" value={data.recentErrors} tone={data.recentErrors > 0 ? "critical" : undefined} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem", marginBottom: "2rem" }}>
        <div style={{ background: "white", padding: "1.25rem", borderRadius: "8px", boxShadow: "0 1px 3px rgba(0,0,0,0.1)" }}>
          <div style={{ fontSize: "0.75rem", color: "#6b7280", textTransform: "uppercase" }}>Derniere installation</div>
          <div style={{ marginTop: "0.25rem" }}>
            {data.lastInstall ? new Date(data.lastInstall).toLocaleString("fr-FR") : "Aucune"}
          </div>
        </div>
        <div style={{ background: "white", padding: "1.25rem", borderRadius: "8px", boxShadow: "0 1px 3px rgba(0,0,0,0.1)" }}>
          <div style={{ fontSize: "0.75rem", color: "#6b7280", textTransform: "uppercase" }}>Derniere synchronisation</div>
          <div style={{ marginTop: "0.25rem" }}>
            {data.lastSync ? new Date(data.lastSync).toLocaleString("fr-FR") : "Aucune"}
          </div>
        </div>
      </div>

      <h2 style={{ fontSize: "1.125rem", margin: "0 0 1rem" }}>Distribution des règles</h2>
      <div style={{ background: "white", borderRadius: "8px", boxShadow: "0 1px 3px rgba(0,0,0,0.1)", overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.875rem" }}>
          <thead>
            <tr style={{ background: "#f9fafb" }}>
              <th style={{ padding: "0.75rem 1rem", textAlign: "left" }}>Categorie</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Activees</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Total possible</th>
            </tr>
          </thead>
          <tbody>
            {data.ruleDistribution.map((d) => (
              <tr key={d.category} style={{ borderTop: "1px solid #e5e7eb" }}>
                <td style={{ padding: "0.75rem 1rem" }}>{d.category}</td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right" }}>{d.enabled}</td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right" }}>{d.total}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <h2 style={{ fontSize: "1.125rem", margin: "2rem 0 1rem" }}>Règles les plus utilisées</h2>
      <div style={{ background: "white", borderRadius: "8px", boxShadow: "0 1px 3px rgba(0,0,0,0.1)", overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "0.875rem" }}>
          <thead>
            <tr style={{ background: "#f9fafb" }}>
              <th style={{ padding: "0.75rem 1rem", textAlign: "left" }}>Règle</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Shops</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Adoption</th>
            </tr>
          </thead>
          <tbody>
            {data.ruleUsage.map((r) => (
              <tr key={r.key} style={{ borderTop: "1px solid #e5e7eb" }}>
                <td style={{ padding: "0.75rem 1rem" }}>{r.label}</td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right" }}>{r.count}</td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right" }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: "0.5rem" }}>
                    <div style={{ width: "60px", height: "6px", background: "#e5e7eb", borderRadius: "3px", overflow: "hidden" }}>
                      <div style={{ width: `${r.percentage}%`, height: "100%", background: r.percentage > 50 ? "#16a34a" : r.percentage > 0 ? "#2c6ecb" : "#e5e7eb", borderRadius: "3px" }} />
                    </div>
                    <span style={{ minWidth: "2.5rem", textAlign: "right" }}>{r.percentage}%</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
