"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";

const nav = [
  { href: "/dashboard", label: "Dashboard", icon: "📊" },
  { section: "Human Resources" },
  { href: "/dashboard/employees", label: "Employees", icon: "👥" },
  { href: "/dashboard/leave", label: "Leave Management", icon: "🌴" },
  { href: "/dashboard/payroll", label: "Payroll", icon: "🧮" },
  { section: "Billing" },
  { href: "/dashboard/clients", label: "Clients", icon: "🏢" },
  { href: "/dashboard/invoices", label: "Invoices", icon: "🧾" },
  { href: "/dashboard/payments", label: "Payments & M-Pesa", icon: "📱" },
] as const;

export default function AppShell({
  user,
  children,
}: {
  user: { name: string; email: string };
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);
  const [loggingOut, setLoggingOut] = useState(false);
  const pathname = usePathname();
  const router = useRouter();

  const logout = async () => {
    setLoggingOut(true);
    await fetch("/api/auth/logout", { method: "POST" });
    router.push("/login");
    router.refresh();
  };

  const sidebar = (
    <div className="flex h-full flex-col">
      <div className="flex items-center gap-3 border-b border-white/10 px-5 py-4">
        <Image src="/logo-mark.png" alt="Macsoft ERP" width={38} height={38} className="rounded-lg bg-white p-0.5" />
        <div>
          <p className="text-sm font-bold leading-tight text-white">Macsoft ERP</p>
          <p className="text-[11px] text-blue-200">Business Suite</p>
        </div>
      </div>
      <nav className="flex-1 space-y-0.5 overflow-y-auto px-3 py-4">
        {nav.map((item, i) =>
          "section" in item ? (
            <p key={i} className="px-3 pb-1 pt-4 text-[10px] font-semibold uppercase tracking-widest text-blue-300/70">
              {item.section}
            </p>
          ) : (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setOpen(false)}
              className={`flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition ${
                pathname === item.href
                  ? "bg-white/15 text-white shadow-inner"
                  : "text-blue-100/80 hover:bg-white/10 hover:text-white"
              }`}
            >
              <span className="text-base">{item.icon}</span>
              {item.label}
            </Link>
          ),
        )}
      </nav>
      <div className="border-t border-white/10 p-4">
        <div className="flex items-center gap-3">
          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-blue-500 text-sm font-bold text-white">
            {user.name.slice(0, 1)}
          </div>
          <div className="min-w-0 flex-1">
            <p className="truncate text-sm font-medium text-white">{user.name}</p>
            <p className="truncate text-[11px] text-blue-200">{user.email}</p>
          </div>
        </div>
        <button
          onClick={logout}
          disabled={loggingOut}
          className="mt-3 w-full rounded-lg bg-white/10 px-3 py-2 text-xs font-semibold text-blue-100 transition hover:bg-white/20 disabled:opacity-60"
        >
          {loggingOut ? "Signing out…" : "Sign out"}
        </button>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-slate-100">
      {/* Mobile top bar */}
      <header className="sticky top-0 z-40 flex items-center justify-between border-b border-slate-200 bg-white px-4 py-3 lg:hidden">
        <button
          onClick={() => setOpen(true)}
          className="rounded-lg border border-slate-200 p-2 text-slate-600"
          aria-label="Open menu"
        >
          <svg className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" d="M4 6h16M4 12h16M4 18h16" />
          </svg>
        </button>
        <div className="flex items-center gap-2">
          <Image src="/logo-mark.png" alt="Macsoft" width={28} height={28} className="rounded-md" />
          <span className="text-sm font-bold text-slate-900">Macsoft ERP</span>
        </div>
        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-700 text-xs font-bold text-white">
          {user.name.slice(0, 1)}
        </div>
      </header>

      {/* Mobile drawer */}
      {open && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-slate-900/60" onClick={() => setOpen(false)} />
          <aside className="absolute inset-y-0 left-0 w-72 bg-[#0b1e3f] shadow-2xl">{sidebar}</aside>
        </div>
      )}

      {/* Desktop sidebar */}
      <aside className="fixed inset-y-0 left-0 z-30 hidden w-64 bg-[#0b1e3f] lg:block">{sidebar}</aside>

      <main className="px-4 py-6 sm:px-6 lg:ml-64 lg:px-8">{children}</main>
    </div>
  );
}
