'use client'

import { useState, useEffect, useRef } from 'react'
import { useSession, signOut } from 'next-auth/react'
import { useRouter, usePathname } from 'next/navigation'
import Link from 'next/link'
import axios from 'axios'
import { cn } from '@/lib/utils'
import {
  LayoutDashboard, Users, CreditCard, PiggyBank, Calculator,
  AlertTriangle, BarChart2, Settings, Shield, Building2,
  ChevronDown, ChevronRight, LogOut, User, Bell, Menu, X,
  Briefcase, Package, UsersRound, Wallet, ClipboardList,
  TrendingUp, FileText, Database, HardDrive, DollarSign,
  BookOpen, Activity, Home, ArrowLeftRight,
} from 'lucide-react'

interface NavItem {
  label: string
  href?: string
  icon: React.ReactNode
  permission?: string
  children?: NavItem[]
  badge?: number
}

const navigation: NavItem[] = [
  { label: 'Dashboard',    href: '/dashboard',      icon: <LayoutDashboard className="w-4 h-4" />, permission: 'loans.view' },
  { label: 'Members',      href: '/members',         icon: <Users className="w-4 h-4" />,           permission: 'members.view' },
  {
    label: 'Loans', icon: <CreditCard className="w-4 h-4" />, permission: 'loans.view',
    children: [
      { label: 'All Loans',       href: '/loans',             icon: <CreditCard className="w-3.5 h-3.5" /> },
      { label: 'Applications',    href: '/loans/applications', icon: <ClipboardList className="w-3.5 h-3.5" /> },
      { label: 'Pending Approval',href: '/loans/approvals',   icon: <AlertTriangle className="w-3.5 h-3.5" /> },
      { label: 'Disbursements',   href: '/loans/disbursements',icon: <DollarSign className="w-3.5 h-3.5" /> },
      { label: 'Loan Products',   href: '/loans/products',    icon: <Package className="w-3.5 h-3.5" /> },
    ],
  },
  {
    label: 'Savings', icon: <PiggyBank className="w-4 h-4" />, permission: 'savings.view',
    children: [
      { label: 'FOSA Accounts',   href: '/savings/fosa',     icon: <Wallet className="w-3.5 h-3.5" /> },
      { label: 'BOSA Savings',    href: '/savings/bosa',     icon: <PiggyBank className="w-3.5 h-3.5" /> },
      { label: 'Shares',          href: '/savings/shares',   icon: <TrendingUp className="w-3.5 h-3.5" /> },
      { label: 'Fixed Deposits',  href: '/savings/deposits', icon: <Database className="w-3.5 h-3.5" /> },
    ],
  },
  { label: 'Groups',       href: '/groups',          icon: <UsersRound className="w-4 h-4" />,      permission: 'groups.view' },
  { label: 'Collections',  href: '/collections',     icon: <AlertTriangle className="w-4 h-4" />,    permission: 'collections.view' },
  {
    label: 'Accounting', icon: <Calculator className="w-4 h-4" />, permission: 'accounting.view',
    children: [
      { label: 'Journal Entries', href: '/accounting/journals', icon: <BookOpen className="w-3.5 h-3.5" /> },
      { label: 'Transfers',       href: '/accounting/transfers', icon: <ArrowLeftRight className="w-3.5 h-3.5" /> },
      { label: 'Chart of Accounts',href: '/accounting/coa',    icon: <Database className="w-3.5 h-3.5" /> },
      { label: 'Cashbook',        href: '/accounting/cashbook', icon: <Wallet className="w-3.5 h-3.5" /> },
      { label: 'Bank Accounts',   href: '/accounting/banks',   icon: <Building2 className="w-3.5 h-3.5" /> },
      { label: 'Trial Balance',   href: '/accounting/trial-balance', icon: <FileText className="w-3.5 h-3.5" /> },
      { label: 'Income Statement',href: '/accounting/income-statement', icon: <TrendingUp className="w-3.5 h-3.5" /> },
      { label: 'Balance Sheet',   href: '/accounting/balance-sheet', icon: <Database className="w-3.5 h-3.5" /> },
      { label: 'Setup',           href: '/accounting/setup',        icon: <Settings className="w-3.5 h-3.5" /> },
    ],
  },
  {
    label: 'Expenses', icon: <DollarSign className="w-4 h-4" />, permission: 'accounting.view',
    children: [
      { label: 'All Expenses',    href: '/expenses',           icon: <DollarSign className="w-3.5 h-3.5" /> },
      { label: 'Categories',      href: '/expenses/categories',icon: <Package className="w-3.5 h-3.5" /> },
    ],
  },
  {
    label: 'Payroll', icon: <Briefcase className="w-4 h-4" />, permission: 'payroll.view',
    children: [
      { label: 'Payroll Runs',    href: '/payroll',           icon: <Briefcase className="w-3.5 h-3.5" /> },
      { label: 'Staff',           href: '/payroll/staff',     icon: <Users className="w-3.5 h-3.5" /> },
      { label: 'Statutory Rates', href: '/payroll/statutory',  icon: <FileText className="w-3.5 h-3.5" /> },
      { label: 'Cash Advances',   href: '/payroll/advances',  icon: <DollarSign className="w-3.5 h-3.5" /> },
    ],
  },
  { label: 'Suppliers',    href: '/suppliers',       icon: <Package className="w-4 h-4" />,          permission: 'admin.view' },
  { label: 'Fixed Assets', href: '/assets',          icon: <HardDrive className="w-4 h-4" />,        permission: 'admin.view' },
  { label: 'Reports',      href: '/reports',         icon: <BarChart2 className="w-4 h-4" />,        permission: 'reports.view' },
  { label: 'Audit Logs',   href: '/admin/audit',     icon: <Activity className="w-4 h-4" />,         permission: 'admin.view' },
  { label: 'Configuration',href: '/configuration',   icon: <Settings className="w-4 h-4" />,         permission: 'configuration.view' },
  { label: 'User Management', href: '/admin/users',  icon: <Shield className="w-4 h-4" />,           permission: 'admin.view' },
]

function NavLink({ item, depth = 0 }: { item: NavItem; depth?: number }) {
  const pathname = usePathname()
  const [open, setOpen] = useState(() => {
    if (!item.children) return false
    return item.children.some(c => c.href && pathname.startsWith(c.href))
  })

  const isActive = item.href ? pathname === item.href || (item.href !== '/dashboard' && pathname.startsWith(item.href)) : false

  if (item.children) {
    return (
      <div>
        <button
          onClick={() => setOpen(!open)}
          className={cn(
            'nav-item w-full justify-between',
            open && 'bg-accent text-foreground'
          )}
        >
          <span className="flex items-center gap-2.5">{item.icon}{item.label}</span>
          {open ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
        </button>
        {open && (
          <div className="ml-4 border-l border-border pl-2 mt-0.5 space-y-0.5">
            {item.children.map(child => (
              <NavLink key={child.href} item={child} depth={depth + 1} />
            ))}
          </div>
        )}
      </div>
    )
  }

  return (
    <Link href={item.href!} className={cn('nav-item', isActive && 'nav-active')}>
      {item.icon}
      <span>{item.label}</span>
      {item.badge ? (
        <span className="ml-auto bg-destructive text-destructive-foreground text-xs px-1.5 py-0.5 rounded-full">{item.badge}</span>
      ) : null}
    </Link>
  )
}

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession()
  const router = useRouter()
  const [sidebarOpen, setSidebarOpen] = useState(true)
  const [mobileOpen, setMobileOpen] = useState(false)

  const [notifOpen, setNotifOpen] = useState(false)
  const [profileOpen, setProfileOpen] = useState(false)
  const notifRef = useRef<HTMLDivElement>(null)
  const profileRef = useRef<HTMLDivElement>(null)
  const [notifData, setNotifData] = useState<{ total: number; items: { label: string; count: number; href: string }[] } | null>(null)

  useEffect(() => {
    axios.get('/api/notifications/pending').then(r => setNotifData(r.data.data)).catch(() => {})
    const interval = setInterval(() => {
      axios.get('/api/notifications/pending').then(r => setNotifData(r.data.data)).catch(() => {})
    }, 30000)
    return () => clearInterval(interval)
  }, [])

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (notifRef.current && !notifRef.current.contains(e.target as Node)) setNotifOpen(false)
      if (profileRef.current && !profileRef.current.contains(e.target as Node)) setProfileOpen(false)
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [])

  useEffect(() => {
    if (status === 'unauthenticated') router.push('/login')
  }, [status, router])

  if (status === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-3">
          <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin" />
          <p className="text-sm text-muted-foreground">Loading LMS...</p>
        </div>
      </div>
    )
  }

  if (status === 'unauthenticated') return null

  const userInitials = session?.user?.name?.split(' ').map(n => n[0]).join('').slice(0, 2) ?? 'U'
  const permissions  = session?.user?.permissions ?? []
  const visibleNav   = navigation.filter(n => !n.permission || permissions.includes(n.permission))

  return (
    <div className="flex h-screen bg-background overflow-hidden">
      {/* Mobile overlay */}
      {mobileOpen && (
        <div className="fixed inset-0 z-40 bg-black/50 lg:hidden" onClick={() => setMobileOpen(false)} />
      )}

      {/* Sidebar */}
      <aside className={cn(
        'fixed inset-y-0 left-0 z-50 flex flex-col bg-card border-r transition-all duration-200',
        sidebarOpen ? 'w-60' : 'w-14',
        'lg:relative lg:flex',
        mobileOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
      )}>
        {/* Logo */}
        <div className="flex items-center gap-3 px-3 py-4 border-b h-14 shrink-0">
          {session?.user?.organisationLogo ? (
            <img src={session.user.organisationLogo} alt="Logo" className="w-8 h-8 rounded-lg object-contain shrink-0" />
          ) : (
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center shrink-0">
              <Home className="w-4 h-4 text-primary-foreground" />
            </div>
          )}
          {sidebarOpen && (
            <div className="overflow-hidden">
              <p className="text-sm font-semibold text-foreground truncate">{session?.user?.organisationName || 'LMS'}</p>
              <p className="text-xs text-muted-foreground truncate">v1.0 · SASRA Compliant</p>
            </div>
          )}
        </div>

        {/* Nav */}
        <nav className="flex-1 overflow-y-auto p-2 space-y-0.5">
          {visibleNav.map(item => (
            sidebarOpen ? (
              <NavLink key={item.label} item={item} />
            ) : (
              item.href ? (
                <Link key={item.label} href={item.href} title={item.label}
                  className="flex items-center justify-center p-2 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
                >
                  {item.icon}
                </Link>
              ) : null
            )
          ))}
        </nav>

        {/* User */}
        <div className="border-t p-2 shrink-0">
          <div className={cn('flex items-center gap-2 rounded-lg p-2', sidebarOpen ? 'hover:bg-accent' : 'justify-center')}>
            <div className="w-8 h-8 bg-primary rounded-full flex items-center justify-center text-primary-foreground text-xs font-bold shrink-0">
              {userInitials}
            </div>
            {sidebarOpen && (
              <div className="flex-1 overflow-hidden">
                <p className="text-sm font-medium truncate">{session?.user?.name}</p>
                <p className="text-xs text-muted-foreground truncate">{session?.user?.roles?.[0]}</p>
              </div>
            )}
            {sidebarOpen && (
              <button onClick={() => signOut({ callbackUrl: '/login' })} className="text-muted-foreground hover:text-foreground">
                <LogOut className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>
      </aside>

      {/* Main */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        {/* Topbar */}
        <header className="h-14 border-b bg-card flex items-center px-4 gap-3 shrink-0">
          <button onClick={() => { setSidebarOpen(!sidebarOpen); setMobileOpen(!mobileOpen) }}
            className="p-1.5 rounded-md hover:bg-accent text-muted-foreground"
          >
            {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </button>

          <div className="flex-1" />

          {/* Branch badge */}
          <div className="hidden sm:flex items-center gap-1.5 text-xs bg-muted px-2.5 py-1.5 rounded-md text-muted-foreground">
            <Building2 className="w-3.5 h-3.5" />
            <span>{session?.user?.branchName || 'Branch'}</span>
          </div>

          {/* Notifications */}
          <div ref={notifRef} className="relative">
            <button onClick={() => setNotifOpen(!notifOpen)} className="relative p-2 rounded-md hover:bg-accent text-muted-foreground">
              <Bell className="w-5 h-5" />
              {(notifData?.total ?? 0) > 0 && (
                <span className="absolute -top-0.5 -right-0.5 w-4 h-4 bg-destructive text-destructive-foreground text-[10px] font-bold rounded-full flex items-center justify-center">
                  {notifData!.total > 9 ? '9+' : notifData!.total}
                </span>
              )}
            </button>
            {notifOpen && (
              <div className="absolute right-0 top-full mt-1 w-72 bg-card border rounded-xl shadow-xl z-50 overflow-hidden">
                <div className="px-4 py-3 border-b font-medium text-sm flex items-center justify-between">
                  <span>Notifications</span>
                  {notifData && <span className="text-xs text-muted-foreground">{notifData.total} pending</span>}
                </div>
                <div className="py-1 max-h-64 overflow-y-auto">
                  {!notifData?.items.length ? (
                    <p className="px-4 py-6 text-sm text-muted-foreground text-center">All clear — no pending items.</p>
                  ) : notifData.items.map(item => (
                    <Link key={item.label} href={item.href} onClick={() => setNotifOpen(false)}
                      className="flex items-center justify-between px-4 py-2.5 hover:bg-accent text-sm transition-colors"
                    >
                      <span>{item.label}</span>
                      <span className="bg-destructive/10 text-destructive text-xs font-bold px-2 py-0.5 rounded-full">{item.count}</span>
                    </Link>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Profile */}
          <div ref={profileRef} className="relative">
            <button onClick={() => setProfileOpen(!profileOpen)}
              className="flex items-center gap-2 rounded-lg p-1.5 hover:bg-accent"
            >
              <div className="w-7 h-7 bg-primary rounded-full flex items-center justify-center text-primary-foreground text-xs font-bold">
                {userInitials}
              </div>
            </button>
            {profileOpen && (
              <div className="absolute right-0 top-full mt-1 w-48 bg-card border rounded-xl shadow-xl z-50 overflow-hidden">
                <div className="px-4 py-2.5 border-b">
                  <p className="text-sm font-medium truncate">{session?.user?.name}</p>
                  <p className="text-xs text-muted-foreground truncate">{session?.user?.email}</p>
                </div>
                <div className="py-1">
                  <Link href="/profile" onClick={() => setProfileOpen(false)}
                    className="flex items-center gap-2 px-4 py-2 text-sm hover:bg-accent transition-colors">
                    <User className="w-3.5 h-3.5" /> View Profile
                  </Link>
                  <button onClick={() => signOut({ callbackUrl: '/login' })}
                    className="flex items-center gap-2 w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors">
                    <LogOut className="w-3.5 h-3.5" /> Sign Out
                  </button>
                </div>
              </div>
            )}
          </div>
        </header>

        {/* Page content */}
        <main className="flex-1 overflow-auto">
          {children}
        </main>
      </div>
    </div>
  )
}
