"use client"

import Image from "next/image"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import {
  LayoutDashboard,
  Users,
  FileText,
  LogOut,
  ChevronRight,
  LayoutGrid,
  UserRound,
  Info,
  Phone,
  Home,
  BookOpen,
  Stethoscope,
  Hospital,
  Layers,
  Scissors,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { useSidebarToggle } from "@/components/dashboard/sidebar-context"
import {
  cleanupDraftImageFolders,
  flushPendingArticleInlineUploadsBeforeLogout,
} from "@/lib/draft-image-cleanup-client"
import {
  getStoredCurrentUser,
  setStoredCurrentUser,
  clearStoredCurrentUser,
  type CachedCurrentUser,
} from "@/lib/current-user-cache"

const navItems = [
  {
    label: "Dashboard",
    href: "/dashboard",
    icon: LayoutDashboard,
    disabled: false,
  },
  {
    label: "Admins",
    href: "/dashboard/admins",
    icon: Users,
    disabled: false,
  },
  {
    label: "Articles",
    href: "/dashboard/articles",
    icon: FileText,
    disabled: false,
  },
  {
    label: "Categories",
    href: "/dashboard/categories",
    icon: LayoutGrid,
    disabled: false,
  },
  {
    label: "Doctors",
    href: "/dashboard/doctors",
    icon: UserRound,
    disabled: false,
  },
  {
    label: "Hospitals",
    href: "/dashboard/hospitals",
    icon: Hospital,
    disabled: false,
  },
  {
    label: "Procedures",
    href: "/dashboard/procedures",
    icon: Scissors,
    disabled: false,
  },
]

const pageItems = [
  {
    label: "Home Page",
    href: "/dashboard/home",
    icon: Home,
    disabled: false,
  },
  {
    label: "Doctors Page",
    href: "/dashboard/doctors-page",
    icon: Stethoscope,
    disabled: false,
  },
  {
    label: "Procedures Page",
    href: "/dashboard/procedures-page",
    icon: Scissors,
    disabled: false,
  },
  {
    label: "Blog Page",
    href: "/dashboard/blog",
    icon: BookOpen,
    disabled: false,
  },
  {
    label: "Hospitals Page",
    href: "/dashboard/hospitals-page",
    icon: Hospital,
    disabled: false,
  },
  {
    label: "About Us Page",
    href: "/dashboard/about-us",
    icon: Info,
    disabled: false,
  },
  {
    label: "Contact Us Page",
    href: "/dashboard/contact-us",
    icon: Phone,
    disabled: false,
  },
]

type SidebarUser = CachedCurrentUser

export function Sidebar() {
  const pathname = usePathname()
  const router = useRouter()
  const { onMenuClose } = useSidebarToggle()
  const [loggingOut, setLoggingOut] = useState(false)
  const [currentUser, setCurrentUser] = useState<SidebarUser | null>(null)
  const [pagesOpen, setPagesOpen] = useState(false)

  useEffect(() => {
    let active = true

    const cached = getStoredCurrentUser()
    if (cached) {
      setCurrentUser(cached)
      return
    }

    async function loadCurrentUser() {
      try {
        const res = await fetch("/api/admin/me", { cache: "no-store" })
        if (!res.ok) return

        const data = (await res.json()) as { user?: SidebarUser }
        if (active && data.user) {
          setCurrentUser(data.user)
          setStoredCurrentUser(data.user)
        }
      } catch {
        // Keep default fallback UI when request fails.
      }
    }

    void loadCurrentUser()

    return () => {
      active = false
    }
  }, [])

  const isInsidePages = pageItems.some(
    (item) => pathname === item.href || pathname.startsWith(`${item.href}/`)
  )

  useEffect(() => {
    if (isInsidePages) {
      setPagesOpen(true)
    }
  }, [isInsidePages])

  const displayName = currentUser?.name?.trim() || currentUser?.email || "Unknown User"
  const displayEmail = currentUser?.email || "no-email"
  const userInitial = displayName.charAt(0).toUpperCase() || "U"

  async function handleLogout() {
    setLoggingOut(true)
    clearStoredCurrentUser()
    try {
      await flushPendingArticleInlineUploadsBeforeLogout()
      await cleanupDraftImageFolders()
      await fetch("/api/auth/logout", { method: "POST" })
      router.push("/login")
      router.refresh()
    } finally {
      setLoggingOut(false)
    }
  }

  return (
    <aside
      className="flex flex-col h-screen w-[240px] min-w-[240px] max-w-[240px] overflow-y-scroll"
      style={{
        background: "var(--brand-navy)",
      }}
    >
      {/* Logo */}
      <div className="flex items-center gap-3 px-5 py-6 border-b border-white/10">
        <div className="shrink-0 w-15 h-15 rounded-xl overflow-hidden  flex items-center justify-center p-1">
          <Image
            src="/images/logo.png"
            alt="Livist Medical"
            width={36}
            height={36}
            className="object-contain w-full h-full"
            priority
          />
        </div>
        <div>
          <p className="text-white font-bold text-sm leading-tight font-sans">Livist Medical</p>
          <p className="text-white/45 text-[10px] font-sans uppercase tracking-wider">Admin Panel</p>
        </div>
      </div>

      {/* Navigation */}
      <nav className="flex-1 px-3 py-4 flex flex-col gap-1" aria-label="Main navigation">
        <p className="text-white/30 text-[10px] uppercase tracking-widest px-2 mb-2 font-sans">
          Menu
        </p>
        {navItems.map((item) => {
          const isActive =
            item.href === "/dashboard"
              ? pathname === "/dashboard"
              : pathname === item.href || pathname.startsWith(`${item.href}/`)
          const Icon = item.icon

          if (item.disabled) {
            return (
              <div
                key={item.href}
                title={item.disabled ? `${item.label} (Soon)` : item.label}
                className={cn(
                  "flex items-center gap-3 px-3 py-2.5 rounded-xl cursor-not-allowed select-none",
                  "opacity-35"
                )}
              >
                <Icon className="w-4 h-4 shrink-0 text-white/60" aria-hidden="true" />
                <span className="flex-1 text-sm text-white/60 font-sans">{item.label}</span>
                <span
                  className="text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded font-sans"
                  style={{ background: "rgba(255,255,255,0.10)", color: "rgba(255,255,255,0.4)" }}
                >
                  Soon
                </span>
              </div>
            )
          }

          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={onMenuClose}
              className={cn(
                "flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-150 group",
                isActive
                  ? "text-white"
                  : "text-white/55 hover:text-white hover:bg-white/8"
              )}
              style={isActive ? { background: "var(--brand-green)", boxShadow: "0 2px 8px rgba(43,182,115,0.30)" } : {}}
              aria-current={isActive ? "page" : undefined}
            >
              <Icon className="w-4 h-4 shrink-0" aria-hidden="true" />
              <>
                <span className="flex-1 text-sm font-medium font-sans">{item.label}</span>
                {isActive && <ChevronRight className="w-3 h-3 opacity-60" aria-hidden="true" />}
              </>
            </Link>
          )
        })}

        {/* Pages dropdown */}
        <button
          type="button"
          onClick={() => setPagesOpen((prev) => !prev)}
          className={cn(
            "flex cursor-pointer items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-150 w-full text-left",
            isInsidePages
              ? "text-white"
              : "text-white/55 hover:text-white hover:bg-white/8"
          )}
          style={isInsidePages && !pagesOpen ? { background: "var(--brand-green)", boxShadow: "0 2px 8px rgba(43,182,115,0.30)" } : {}}
        >
          <Layers className="w-4 h-4 shrink-0" aria-hidden="true" />
          <>
            <span className="flex-1 text-sm font-medium font-sans">Pages</span>
            <ChevronRight
              className={cn(
                "w-3 h-3 opacity-60 transition-transform duration-200",
                pagesOpen && "rotate-90"
              )}
              aria-hidden="true"
            />
          </>
        </button>

        {pagesOpen && (
          <div className="flex flex-col gap-1 pl-3">
            {pageItems.map((item) => {
              const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`)
              const Icon = item.icon
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={onMenuClose}
                  className={cn(
                    "flex items-center gap-3 px-3 py-2 rounded-xl transition-all duration-150",
                    isActive
                      ? "text-white"
                      : "text-white/55 hover:text-white hover:bg-white/8"
                  )}
                  style={isActive ? { background: "var(--brand-green)", boxShadow: "0 2px 8px rgba(43,182,115,0.30)" } : {}}
                  aria-current={isActive ? "page" : undefined}
                >
                  <Icon className="w-4 h-4 shrink-0" aria-hidden="true" />
                  <span className="flex-1 text-sm font-medium font-sans">{item.label}</span>
                  {isActive && <ChevronRight className="w-3 h-3 opacity-60" aria-hidden="true" />}
                </Link>
              )
            })}
          </div>
        )}
      </nav>

      {/* User + logout */}
      <div className="px-3 pb-4 border-t border-white/10 pt-4">
        <div className="flex items-center gap-3 px-3 py-2 mb-2">
          {currentUser?.image ? (
            <img
              src={currentUser.image}
              alt={displayName}
              className="w-8 h-8 rounded-full object-cover shrink-0"
            />
          ) : (
            <div
              className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 text-white font-bold text-sm font-sans"
              style={{ background: "var(--brand-green)" }}
              aria-hidden="true"
            >
              {userInitial}
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p className="text-white text-xs font-semibold font-sans truncate">{displayName}</p>
            <p className="text-white/40 text-[10px] font-sans truncate">{displayEmail}</p>
          </div>
        </div>
        <button
          type="button"
          onClick={() => void handleLogout()}
          disabled={loggingOut}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/50 hover:text-white hover:bg-white/8 transition-all duration-150 disabled:opacity-50 cursor-pointer text-left"
          title="Log out"
        >
          <LogOut className="w-4 h-4 shrink-0" aria-hidden="true" />
          <span className="text-sm font-sans">{loggingOut ? "Signing out…" : "Log out"}</span>
        </button>
      </div>
    </aside>
  )
}
