import { useState } from 'react'
import { NavLink, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import {
  LayoutDashboard, ReceiptText, Settings, Users,
  Container, Package, Anchor, ChevronDown,
  ClipboardList, FileStack, FileText, ShieldCheck, Ship,
} from 'lucide-react'

// ─── Nav structure ─────────────────────────────────────────────────────────────
const NAV = [
  {
    group: null,
    items: [
      { to: '/', icon: LayoutDashboard, label: 'Dashboard', sub: 'Rekap & insight data' },
      { to: '/invoice', icon: ReceiptText, label: 'Daftar Invoice', sub: 'Semua invoice & analisa' },
    ],
  },
  {
    group: 'TPP',
    accent: '#38bdf8',
    items: [
      { to: '/tpp/btd', icon: FileStack, label: 'Input BTD', sub: 'BCF 1.5' },
      { to: '/tpp/btd/daftar', icon: ClipboardList, label: 'Daftar BTD' },
      { to: '/tpp/bdn', icon: FileStack, label: 'Input BDN', sub: 'KEP BDN' },
      { to: '/tpp/bdn/daftar', icon: ClipboardList, label: 'Daftar BDN' },
      { to: '/tpp/fcl', icon: Container, label: 'Transaksi FCL', sub: 'Full Container' },
      { to: '/tpp/lcl', icon: Package, label: 'Transaksi LCL', sub: 'LCL / Kargo' },
    ],
  },
  {
    group: 'Gudang Umum',
    accent: '#34d399',
    items: [
      { to: '/gu/data', icon: FileText, label: 'Input Gudang', sub: 'Surat Jalan' },
      { to: '/gu/fcl', icon: Container, label: 'Transaksi FCL', sub: 'Full Container' },
      { to: '/gu/lcl', icon: Package, label: 'Transaksi LCL', sub: 'LCL / Kargo' },
    ],
  },
  {
    group: 'Konsolidasi Ekspor',
    accent: '#f59e0b',
    items: [
      { to: '/konsolidasi/emkl',      icon: Ship,          label: 'Master EMKL',       sub: 'Data EMKL & Tarif' },
      { to: '/konsolidasi/input',     icon: FileText,      label: 'Input Konsolidasi', sub: 'Booking Ekspor' },
      { to: '/konsolidasi/daftar',    icon: ClipboardList, label: 'Daftar Konsolidasi' },
      { to: '/konsolidasi/transaksi', icon: ReceiptText,   label: 'Transaksi',         sub: 'Invoice EXP' },
    ],
  },
  {
    group: 'Master Data',
    accent: '#94a3b8',
    items: [
      { to: '/master-tarif',    icon: Settings,  label: 'Master Tarif',     sub: 'Kelola tarif & biaya' },
      { to: '/master-klien',    icon: Users,     label: 'Master Klien',     sub: 'Data klien' },
      { to: '/user-management', icon: ShieldCheck, label: 'User Management', sub: 'Akun & hak akses', adminOnly: true },
    ],
  },
]

// ─── Single nav item ──────────────────────────────────────────────────────────
function NavItem({ item, accent }) {
  const Icon = item.icon
  return (
    <NavLink
      to={item.to}
      end={item.to === '/'}
      style={({ isActive }) => ({
        display: 'flex', alignItems: 'center', gap: 11,
        padding: '9px 14px', borderRadius: 10, marginBottom: 2,
        textDecoration: 'none', transition: 'all 0.15s',
        background: isActive ? `${accent}20` : 'transparent',
        borderLeft: `3px solid ${isActive ? accent : 'transparent'}`,
      })}
    >
      {({ isActive }) => (
        <>
          <Icon
            size={16}
            strokeWidth={isActive ? 2.5 : 2}
            color={isActive ? accent : 'rgba(255,255,255,0.55)'}
            style={{ flexShrink: 0 }}
          />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 13, fontWeight: isActive ? 700 : 600,
              color: isActive ? '#ffffff' : 'rgba(255,255,255,0.72)',
              lineHeight: 1.2, letterSpacing: isActive ? '-0.01em' : 'normal',
            }}>
              {item.label}
            </div>
            {item.sub && (
              <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.32)', marginTop: 1 }}>
                {item.sub}
              </div>
            )}
          </div>
        </>
      )}
    </NavLink>
  )
}

// ─── Nav group ────────────────────────────────────────────────────────────────
function NavGroup({ group }) {
  const location = useLocation()
  const [open, setOpen] = useState(true)
  const accent = group.accent || '#38bdf8'
  const anyActive = group.items.some(i =>
    i.to === '/' ? location.pathname === '/' : location.pathname.startsWith(i.to)
  )

  // Top-level group (no header)
  if (!group.group) {
    return (
      <div style={{ marginBottom: 4 }}>
        {group.items.map(item => <NavItem key={item.to} item={item} accent="#38bdf8" />)}
      </div>
    )
  }

  return (
    <div style={{ marginBottom: 4 }}>
      {/* Group header */}
      <button onClick={() => setOpen(o => !o)} style={{
        width: '100%', border: 'none', background: 'none', padding: '6px 14px 4px',
        cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'inherit',
      }}>
        {/* Active dot */}
        <span style={{
          width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
          background: anyActive ? accent : 'transparent',
          boxShadow: anyActive ? `0 0 6px ${accent}` : 'none',
          transition: 'all 0.2s',
        }} />
        <span style={{
          flex: 1, textAlign: 'left', fontSize: 10, fontWeight: 700,
          letterSpacing: '0.12em', textTransform: 'uppercase',
          color: anyActive ? accent : 'rgba(255,255,255,0.35)',
          transition: 'color 0.15s',
        }}>
          {group.group}
        </span>
        <ChevronDown
          size={11}
          color="rgba(255,255,255,0.25)"
          style={{ transform: open ? 'rotate(0deg)' : 'rotate(-90deg)', transition: 'transform 0.2s' }}
        />
      </button>

      {open && (
        <div style={{ paddingLeft: 0, paddingBottom: 4 }}>
          {group.items.map(item => <NavItem key={item.to} item={item} accent={accent} />)}
        </div>
      )}
    </div>
  )
}

// ─── Main Sidebar ─────────────────────────────────────────────────────────────
export default function Sidebar() {
  const { isAdmin } = useAuth()
  const filteredNav = NAV.map(group => ({
    ...group,
    items: (group.items || []).filter(item => !item.adminOnly || isAdmin),
  }))
  return (
    <aside style={{
      width: 'var(--sidebar-width)',
      background: 'linear-gradient(180deg, #111827 0%, #1a2744 50%, #0f1f3d 100%)',
      height: '100vh', position: 'fixed', left: 0, top: 0,
      display: 'flex', flexDirection: 'column',
      borderRight: '1px solid rgba(255,255,255,0.06)',
      zIndex: 50,
    }}>

      {/* ── Logo ── */}
      <div style={{ padding: '20px 16px 16px', borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 11, flexShrink: 0,
            background: 'linear-gradient(135deg, #0ea5e9 0%, #0369a1 100%)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 4px 14px rgba(14,165,233,0.4)',
          }}>
            <Anchor size={19} color="white" strokeWidth={2.5} />
          </div>
          <div>
            <div style={{
              fontFamily: "'DM Serif Display', Georgia, serif",
              fontSize: 15.5, color: 'white', lineHeight: 1.1,
              letterSpacing: '0.01em',
            }}>
              Sarana Gemilang
            </div>
            <div style={{
              fontSize: 9.5, marginTop: 3, letterSpacing: '0.14em',
              textTransform: 'uppercase', color: 'rgba(255,255,255,0.35)',
              fontWeight: 600,
            }}>
              Finance System
            </div>
          </div>
        </div>
      </div>

      {/* ── Nav ── */}
      <nav style={{ flex: 1, overflowY: 'auto', padding: '12px 8px 12px' }}>
        {filteredNav.map((group, idx) => (
          <div key={idx}>
            {idx > 0 && idx === 1 && (
              <div style={{ margin: '6px 14px 10px', borderTop: '1px solid rgba(255,255,255,0.06)' }} />
            )}
            {idx > 0 && idx !== 1 && (
              <div style={{ margin: '4px 14px 8px', borderTop: '1px solid rgba(255,255,255,0.04)' }} />
            )}
            <NavGroup group={group} />
          </div>
        ))}
      </nav>

      {/* ── Footer ── */}
      <div style={{
        padding: '12px 16px 16px',
        borderTop: '1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.25)', lineHeight: 1.7 }}>
          <span style={{ color: 'rgba(255,255,255,0.4)', fontWeight: 600 }}>PT. Sarana Gemilang</span>
          <br />Jl. Raya Pelabuhan No.1, Belawan
        </div>
      </div>
    </aside>
  )
}