"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  LayoutDashboard, Package, Percent, ShoppingCart, FileText, Users, BarChart3,
  Image as ImageIcon, Newspaper, Type, Wrench, LogOut, Menu as MenuIcon, X, Home, Phone,
} from "lucide-react";
import { toast } from "sonner";

export const ADMIN_NAV = [
  { href: "/admin", label: "داشبورد", icon: LayoutDashboard },
  { href: "/admin/orders", label: "سفارشات", icon: ShoppingCart },
  { href: "/admin/invoices", label: "فاکتورها", icon: FileText },
  { href: "/admin/products", label: "محصولات", icon: Package },
  { href: "/admin/discounts", label: "تخفیفات", icon: Percent },
  { href: "/admin/analytics", label: "تحلیل فروش", icon: BarChart3 },
  { href: "/admin/customers", label: "مشتریان", icon: Users },
  { href: "/admin/banners", label: "بنرها", icon: ImageIcon },
  { href: "/admin/articles", label: "مقالات", icon: Newspaper },
  { href: "/admin/content", label: "متن‌های سایت", icon: Type },
  { href: "/admin/repairs", label: "تعمیرات", icon: Wrench },
];

export default function AdminShell({
  children,
  user,
}: {
  children: React.ReactNode;
  user: { name?: string | null; phone: string };
}) {
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState(false);

  const logout = async () => {
    await fetch("/api/auth/logout", { method: "POST" });
    try {
      localStorage.removeItem("kh_token");
    } catch {}
    toast.success("از پنل خارج شدید");
    router.push("/");
  };

  const isActive = (href: string) => (href === "/admin" ? pathname === "/admin" : pathname.startsWith(href));

  return (
    <div className="min-h-screen bg-[#f1f5f9] text-slate-900 flex" dir="rtl">
      {/* سایدبار */}
      <aside
        className={`fixed lg:sticky top-0 h-screen w-64 shrink-0 bg-[#0f172a] text-white flex flex-col z-50 transition-transform duration-300 ${
          open ? "translate-x-0" : "translate-x-full lg:translate-x-0"
        }`}
      >
        <div className="px-5 py-5 border-b border-white/10 flex items-center justify-between">
          <div>
            <p className="font-black text-lg">پنل مدیریت</p>
            <p className="text-[10px] text-white/50 tracking-widest mt-0.5">MIK ADMIN</p>
          </div>
          <button onClick={() => setOpen(false)} className="lg:hidden p-1.5 rounded-lg bg-white/10" aria-label="بستن منو">
            <X className="h-4 w-4" />
          </button>
        </div>

        <nav className="flex-1 overflow-y-auto px-3 py-4 space-y-1" aria-label="منوی مدیریت">
          {ADMIN_NAV.map((item) => {
            const Icon = item.icon;
            const active = isActive(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                onClick={() => setOpen(false)}
                className={`flex items-center gap-3 rounded-xl px-3.5 py-2.5 text-sm font-bold transition-all ${
                  active
                    ? "bg-emerald-600 text-white shadow-[0_4px_14px_rgba(16,185,129,0.35)]"
                    : "text-slate-300 hover:bg-white/8 hover:text-white"
                }`}
              >
                <Icon className="h-4.5 w-4.5 shrink-0" />
                {item.label}
              </Link>
            );
          })}
        </nav>

        <div className="px-3 pb-4 space-y-1.5 border-t border-white/10 pt-4">
          <div className="px-3 py-2 rounded-xl bg-white/5 mb-2">
            <p className="text-xs font-bold">{user.name || "مدیر سیستم"}</p>
            <p dir="ltr" className="text-[11px] text-slate-400 text-right">{user.phone}</p>
          </div>
          <Link href="/" className="flex items-center gap-3 rounded-xl px-3.5 py-2.5 text-sm font-bold text-slate-300 hover:bg-white/8 hover:text-white transition-colors">
            <Home className="h-4.5 w-4.5" /> نمایش سایت
          </Link>
          <button
            onClick={logout}
            className="w-full flex items-center gap-3 rounded-xl px-3.5 py-2.5 text-sm font-bold text-rose-300 hover:bg-rose-500/15 transition-colors"
          >
            <LogOut className="h-4.5 w-4.5" /> خروج از حساب
          </button>
        </div>
      </aside>

      {/* پس‌زمینه موبایل */}
      {open && <div className="fixed inset-0 bg-black/50 z-40 lg:hidden" onClick={() => setOpen(false)} />}

      {/* محتوا */}
      <div className="flex-1 min-w-0 flex flex-col">
        <header className="sticky top-0 z-30 bg-white/85 backdrop-blur border-b border-slate-200 h-14 flex items-center justify-between px-4 sm:px-6 print:hidden">
          <div className="flex items-center gap-3">
            <button onClick={() => setOpen(true)} className="lg:hidden p-2 rounded-lg bg-slate-100 hover:bg-slate-200" aria-label="باز کردن منوی مدیریت">
              <MenuIcon className="h-5 w-5" />
            </button>
            <h1 className="font-black text-slate-800 text-sm sm:text-base">
              {ADMIN_NAV.find((n) => isActive(n.href))?.label || "پنل مدیریت"}
            </h1>
          </div>
          <div className="flex items-center gap-3">
            <a href="tel:02191009100" className="hidden sm:flex items-center gap-1.5 text-xs font-bold text-slate-500 hover:text-emerald-700 transition-colors">
              <Phone className="h-3.5 w-3.5" /> <span dir="ltr">021-91009100</span>
            </a>
            <span className="flex items-center gap-2 rounded-full bg-emerald-50 border border-emerald-200 px-3 py-1.5 text-[11px] font-black text-emerald-700">
              <span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
              دسترسی مدیر
            </span>
          </div>
        </header>

        <main className="flex-1 p-4 sm:p-6">{children}</main>
      </div>
    </div>
  );
}
