'use client'

import { useEffect, useState } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import axios from 'axios'
import { Loader2, LayoutDashboard, CreditCard, FileText, User, LogOut, Building2, Menu, X, ChevronRight } from 'lucide-react'

export default function PortalLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const router = useRouter()
  const [member, setMember] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [sidebarOpen, setSidebarOpen] = useState(false)

  useEffect(() => {
    if (pathname === '/portal/login') { setLoading(false); return }
    axios.get('/api/auth/member/me')
      .then(r => { setMember(r.data.data); setLoading(false) })
      .catch(() => { router.push('/portal/login'); setLoading(false) })
  }, [pathname, router])

  if (pathname === '/portal/login') return children

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    )
  }

  async function handleLogout() {
    await axios.post('/api/auth/member/logout')
    router.push('/portal/login')
  }

  const navItems = [
    { href: '/portal/dashboard', label: 'Dashboard', icon: <LayoutDashboard className="w-4 h-4" /> },
    { href: '/portal/loans', label: 'My Loans', icon: <CreditCard className="w-4 h-4" /> },
    { href: '/portal/savings', label: 'Savings', icon: <FileText className="w-4 h-4" /> },
    { href: '/portal/profile', label: 'My Profile', icon: <User className="w-4 h-4" /> },
  ]

  return (
    <div className="min-h-screen bg-gray-50 flex">
      <aside className={`fixed inset-y-0 left-0 z-40 w-64 bg-white border-r shadow-sm transform transition-transform lg:translate-x-0 lg:static lg:inset-auto ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}>
        <div className="flex items-center justify-between h-16 px-5 border-b">
          <div className="flex items-center gap-2"><Building2 className="w-5 h-5 text-primary" /><span className="font-semibold text-sm">FinServe Portal</span></div>
          <button className="lg:hidden text-muted-foreground" onClick={() => setSidebarOpen(false)}><X className="w-4 h-4" /></button>
        </div>

        <nav className="p-3 space-y-1">
          {navItems.map(item => (
            <a
              key={item.href}
              href={item.href}
              onClick={e => { e.preventDefault(); router.push(item.href); setSidebarOpen(false) }}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${
                pathname === item.href ? 'bg-primary/10 text-primary' : 'text-gray-600 hover:bg-gray-100'
              }`}
            >
              {item.icon}{item.label}
            </a>
          ))}
        </nav>

        <div className="absolute bottom-0 left-0 right-0 p-4 border-t">
          {member && (
            <div className="mb-3 px-3 py-2 bg-gray-50 rounded-lg">
              <p className="text-sm font-medium truncate">{member.fullName}</p>
              <p className="text-xs text-muted-foreground truncate">{member.memberNo}</p>
            </div>
          )}
          <button onClick={handleLogout} className="flex items-center gap-2 w-full px-3 py-2.5 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 transition-colors">
            <LogOut className="w-4 h-4" /> Sign Out
          </button>
        </div>
      </aside>

      {sidebarOpen && <div className="fixed inset-0 bg-black/30 z-30 lg:hidden" onClick={() => setSidebarOpen(false)} />}

      <div className="flex-1 flex flex-col min-h-screen">
        <header className="h-16 bg-white border-b flex items-center justify-between px-4 lg:px-6">
          <button className="lg:hidden text-muted-foreground" onClick={() => setSidebarOpen(true)}><Menu className="w-5 h-5" /></button>
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <span>{member?.fullName}</span>
            <ChevronRight className="w-3 h-3" />
            <span className="text-foreground font-medium">{navItems.find(n => n.href === pathname)?.label ?? 'Dashboard'}</span>
          </div>
        </header>
        <main className="flex-1 p-4 lg:p-6">{children}</main>
      </div>
    </div>
  )
}
