import React from "react";
import { NavLink, Outlet, useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";

const NAV = [
  { to: "/", label: "Dashboard", exact: true },
  { to: "/catalog", label: "Catalog" },
  { to: "/users", label: "Users" },
  { to: "/vendor", label: "Vendor" },
];

export default function Layout() {
  const { user, logout } = useAuth();
  const navigate = useNavigate();

  const handleLogout = async () => {
    await logout();
    navigate("/login", { replace: true });
  };

  return (
    <div style={s.shell}>
      <aside style={s.sidebar}>
        <div style={s.brand}>POS Admin</div>
        <nav style={s.nav}>
          {NAV.map((item) => (
            <NavLink
              key={item.to}
              to={item.to}
              end={item.exact}
              style={({ isActive }) => ({
                ...s.navLink,
                ...(isActive ? s.navLinkActive : {}),
              })}
            >
              {item.label}
            </NavLink>
          ))}
        </nav>
        <div style={s.sidebarFooter}>
          <div style={s.userBlock}>
            <div style={s.userName}>{user?.name}</div>
            <div style={s.userRole}>{user?.role}</div>
          </div>
          <button type="button" style={s.logoutBtn} onClick={handleLogout}>
            Sign out
          </button>
        </div>
      </aside>
      <main style={s.main}>
        <Outlet />
      </main>
    </div>
  );
}

const s: Record<string, React.CSSProperties> = {
  shell: { display: "flex", minHeight: "100vh" },
  sidebar: {
    width: 220,
    flexShrink: 0,
    background: "#1e293b",
    color: "#cbd5e1",
    display: "flex",
    flexDirection: "column",
  },
  brand: {
    padding: "20px 20px 12px",
    fontSize: 16,
    fontWeight: 700,
    color: "#f8fafc",
    borderBottom: "1px solid #334155",
  },
  nav: {
    flex: 1,
    display: "flex",
    flexDirection: "column",
    gap: 2,
    padding: "12px 8px",
  },
  navLink: {
    display: "block",
    padding: "9px 12px",
    borderRadius: 6,
    color: "#94a3b8",
    fontSize: 14,
    fontWeight: 500,
    textDecoration: "none",
    transition: "background 0.1s",
  },
  navLinkActive: {
    background: "#334155",
    color: "#f8fafc",
  },
  sidebarFooter: {
    padding: "12px 16px",
    borderTop: "1px solid #334155",
    display: "flex",
    flexDirection: "column",
    gap: 8,
  },
  userBlock: {},
  userName: { fontSize: 13, fontWeight: 600, color: "#e2e8f0" },
  userRole: { fontSize: 12, color: "#64748b", textTransform: "capitalize" },
  logoutBtn: {
    background: "none",
    border: "1px solid #334155",
    borderRadius: 6,
    padding: "5px 10px",
    color: "#64748b",
    fontSize: 12,
    cursor: "pointer",
    alignSelf: "flex-start",
  },
  main: { flex: 1, overflow: "auto", background: "var(--color-bg)" },
};
