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

export const loader = async ({ params }: LoaderFunctionArgs) => {
  const shopId = params.shopId!;

  const shop = await db.shop.findUnique({
    where: { id: shopId },
    include: { rules: true },
  });

  if (!shop) {
    throw new Response("Shop not found", { status: 404 });
  }

  const rulesWithState = RULES.map((rule) => {
    const shopRule = shop.rules.find((sr) => sr.ruleKey === rule.key);
    return {
      key: rule.key,
      label: rule.label,
      category: rule.category,
      enabled: shopRule?.enabled ?? false,
      customValue: shopRule?.customValue ?? null,
    };
  });

  return json({
    shop: {
      id: shop.id,
      name: shop.name,
      isActive: shop.isActive,
      installedAt: shop.installedAt.toISOString(),
      uninstalledAt: shop.uninstalledAt?.toISOString() ?? null,
      lastSyncedAt: shop.lastSyncedAt?.toISOString() ?? null,
      createdAt: shop.createdAt.toISOString(),
      updatedAt: shop.updatedAt.toISOString(),
    },
    rules: rulesWithState,
  });
};

export const action = async ({ request, params }: ActionFunctionArgs) => {
  const shopId = params.shopId!;
  const formData = await request.formData();
  const intent = formData.get("intent") as string;

  if (intent === "toggle-active") {
    const shop = await db.shop.findUnique({ where: { id: shopId } });
    if (shop) {
      await db.shop.update({
        where: { id: shopId },
        data: { isActive: !shop.isActive },
      });
    }
  } else if (intent === "delete") {
    await db.shop.delete({ where: { id: shopId } });
    return redirect("/admin/shops");
  }

  return json({ ok: true });
};

export default function AdminShopDetail() {
  const { shop, rules } = useLoaderData<typeof loader>();

  return (
    <div>
      <div style={{ marginBottom: "1.5rem" }}>
        <Link to="/admin/shops" style={{ color: "#6b7280", textDecoration: "none", fontSize: "0.875rem" }}>
          ← Retour aux shops
        </Link>
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "1.5rem" }}>
        <h1 style={{ margin: 0, fontSize: "1.5rem" }}>{shop.id}</h1>
        <span style={{
          padding: "0.25rem 0.75rem",
          borderRadius: "9999px",
          fontSize: "0.8125rem",
          fontWeight: 500,
          background: shop.isActive ? "#dcfce7" : "#fee2e2",
          color: shop.isActive ? "#166534" : "#991b1b",
        }}>
          {shop.isActive ? "Actif" : "Inactif"}
        </span>
      </div>

      {/* Shop info */}
      <div style={{ background: "white", padding: "1.25rem", borderRadius: "8px", boxShadow: "0 1px 3px rgba(0,0,0,0.1)", marginBottom: "1.5rem" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem", fontSize: "0.875rem" }}>
          <div><strong>Installe le :</strong> {new Date(shop.installedAt).toLocaleString("fr-FR")}</div>
          <div><strong>Derniere sync :</strong> {shop.lastSyncedAt ? new Date(shop.lastSyncedAt).toLocaleString("fr-FR") : "Jamais"}</div>
          <div><strong>Cree le :</strong> {new Date(shop.createdAt).toLocaleString("fr-FR")}</div>
          <div><strong>Mis a jour :</strong> {new Date(shop.updatedAt).toLocaleString("fr-FR")}</div>
          {shop.uninstalledAt && (
            <div><strong>Desinstalle le :</strong> {new Date(shop.uninstalledAt).toLocaleString("fr-FR")}</div>
          )}
        </div>
      </div>

      {/* Actions */}
      <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1.5rem" }}>
        <Form method="post">
          <input type="hidden" name="intent" value="toggle-active" />
          <button type="submit" style={{
            padding: "0.5rem 1rem",
            border: "1px solid #d1d5db",
            borderRadius: "4px",
            background: "white",
            cursor: "pointer",
            fontSize: "0.875rem",
          }}>
            {shop.isActive ? "Desactiver" : "Reactiver"}
          </button>
        </Form>
        <Form method="post" onSubmit={(e) => { if (!confirm("Supprimer ce shop et toutes ses règles ?")) e.preventDefault(); }}>
          <input type="hidden" name="intent" value="delete" />
          <button type="submit" style={{
            padding: "0.5rem 1rem",
            border: "1px solid #dc2626",
            borderRadius: "4px",
            background: "white",
            color: "#dc2626",
            cursor: "pointer",
            fontSize: "0.875rem",
          }}>
            Supprimer
          </button>
        </Form>
      </div>

      {/* Rules */}
      <h2 style={{ fontSize: "1.125rem", margin: "0 0 1rem" }}>Règles ({rules.filter((r) => r.enabled).length} activé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" }}>Regle</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "center" }}>Statut</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "left" }}>Categorie</th>
              <th style={{ padding: "0.75rem 1rem", textAlign: "left" }}>Valeur custom</th>
            </tr>
          </thead>
          <tbody>
            {rules.map((rule) => (
              <tr key={rule.key} style={{ borderTop: "1px solid #e5e7eb" }}>
                <td style={{ padding: "0.75rem 1rem" }}>{rule.label}</td>
                <td style={{ padding: "0.75rem 1rem", textAlign: "center" }}>
                  <span style={{
                    display: "inline-block",
                    width: "8px",
                    height: "8px",
                    borderRadius: "50%",
                    background: rule.enabled ? "#16a34a" : "#d1d5db",
                  }} />
                </td>
                <td style={{ padding: "0.75rem 1rem", color: "#6b7280" }}>{rule.category}</td>
                <td style={{ padding: "0.75rem 1rem", color: "#6b7280", maxWidth: "200px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {rule.customValue ?? "—"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
