import type { LoaderFunctionArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData, Link, useSearchParams } from "@remix-run/react";
import db from "../db.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const url = new URL(request.url);
  const filter = url.searchParams.get("filter") ?? "all";
  const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10));
  const perPage = 20;

  const where =
    filter === "active"
      ? { isActive: true }
      : filter === "inactive"
        ? { isActive: false }
        : {};

  const [shops, total] = await Promise.all([
    db.shop.findMany({
      where,
      orderBy: { installedAt: "desc" },
      skip: (page - 1) * perPage,
      take: perPage,
      include: { _count: { select: { rules: { where: { enabled: true } } } } },
    }),
    db.shop.count({ where }),
  ]);

  return json({
    shops: shops.map((s) => ({
      id: s.id,
      name: s.name,
      isActive: s.isActive,
      installedAt: s.installedAt.toISOString(),
      lastSyncedAt: s.lastSyncedAt?.toISOString() ?? null,
      enabledRules: s._count.rules,
    })),
    total,
    page,
    totalPages: Math.ceil(total / perPage),
    filter,
  });
};

export default function AdminShops() {
  const { shops, total, page, totalPages, filter } = useLoaderData<typeof loader>();
  const [, setSearchParams] = useSearchParams();

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1.5rem" }}>
        <h1 style={{ margin: 0, fontSize: "1.5rem" }}>Shops ({total})</h1>
        <div style={{ display: "flex", gap: "0.5rem" }}>
          {["all", "active", "inactive"].map((f) => (
            <button
              key={f}
              onClick={() => setSearchParams({ filter: f, page: "1" })}
              style={{
                padding: "0.375rem 0.75rem",
                border: "1px solid #d1d5db",
                borderRadius: "4px",
                background: filter === f ? "#111" : "white",
                color: filter === f ? "white" : "#374151",
                cursor: "pointer",
                fontSize: "0.8125rem",
              }}
            >
              {f === "all" ? "Tous" : f === "active" ? "Actifs" : "Inactifs"}
            </button>
          ))}
        </div>
      </div>

      <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" }}>Shop</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "center" }}>Statut</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Règles</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Installation</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "right" }}>Derniere sync</th>
            </tr>
          </thead>
          <tbody>
            {shops.map((shop) => (
              <tr key={shop.id} style={{ borderTop: "1px solid #e5e7eb" }}>
                <td style={{ padding: "0.75rem 1rem" }}>
                  <Link to={`/admin/shops/${encodeURIComponent(shop.id)}`} style={{ color: "#2563eb", textDecoration: "none" }}>
                    {shop.id}
                  </Link>
                </td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "center" }}>
                  <span style={{
                    display: "inline-block",
                    padding: "0.125rem 0.5rem",
                    borderRadius: "9999px",
                    fontSize: "0.75rem",
                    fontWeight: 500,
                    background: shop.isActive ? "#dcfce7" : "#fee2e2",
                    color: shop.isActive ? "#166534" : "#991b1b",
                  }}>
                    {shop.isActive ? "Actif" : "Inactif"}
                  </span>
                </td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right" }}>{shop.enabledRules}</td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right", color: "#6b7280" }}>
                  {new Date(shop.installedAt).toLocaleDateString("fr-FR")}
                </td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "right", color: "#6b7280" }}>
                  {shop.lastSyncedAt ? new Date(shop.lastSyncedAt).toLocaleString("fr-FR") : "—"}
                </td>
              </tr>
            ))}
            {shops.length === 0 && (
              <tr>
                <td colSpan={5} style={{ padding: "2rem", textAlign: "center", color: "#6b7280" }}>
                  Aucun shop trouve
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div style={{ display: "flex", justifyContent: "center", gap: "0.5rem", marginTop: "1rem" }}>
          {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
            <button
              key={p}
              onClick={() => setSearchParams({ filter, page: String(p) })}
              style={{
                padding: "0.375rem 0.625rem",
                border: "1px solid #d1d5db",
                borderRadius: "4px",
                background: page === p ? "#111" : "white",
                color: page === p ? "white" : "#374151",
                cursor: "pointer",
                fontSize: "0.8125rem",
              }}
            >
              {p}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
