import type { LoaderFunctionArgs, ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { Link, Outlet, useLocation, Form } from "@remix-run/react";
import { requireAdmin, logoutAdmin } from "../lib/admin-auth.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  await requireAdmin(request);
  return null;
};

export const action = async ({ request }: ActionFunctionArgs) => {
  const cookie = await logoutAdmin(request);
  return redirect("/admin/login", {
    headers: { "Set-Cookie": cookie },
  });
};

const navItems = [
  { to: "/admin", label: "Dashboard" },
  { to: "/admin/shops", label: "Shops" },
  { to: "/admin/logs", label: "Logs" },
  { to: "/admin/config", label: "Config" },
];

export default function AdminLayout() {
  const location = useLocation();

  return (
    <div style={{ display: "flex", minHeight: "100vh", fontFamily: "system-ui, -apple-system, sans-serif" }}>
      <nav style={{ width: "220px", background: "#111", color: "white", padding: "1.5rem 0", flexShrink: 0 }}>
        <div style={{ padding: "0 1.25rem 1.5rem", borderBottom: "1px solid #333" }}>
          <h2 style={{ margin: 0, fontSize: "1.125rem" }}>CleanSerp Admin</h2>
        </div>
        <ul style={{ listStyle: "none", padding: "1rem 0", margin: 0 }}>
          {navItems.map((item) => {
            const isActive =
              item.to === "/admin"
                ? location.pathname === "/admin"
                : location.pathname.startsWith(item.to);
            return (
              <li key={item.to}>
                <Link
                  to={item.to}
                  style={{
                    display: "block",
                    padding: "0.625rem 1.25rem",
                    color: isActive ? "white" : "#9ca3af",
                    textDecoration: "none",
                    background: isActive ? "#333" : "transparent",
                    fontSize: "0.875rem",
                  }}
                >
                  {item.label}
                </Link>
              </li>
            );
          })}
        </ul>
        <div style={{ padding: "1rem 1.25rem", borderTop: "1px solid #333", marginTop: "auto" }}>
          <Form method="post">
            <button
              type="submit"
              style={{ background: "none", border: "none", color: "#9ca3af", cursor: "pointer", fontSize: "0.875rem", padding: 0 }}
            >
              Deconnexion
            </button>
          </Form>
        </div>
      </nav>
      <main style={{ flex: 1, padding: "2rem", background: "#f9fafb", overflow: "auto" }}>
        <Outlet />
      </main>
    </div>
  );
}
