'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import {
  Building2, DollarSign, Briefcase, TrendingUp, FileText,
  Globe, MessageSquare, ClipboardList, Settings, ShoppingCart,
  Bell, LogOut, ChevronDown, ChevronLeft,
} from 'lucide-react'
import { useState } from 'react'
import { useAuth } from '@/hooks/useAuth'

// ── Constants ─────────────────────────────────────────────────────────────────

const BRAND_GOLD = '#C9A96E'
const DIVIDER    = '1px solid rgba(255,255,255,0.08)'
const hoverBg    = 'rgba(255,255,255,0.08)'

const NAV_ITEMS = [
  { label: 'Client Master',    segment: 'master',     Icon: Building2 },
  { label: 'Debt & Treasury',  segment: 'debt',       Icon: DollarSign },
  { label: 'Business Profile', segment: 'business',   Icon: Briefcase },
  { label: 'Financials',       segment: 'financials', Icon: TrendingUp },
  { label: 'Fund Raise',       segment: 'fundraise',  Icon: FileText },
  { label: 'Forex & Trade',    segment: 'forex',      Icon: Globe },
]

const TOOL_ITEMS = [
  { label: 'RFI Center',      href: '/rfi',               Icon: MessageSquare },
  { label: 'Audit Log',       href: '/audit',             Icon: ClipboardList },
  { label: 'Industry Master', href: '/master/industries', Icon: Building2 },
  { label: 'Settings',        href: '/settings',          Icon: Settings },
]

// ── Primitives ────────────────────────────────────────────────────────────────

function useHover() {
  return {
    onMouseEnter: (e: React.MouseEvent<HTMLElement>) => { e.currentTarget.style.background = hoverBg },
    onMouseLeave: (e: React.MouseEvent<HTMLElement>) => { e.currentTarget.style.background = '' },
  }
}

function LogoSvg({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" className={className}>
      <rect width="40" height="40" rx="8" fill={BRAND_GOLD} fillOpacity="0.18" />
      <rect width="40" height="40" rx="8" stroke={BRAND_GOLD} strokeWidth="1.5" fillOpacity="0" />
      <text x="50%" y="56%" dominantBaseline="middle" textAnchor="middle"
        fontFamily="'Noto Sans Devanagari', serif" fontSize="18" fontWeight="600" fill={BRAND_GOLD}>
        सa
      </text>
    </svg>
  )
}

function NavLink({ href, active, children }: { href: string; active: boolean; children: React.ReactNode }) {
  const hover = useHover()
  return (
    <Link
      href={href}
      className={`sidebar-nav-item ${active ? 'sidebar-nav-item-active' : 'sidebar-nav-item-inactive'}`}
      {...(!active ? hover : {})}
    >
      {children}
    </Link>
  )
}

function NavBtn({ badge, children, onClick }: { badge?: number; children: React.ReactNode , onClick?: () => void}) {
  const hover = useHover()
  return (
    <button onClick={onClick} className="sidebar-nav-item sidebar-nav-item-inactive w-full relative" {...hover}>
      {children}
      {badge && (
        <span className="flex items-center justify-center bg-red-500 text-white font-bold rounded-full text-[10px] leading-none w-5 h-5 flex-shrink-0">
          {badge}
        </span>
      )}
    </button>
  )
}

function SectionLabel({ label }: { label: string }) {
  return (
    <div className="px-2 pt-3 pb-1">
      <span className="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-600">{label}</span>
    </div>
  )
}

// ── Sub-components ────────────────────────────────────────────────────────────

function LogoRow({ collapsed, onToggle }: { collapsed: boolean; onToggle: () => void }) {
  return (
    <div className="flex items-center justify-between px-3 py-4 h-14 flex-shrink-0" style={{ borderBottom: DIVIDER }}>
      {collapsed ? (
        <div className="w-7 h-7 mx-auto"><LogoSvg className="w-full h-full" /></div>
      ) : (
        <div className="flex items-center gap-2.5 min-w-0">
          <div className="w-7 h-7 flex-shrink-0"><LogoSvg className="w-full h-full" /></div>
          <div className="min-w-0">
            <div className="text-white font-semibold text-md leading-tight truncate">Samastha Arth</div>
            <div className="text-[10px] font-medium uppercase tracking-[0.1em] truncate" style={{ color: BRAND_GOLD }}>
              Capital Intelligence
            </div>
          </div>
        </div>
      )}
      <button
        onClick={onToggle}
        className="flex-shrink-0 w-6 h-6 rounded-md flex items-center justify-center text-slate-400 hover:text-white hover:bg-white/10 transition-colors"
        aria-label="Collapse sidebar"
      >
        <ChevronLeft
          className="w-3.5 h-3.5 transition-transform duration-200"
          style={{ transform: collapsed ? 'rotate(180deg)' : 'none' }}
        />
      </button>
    </div>
  )
}

function ClientSelector({ displayName, collapsed }: { displayName: string; collapsed: boolean }) {
  const hover = useHover()
  return (
    <div className="px-2 py-3 flex-shrink-0" style={{ borderBottom: DIVIDER }}>
      <button className="w-full flex items-center gap-2 px-2 py-2 rounded-md text-left transition-colors" {...hover}>
        <div className="w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0" style={{ background: `rgba(201,169,110,0.2)` }}>
          <Building2 className="w-3.5 h-3.5" style={{ color: BRAND_GOLD }} />
        </div>
        {!collapsed && (
          <>
            <div className="min-w-0 flex-1">
              <div className="text-white text-sm font-medium truncate leading-tight">{displayName}</div>
              <div className="text-slate-500 text-[12px] truncate">Private Limited</div>
            </div>
            <ChevronDown className="w-3.5 h-3.5 text-slate-500 flex-shrink-0" />
          </>
        )}
      </button>
    </div>
  )
}

function NavSection({
  collapsed,
  navHref,
  isActive,
}: {
  collapsed: boolean;
  navHref: (segment: string) => string;
  isActive: (segment: string) => boolean;
}) {
  return (
    <nav className="flex-1 overflow-y-auto px-2 py-3 space-y-0.5">
      {NAV_ITEMS.map(({ label, segment, Icon }) => (
        <NavLink key={segment} href={navHref(segment)} active={isActive(segment)}>
          <Icon className="w-4 h-4 flex-shrink-0" />
          {!collapsed && <span className="truncate">{label}</span>}
        </NavLink>
      ))}

      {!collapsed && <SectionLabel label="Tools" />}

      {TOOL_ITEMS.map(({ label, href, Icon }) => (
        <NavLink key={href} href={href} active={isActive(href)}>
          <Icon className="w-4 h-4 flex-shrink-0" />
          {!collapsed && <span className="truncate">{label}</span>}
        </NavLink>
      ))}
    </nav>
  )
}

function BottomSection({ collapsed }: { collapsed: boolean }) {
  const { logout } = useAuth()
  return (
    <div className="px-2 py-3 space-y-1 flex-shrink-0" style={{ borderTop: DIVIDER }}>
      <NavBtn>
        <ShoppingCart className="w-4 h-4 flex-shrink-0" />
        {!collapsed && <span className="flex-1 text-left">Document Cart</span>}
      </NavBtn>

      <NavBtn badge={7}>
        <Bell className="w-4 h-4 flex-shrink-0" />
        {!collapsed && <span className="flex-1 text-left">Notifications</span>}
      </NavBtn>

      {!collapsed && (
        <div className="flex items-center gap-2.5 px-2 py-2 mt-1">
          <div className="w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0" style={{ background: 'rgba(201,169,110,0.2)' }}>
            <span className="text-[10px] font-bold" style={{ color: BRAND_GOLD }}>RM</span>
          </div>
          <div className="min-w-0 flex-1">
            <div className="text-white text-xs font-medium truncate leading-tight">Rahul Mehta</div>
            <div className="text-slate-500 text-[10px] capitalize truncate">advisory admin</div>
          </div>
        </div>
      )}

      <NavBtn onClick={() => logout()} >
        <LogOut className="w-4 h-4 flex-shrink-0" />
        {!collapsed && <span className="truncate">Sign out</span>}
      </NavBtn>
    </div>
  )
}

// ── Sidebar ───────────────────────────────────────────────────────────────────

export default function Sidebar() {
  const pathname = usePathname()
  const [collapsed, setCollapsed] = useState(false)
   

  const segments = pathname.split('/').filter(Boolean)
  const clientId = segments[0] === 'clients' && segments.length >= 3 ? segments[1] : null

  const clientDisplayName = clientId
    ? clientId.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')
    : 'Select Client'

  function navHref(segment: string) {
    return clientId ? `/clients/${clientId}/${segment}` : '/clients'
  }

  function isActive(segment: string) {
    if (segment === 'master') return pathname === '/clients' || pathname.endsWith('/master')
    return pathname.endsWith(`/${segment}`) || pathname === segment
  }

  return (
    <aside
      className="flex flex-col h-screen sticky top-0 flex-shrink-0 transition-all duration-200 ease-in-out"
      style={{ background: '#0B1E3F', borderRight: DIVIDER, width: collapsed ? '56px' : '240px' }}
    >
      <LogoRow collapsed={collapsed} onToggle={() => setCollapsed(v => !v)} />
      <ClientSelector displayName={clientDisplayName} collapsed={collapsed} />
      <NavSection collapsed={collapsed} navHref={navHref} isActive={isActive} />
      <BottomSection collapsed={collapsed} />
    </aside>
  )
}
