"use client"

import Link from "next/link"
import { usePathname, useSearchParams } from "next/navigation"
import { useTranslation } from "react-i18next"
import { getNavigation } from "@/lib/navigation"
import { cn } from "@/lib/utils"
import { Coins, LogOut, ChevronDown, ChevronLeft } from "lucide-react"
import { useMemo, useState, useEffect } from "react"
import { api } from "@/lib/api"
import { ENDPOINTS } from "@/constants/endpoints"

const REVIEWABLE_KYC_STATUSES = new Set(["submitted", "pending", "under_review"])

function unwrapListPayload(response: any): any[] {
  const payload = response && typeof response === "object" && "success" in response
    ? response.data
    : response

  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload?.items)) return payload.items
  if (Array.isArray(payload?.data)) return payload.data
  if (Array.isArray(payload?.data?.items)) return payload.data.items
  return []
}

export function AppSidebar() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const { t, i18n } = useTranslation()
  const navigation = useMemo(() => getNavigation(), [i18n.language])
  
  // Initialize with all groups collapsed by default, except the first one
  const [expandedGroups, setExpandedGroups] = useState<string[]>([])
  const [kycApplicationsBadge, setKycApplicationsBadge] = useState<string | null>(null)

  useEffect(() => {
    // Expand only the first group by default on mount
    if (navigation.length > 0) {
      setExpandedGroups([navigation[0].title])
    }
  }, [navigation])

  useEffect(() => {
    const fetchKycApplicationCount = async () => {
      try {
        const res = await api.get(ENDPOINTS.KYC.LIST, { params: { limit: 1000 } })
        const applications = unwrapListPayload(res)
        const reviewableCount = applications.filter((application) =>
          REVIEWABLE_KYC_STATUSES.has(String(application.status || "").toLowerCase())
        ).length
        setKycApplicationsBadge(String(reviewableCount))
      } catch (err) {
        console.error("Failed to fetch KYC application count", err)
        setKycApplicationsBadge(null)
      }
    }

    fetchKycApplicationCount()
    window.addEventListener("kyc-applications-updated", fetchKycApplicationCount)
    return () => window.removeEventListener("kyc-applications-updated", fetchKycApplicationCount)
  }, [])

  const toggleGroup = (title: string) => {
    setExpandedGroups(prev => 
      prev.includes(title) ? prev.filter(t => t !== title) : [...prev, title]
    )
  }

  const isActive = (href: string) => {
    const query = searchParams.toString()
    const currentHref = query ? `${pathname}?${query}` : pathname
    if (href.includes("?")) return currentHref === href
    if (href === "/") return pathname === "/"
    
    // Fix: Prevent /ledger from highlighting when we are in /ledger/payments
    if (href === "/ledger" && pathname.startsWith("/ledger/payments")) {
      return false
    }

    return pathname === href || pathname.startsWith(`${href}/`)
  }

  return (
    <aside
      className="hidden lg:flex fixed top-0 ltr:left-0 rtl:right-0 h-screen w-64 flex-col bg-sidebar text-sidebar-foreground ltr:border-r rtl:border-l border-sidebar-border z-40"
    >
      {/* Brand */}
      <div className="flex items-center gap-3 px-5 py-5 border-b border-sidebar-border">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-gold-400 to-gold-600 shadow-[0_2px_10px_rgba(201,162,39,0.25)]">
          <Coins className="h-5 w-5 text-[#1f1604]" strokeWidth={2.25} />
        </div>
        <div className="flex flex-col leading-tight">
          <span className="text-[15px] font-bold text-white tracking-tight">Gold Wallet</span>
          <span className="text-[11px] text-sidebar-muted font-medium">{t('components.layout.app-sidebar.text_1')}</span>
        </div>
      </div>

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto px-3 py-4">
        {navigation.map((group) => {
          const isExpanded = expandedGroups.includes(group.title)
          
          return (
            <div key={group.title} className="mb-3">
              <button
                onClick={() => toggleGroup(group.title)}
                className="w-full flex items-center justify-between px-3 py-2 text-[10.5px] font-semibold uppercase tracking-[0.12em] text-sidebar-muted hover:text-sidebar-foreground transition-colors rounded-md hover:bg-sidebar-accent/30"
              >
                <span>{group.title}</span>
                {isExpanded ? (
                  <ChevronDown className="w-3.5 h-3.5" />
                ) : (
                  <ChevronLeft className="w-3.5 h-3.5" />
                )}
              </button>
              
              {isExpanded && (
                <ul className="space-y-0.5 mt-1">
                  {group.items.map((item) => {
                    const active = isActive(item.href)
                    const Icon = item.icon
                    const badge = item.href === "/kyc" ? kycApplicationsBadge : item.badge
                    return (
                      <li key={item.href}>
                        <Link
                          href={item.href}
                          className={cn(
                            "group flex items-center gap-3 rounded-md px-3 py-2 text-[13px] font-medium transition-colors relative",
                            active
                              ? "bg-sidebar-accent text-white"
                              : "text-sidebar-foreground/85 hover:bg-sidebar-accent/60 hover:text-white",
                          )}
                        >
                          {active && (
                            <span className="absolute ltr:left-0 rtl:right-0 top-1.5 bottom-1.5 w-[3px] ltr:rounded-r rtl:rounded-l bg-gold-500" />
                          )}
                          <Icon
                            className={cn(
                              "h-[17px] w-[17px] shrink-0",
                              active ? "text-gold-400" : "text-sidebar-muted group-hover:text-sidebar-foreground",
                            )}
                            strokeWidth={1.75}
                          />
                          <span className="flex-1 truncate">{item.title}</span>
                          {badge && (
                            <span className="rounded-full bg-destructive/90 text-white text-[10px] font-semibold px-1.5 py-0.5 min-w-[20px] text-center">
                              {badge}
                            </span>
                          )}
                        </Link>
                      </li>
                    )
                  })}
                </ul>
              )}
            </div>
          )
        })}
      </nav>

      {/* Footer */}
      <div className="border-t border-sidebar-border px-3 py-3">
        <Link
          href="/login"
          className="flex items-center gap-3 rounded-md px-3 py-2 text-[13px] font-medium text-sidebar-foreground/85 hover:bg-sidebar-accent/60 hover:text-white transition-colors"
        >
          <LogOut className="h-[17px] w-[17px]" strokeWidth={1.75} />
          <span>{t('components.layout.app-sidebar.text_2')}</span>
        </Link>
      </div>
    </aside>
  )
}
