'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { 
  LayoutDashboard, Users, CreditCard, Receipt, Settings, 
  LogOut, Bell, Menu, X, BookOpen, GraduationCap, FileText, CheckCircle
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { ThemeToggle } from '@/components/theme-toggle';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // Determine role based on URL pattern for the preview
  let roleText = 'Dashboard';
  let badgeColor = 'bg-emerald-100 text-emerald-800';
  let menuItems: any[] = [];

  if (pathname.includes('/admin')) {
    roleText = 'Administrator';
    badgeColor = 'bg-red-100 text-red-800';
    menuItems = [
      { href: '/dashboard/admin', icon: LayoutDashboard, label: 'Dashboard' },
      { href: '/dashboard/admin/users', icon: Users, label: 'Manajemen User' },
      { href: '/dashboard/admin/siswa', icon: GraduationCap, label: 'Manajemen Siswa' },
      { href: '/dashboard/admin/pembayaran', icon: BookOpen, label: 'Jenis Pembayaran' },
      { href: '/dashboard/admin/tagihan', icon: Receipt, label: 'Kelola Tagihan' },
      { href: '/dashboard/admin/laporan', icon: FileText, label: 'Laporan Seluruhnya' },
      { href: '/dashboard/admin/logs', icon: Bell, label: 'Log Aktivitas', badge: '3 New' },
      { href: '/dashboard/admin/settings', icon: Settings, label: 'Pengaturan' },
    ];
  } else if (pathname.includes('/kepala')) {
    roleText = 'Kepala Madrasah';
    badgeColor = 'bg-amber-100 text-amber-800';
    menuItems = [
      { href: '/dashboard/kepala', icon: LayoutDashboard, label: 'Dashboard' },
      { href: '/dashboard/kepala/laporan', icon: FileText, label: 'Laporan & Statistik' },
    ];
  } else if (pathname.includes('/bendahara')) {
    roleText = 'Bendahara';
    badgeColor = 'bg-blue-100 text-blue-800';
    menuItems = [
      { href: '/dashboard/bendahara', icon: LayoutDashboard, label: 'Dashboard' },
      { href: '/dashboard/bendahara/transaksi', icon: CreditCard, label: 'Transaksi' },
      { href: '/dashboard/bendahara/verifikasi', icon: CheckCircle, label: 'Verifikasi Pembayaran' },
      { href: '/dashboard/bendahara/laporan', icon: FileText, label: 'Laporan Keuangan' },
    ];
  } else if (pathname.includes('/wali')) {
    roleText = 'Wali Murid';
    badgeColor = 'bg-purple-100 text-purple-800';
    menuItems = [
      { href: '/dashboard/wali', icon: LayoutDashboard, label: 'Dashboard Siswa' },
      { href: '/dashboard/wali/tagihan', icon: Receipt, label: 'Tagihan Aktif' },
      { href: '/dashboard/wali/riwayat', icon: FileText, label: 'Riwayat Pembayaran' },
    ];
  }

  return (
    <div className="min-h-screen bg-slate-50 flex flex-col md:flex-row font-sans print:block print:bg-white print:min-h-0">
      
      {/* Mobile Header overlay for Sidebar Toggle */}
      <div className="md:hidden flex items-center justify-between p-4 bg-emerald-800 text-white z-50 fixed w-full top-0 print:hidden">
        <div className="flex items-center gap-2">
          <GraduationCap className="h-6 w-6 text-amber-400" />
          <span className="font-bold">MA MAMA e-Pay</span>
        </div>
        <button onClick={() => setSidebarOpen(!sidebarOpen)}>
          {sidebarOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
        </button>
      </div>

      {/* Sidebar Navigation */}
      <aside className={cn(
        "fixed md:static inset-y-0 left-0 z-40 w-60 bg-[#064E3B] text-white transform transition-transform duration-300 flex flex-col pt-16 md:pt-0 print:hidden",
        sidebarOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
      )}>
        <div className="flex flex-col h-full">
          {/* Desktop Logo */}
          <div className="hidden md:flex items-center gap-3 p-6 border-b border-emerald-800/50 mb-4">
            <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center">
              <GraduationCap className="h-6 w-6 text-emerald-700" />
            </div>
            <div className="leading-tight">
              <span className="font-bold text-white text-sm tracking-tight block">e-Payment</span>
              <span className="text-[10px] text-emerald-300 uppercase font-semibold">MA Mamba'ul Ma'arif</span>
            </div>
          </div>

          {/* Navigation Links */}
          <div className="flex-1 space-y-1 px-3">
            <p className="px-3 text-[10px] uppercase text-emerald-400 font-bold mb-2 tracking-wider mt-4">Menu Utama</p>
            {menuItems.map((item) => {
              const isActive = pathname === item.href || (pathname.startsWith(item.href) && item.href !== `/dashboard/${roleText.toLowerCase()}`);
              return (
                <Link 
                  key={item.href} 
                  href={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={cn(
                    "flex items-center gap-3 px-3 py-2 text-sm font-medium transition-colors",
                    isActive 
                      ? "bg-emerald-800/50 border-l-4 border-amber-500 rounded-r-md text-white" 
                      : "text-emerald-100 hover:bg-emerald-800/30 rounded-md"
                  )}
                >
                  <item.icon className={cn("h-4 w-4 shrink-0", isActive ? "text-white" : "text-emerald-100")} />
                  <span className="flex-1 truncate">{item.label}</span>
                  {item.badge && (
                    <span className={cn(
                      "px-2 py-0.5 text-[10px] font-bold rounded-full",
                      isActive ? "bg-amber-500 text-emerald-950" : "bg-red-500 text-white"
                    )}>
                      {item.badge}
                    </span>
                  )}
                </Link>
              );
            })}
          </div>

          {/* Logout Section */}
          <div className="p-4 bg-emerald-950 mt-auto flex items-center gap-3 border-t border-emerald-900">
            <Link 
              href="/"
              className="flex items-center gap-3 w-full text-sm font-medium text-emerald-400 hover:text-white transition-colors"
            >
              <LogOut className="h-4 w-4" />
              Keluar Sistem
            </Link>
          </div>
        </div>
      </aside>

      {/* Main Content Area */}
      <main className="flex-1 flex flex-col min-w-0 md:pt-0 pt-16 print:pt-0 print:block">
        
        {/* Top Navbar */}
        <header className="bg-white border-b border-slate-200 h-16 flex items-center justify-between px-6 shrink-0 sticky top-0 z-30 hidden md:flex print:hidden">
          <div className="flex items-center">
            <span className={cn("px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wide", badgeColor)}>
              Mode: {roleText}
            </span>
          </div>
          
          <div className="flex items-center gap-5">
            <ThemeToggle />
            <button className="relative text-slate-400 hover:text-emerald-700 transition-colors">
              <Bell className="h-5 w-5" />
              <span className="absolute top-0 right-0 h-2.5 w-2.5 bg-red-500 border-2 border-white rounded-full"></span>
            </button>
            
            <div className="flex items-center gap-3 pl-5 border-l border-slate-200">
              <div className="text-right hidden lg:block">
                <p className="text-sm font-semibold text-slate-800 leading-none mb-1">User Aktif</p>
                <p className="text-xs text-slate-500">{roleText}</p>
              </div>
              <div className="h-9 w-9 rounded-full bg-emerald-700 flex items-center justify-center text-white font-bold text-sm">
                {roleText.charAt(0)}
              </div>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <div className="flex-1 p-4 md:p-6 lg:p-8 overflow-auto print:overflow-visible print:p-0 print:m-0">
          {children}
        </div>
      </main>
      
      {/* Mobile overlay backdrop */}
      {sidebarOpen && (
        <div 
          className="fixed inset-0 bg-slate-900/50 z-30 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}
    </div>
  );
}
