"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import {
  LayoutDashboard, Building2, Users, CreditCard,
  Wrench, FileText, Receipt, Settings, LogOut,
  X, Menu, ChevronRight, Zap, Sparkles, Bot, BarChart3, Hammer, ClipboardList,
  PanelLeftClose, PanelLeftOpen, CalendarDays, Activity, Brain, Bell, Palette, KeyRound, Plug, Webhook, ShieldCheck,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { Logo, LogoMark } from "@/components/shared/logo"
import { signOut } from "@/app/actions/auth"
import type { Profile } from "@/types"
import { initials } from "@/lib/utils"

const navItems = [
  { label: "Dashboard",    href: "/dashboard",   icon: LayoutDashboard, section: "main" },
  { label: "Properties",   href: "/properties",  icon: Building2,       section: "main" },
  { label: "Tenants",      href: "/tenants",     icon: Users,           section: "main" },
  { label: "Rent Tracker", href: "/rent",        icon: CreditCard,      section: "main" },
  { label: "Maintenance",  href: "/maintenance", icon: Wrench,          section: "main" },
  { label: "Leases",       href: "/leases",      icon: FileText,        section: "main" },
  { label: "Expenses",     href: "/expenses",    icon: Receipt,         section: "main" },
  { label: "AI Dashboard", href: "/ai-dashboard", icon: Brain,           section: "main" },
  { label: "AI Assistant", href: "/ai",          icon: Bot,             section: "main" },
  { label: "Reports",      href: "/reports",     icon: BarChart3,       section: "main" },
  { label: "Vendors",      href: "/vendors",     icon: Hammer,          section: "main" },
  { label: "Inspections",  href: "/inspections", icon: ClipboardList,   section: "main" },
  { label: "Calendar",     href: "/calendar",    icon: CalendarDays,    section: "main" },
  { label: "Activity",     href: "/activity",       icon: Activity,   section: "main" },
  { label: "AI Insights",  href: "/recommendations", icon: Zap,        section: "main" },
  { label: "AI Impact",    href: "/impact",          icon: Sparkles,   section: "main" },
  { label: "Predictions",  href: "/predictions",     icon: BarChart3,  section: "main" },
  { label: "Follow-ups",   href: "/follow-ups",      icon: Bell,       section: "main" },
]

const planConfig: Record<string, { label: string; color: string; bg: string; border: string }> = {
  starter:  { label: "Starter",  color: "text-white/50",   bg: "bg-white/5",         border: "border-white/10" },
  pro:      { label: "Pro",      color: "text-indigo-300",  bg: "bg-indigo-500/10",   border: "border-indigo-500/20" },
  landlord: { label: "Landlord", color: "text-violet-300",  bg: "bg-violet-500/10",   border: "border-violet-500/20" },
  lifetime: { label: "Lifetime", color: "text-amber-300",   bg: "bg-amber-500/10",    border: "border-amber-500/20" },
}

interface SidebarProps { profile: Profile | null; isAdmin?: boolean }

function NavContent({
  profile,
  collapsed,
  onClose,
  isAdmin,
}: {
  profile: Profile | null
  collapsed?: boolean
  onClose?: () => void
  isAdmin?: boolean
}) {
  const pathname = usePathname()

  function isActive(href: string) {
    if (href === "/dashboard") return pathname === "/dashboard"
    return pathname.startsWith(href)
  }

  const plan = profile?.plan ?? "starter"
  const pc = planConfig[plan] ?? planConfig.starter

  return (
    <div className="flex h-full flex-col">
      {/* Logo */}
      <div className={cn(
        "flex h-16 shrink-0 items-center border-b border-white/[0.06]",
        collapsed ? "justify-center px-2" : "justify-between px-4"
      )}>
        {!collapsed && <Logo />}
        {collapsed && <LogoMark size="md" />}
        {onClose && (
          <button onClick={onClose} className="rounded-lg p-1.5 text-white/40 hover:text-white transition md:hidden">
            <X className="h-5 w-5" />
          </button>
        )}
      </div>

      {/* Nav */}
      <nav className={cn("flex flex-1 flex-col gap-0.5 overflow-y-auto py-3", collapsed ? "px-2" : "px-3")}>
        {!collapsed && (
          <p className="mb-1 px-2 text-[10px] font-semibold uppercase tracking-widest text-white/20">Navigation</p>
        )}

        {navItems.map((item) => {
          const Icon = item.icon
          const active = isActive(item.href)
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={onClose}
              title={collapsed ? item.label : undefined}
              className={cn(
                "group relative flex items-center rounded-xl transition-all duration-200",
                collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
                active
                  ? "bg-indigo-600/15 text-indigo-300"
                  : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
              )}
            >
              {active && !collapsed && (
                <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
              )}
              {active && collapsed && (
                <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
              )}
              <Icon className={cn(
                "h-4 w-4 shrink-0 transition-colors",
                active ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
              )} />
              {!collapsed && (
                <>
                  <span className="flex-1">{item.label}</span>
                  {active && <ChevronRight className="h-3 w-3 text-indigo-400/60 shrink-0" />}
                </>
              )}
            </Link>
          )
        })}

        <div className="my-3 border-t border-white/[0.06]" />
        {!collapsed && (
          <p className="mb-1 px-2 text-[10px] font-semibold uppercase tracking-widest text-white/20">Account</p>
        )}

        <Link
          href="/settings/profile"
          onClick={onClose}
          title={collapsed ? "Settings" : undefined}
          className={cn(
            "group relative flex items-center rounded-xl transition-all duration-200",
            collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
            pathname.startsWith("/settings") && !pathname.includes("/demo")
              ? "bg-indigo-600/15 text-indigo-300"
              : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
          )}
        >
          {pathname.startsWith("/settings") && !pathname.includes("/demo") && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
          )}
          <Settings className={cn(
            "h-4 w-4 shrink-0 transition-colors",
            pathname.startsWith("/settings") && !pathname.includes("/demo") ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
          )} />
          {!collapsed && "Settings"}
        </Link>

        {/* Demo Data is an admin-only testing tool (seed sample data + plan
            switcher). Hidden from regular users; access is also enforced
            server-side in the page and actions. */}
        {isAdmin && (
          <Link
            href="/settings/demo"
            onClick={onClose}
            title={collapsed ? "Demo Data" : undefined}
            className={cn(
              "group relative flex items-center rounded-xl transition-all duration-200",
              collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
              pathname === "/settings/demo"
                ? "bg-indigo-600/15 text-indigo-300"
                : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
            )}
          >
            {pathname === "/settings/demo" && (
              <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
            )}
            <Sparkles className={cn(
              "h-4 w-4 shrink-0 transition-colors",
              pathname === "/settings/demo" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
            )} />
            {!collapsed && "Demo Data"}
          </Link>
        )}

        <Link
          href="/settings/api-keys"
          onClick={onClose}
          title={collapsed ? "API keys" : undefined}
          className={cn(
            "group relative flex items-center rounded-xl transition-all duration-200",
            collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
            pathname === "/settings/api-keys"
              ? "bg-indigo-600/15 text-indigo-300"
              : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
          )}
        >
          {pathname === "/settings/api-keys" && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
          )}
          <KeyRound className={cn(
            "h-4 w-4 shrink-0 transition-colors",
            pathname === "/settings/api-keys" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
          )} />
          {!collapsed && "API keys"}
        </Link>

        <Link
          href="/settings/integrations"
          onClick={onClose}
          title={collapsed ? "Integrations" : undefined}
          className={cn(
            "group relative flex items-center rounded-xl transition-all duration-200",
            collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
            pathname === "/settings/integrations"
              ? "bg-indigo-600/15 text-indigo-300"
              : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
          )}
        >
          {pathname === "/settings/integrations" && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
          )}
          <Plug className={cn(
            "h-4 w-4 shrink-0 transition-colors",
            pathname === "/settings/integrations" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
          )} />
          {!collapsed && "Integrations"}
        </Link>

        <Link
          href="/settings/webhooks"
          onClick={onClose}
          title={collapsed ? "Webhooks" : undefined}
          className={cn(
            "group relative flex items-center rounded-xl transition-all duration-200",
            collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
            pathname === "/settings/webhooks"
              ? "bg-indigo-600/15 text-indigo-300"
              : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
          )}
        >
          {pathname === "/settings/webhooks" && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
          )}
          <Webhook className={cn(
            "h-4 w-4 shrink-0 transition-colors",
            pathname === "/settings/webhooks" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
          )} />
          {!collapsed && "Webhooks"}
        </Link>

        <Link
          href="/settings/privacy"
          onClick={onClose}
          title={collapsed ? "Privacy & Data" : undefined}
          className={cn(
            "group relative flex items-center rounded-xl transition-all duration-200",
            collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
            pathname === "/settings/privacy"
              ? "bg-indigo-600/15 text-indigo-300"
              : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
          )}
        >
          {pathname === "/settings/privacy" && (
            <div className="absolute left-0 top-1/2 -translate-y-1/2 w-[3px] h-5 rounded-r-full bg-indigo-500" />
          )}
          <ShieldCheck className={cn(
            "h-4 w-4 shrink-0 transition-colors",
            pathname === "/settings/privacy" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
          )} />
          {!collapsed && "Privacy & Data"}
        </Link>

        {(plan === "landlord" || plan === "lifetime") && (
          <>
            <Link
              href="/settings/branding"
              onClick={onClose}
              title={collapsed ? "Branding" : undefined}
              className={cn(
                "group relative flex items-center rounded-xl transition-all duration-200",
                collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
                pathname === "/settings/branding"
                  ? "bg-indigo-600/15 text-indigo-300"
                  : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
              )}
            >
              <Palette className={cn(
                "h-4 w-4 shrink-0 transition-colors",
                pathname === "/settings/branding" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
              )} />
              {!collapsed && "Branding"}
            </Link>

            <Link
              href="/settings/team"
              onClick={onClose}
              title={collapsed ? "Team" : undefined}
              className={cn(
                "group relative flex items-center rounded-xl transition-all duration-200",
                collapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2.5",
                pathname === "/settings/team"
                  ? "bg-indigo-600/15 text-indigo-300"
                  : "text-white/50 hover:bg-white/[0.05] hover:text-white/90"
              )}
            >
              <Users className={cn(
                "h-4 w-4 shrink-0 transition-colors",
                pathname === "/settings/team" ? "text-indigo-400" : "text-white/30 group-hover:text-white/60"
              )} />
              {!collapsed && "Team"}
            </Link>
          </>
        )}
      </nav>

      {/* Bottom — plan + user */}
      {!collapsed && (
        <div className="shrink-0 border-t border-white/[0.06] p-3 space-y-2">
          <div className={cn("flex items-center justify-between rounded-xl border px-3 py-2", pc.bg, pc.border)}>
            <div className="flex items-center gap-2">
              <Zap className={cn("h-3.5 w-3.5", pc.color)} />
              <span className={cn("text-xs font-semibold", pc.color)}>{pc.label} Plan</span>
            </div>
            {plan === "starter" && (
              <Link
                href="/settings/billing"
                onClick={onClose}
                className="text-[10px] font-semibold text-indigo-400 hover:text-indigo-300 transition"
              >
                Upgrade →
              </Link>
            )}
          </div>

          <div className="flex items-center gap-3 rounded-xl px-2 py-2 hover:bg-white/[0.03] transition group">
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-violet-600 text-xs font-bold text-white shadow-lg shadow-indigo-500/20">
              {profile?.full_name ? initials(profile.full_name) : "?"}
            </div>
            <div className="min-w-0 flex-1">
              <p className="truncate text-xs font-semibold text-white">{profile?.full_name ?? "User"}</p>
              <p className="truncate text-[10px] text-white/40">{profile?.email}</p>
            </div>
            <form action={signOut}>
              <button
                type="submit"
                title="Sign out"
                className="rounded-lg p-1.5 text-white/20 transition hover:text-red-400 hover:bg-red-500/10"
              >
                <LogOut className="h-3.5 w-3.5" />
              </button>
            </form>
          </div>
        </div>
      )}

      {/* Collapsed bottom — just avatar + logout */}
      {collapsed && (
        <div className="shrink-0 border-t border-white/[0.06] p-2 space-y-1">
          <div
            title={profile?.full_name ?? "User"}
            className="flex justify-center"
          >
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-violet-600 text-xs font-bold text-white">
              {profile?.full_name ? initials(profile.full_name) : "?"}
            </div>
          </div>
          <form action={signOut} className="flex justify-center">
            <button
              type="submit"
              title="Sign out"
              className="rounded-lg p-1.5 text-white/20 transition hover:text-red-400 hover:bg-red-500/10"
            >
              <LogOut className="h-3.5 w-3.5" />
            </button>
          </form>
        </div>
      )}
    </div>
  )
}

export function Sidebar({ profile, isAdmin }: SidebarProps) {
  const [mobileOpen, setMobileOpen] = useState(false)
  const [collapsed, setCollapsed] = useState(false)

  // Persist collapse preference
  useEffect(() => {
    const stored = localStorage.getItem("sidebar-collapsed")
    if (stored === "true") setCollapsed(true)
  }, [])

  function toggleCollapse() {
    const next = !collapsed
    setCollapsed(next)
    localStorage.setItem("sidebar-collapsed", String(next))
  }

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={cn(
          "hidden md:flex h-screen shrink-0 flex-col border-r border-white/[0.06] bg-[#111118] transition-all duration-300",
          collapsed ? "w-16" : "w-60"
        )}
      >
        <NavContent profile={profile} collapsed={collapsed} isAdmin={isAdmin} />

        {/* Collapse toggle */}
        <button
          onClick={toggleCollapse}
          className="shrink-0 flex items-center justify-center gap-2 border-t border-white/[0.06] py-3 text-xs text-white/25 transition hover:text-white/60"
          title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
        >
          {collapsed
            ? <PanelLeftOpen className="h-4 w-4" />
            : <><PanelLeftClose className="h-4 w-4" /><span>Collapse</span></>
          }
        </button>
      </aside>

      {/* Mobile hamburger */}
      <div className="fixed top-0 left-0 z-50 flex h-16 items-center px-4 md:hidden">
        <button
          onClick={() => setMobileOpen(true)}
          className="flex h-9 w-9 items-center justify-center rounded-xl border border-white/[0.06] bg-white/[0.03] text-white/60 hover:bg-white/[0.08] hover:text-white transition"
          aria-label="Open menu"
        >
          <Menu className="h-5 w-5" />
        </button>
      </div>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 md:hidden">
          <div
            className="absolute inset-0 bg-black/70 backdrop-blur-sm"
            onClick={() => setMobileOpen(false)}
          />
          <aside className="absolute left-0 top-0 flex h-full w-72 flex-col bg-[#111118] shadow-2xl">
            <NavContent profile={profile} onClose={() => setMobileOpen(false)} isAdmin={isAdmin} />
          </aside>
        </div>
      )}
    </>
  )
}
