import React, { useState } from 'react';
import { usePage, Link } from '@inertiajs/react';

// ================================================================
// FONT AWESOME IMPORTS
// ================================================================
import {
    faTachometerAlt,
    faCog,
    faUsers,
    faChevronDown,
    faUser,
    faSignOutAlt,
    faTimes,
    faBars,
    faGraduationCap,
    faBuilding,
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

// ================================================================
// KOMPONEN PEMBANTU INTERNAL
// ================================================================

// 1. ApplicationLogo Component
const ApplicationLogo = ({ className = 'w-10 h-10 fill-current text-gray-500' }) => (
    <div className={className}>
        <FontAwesomeIcon icon={faGraduationCap} className="w-full h-full text-indigo-300" />
    </div>
);

// 2. SidebarLink Component
// Menerima 'icon' sebagai objek Font Awesome, dan 'href' sebagai nama rute (dinamis), path statis ('#'), atau URL penuh.
const SidebarLink = ({ href, active, children, icon, method = 'get', as = 'a' }) => {
    // Fungsi untuk menentukan apakah rute aktif. Menggunakan fallback '#' jika route() tidak tersedia.
    const getRouteUrl = (name) => {
        // Cek jika ini adalah URL penuh (dimulai dengan http atau /)
        if (name.startsWith('http') || name.startsWith('/')) {
            return name;
        }

        // Rute dinamis: dashboard, profile.edit, logout, admin.super.dashboard
        if (['dashboard', 'profile.edit', 'logout', 'admin.super.dashboard'].includes(name)) {
            // Gunakan fungsi route() jika tersedia
            return typeof route === 'function' ? route(name) : `/${name.replace(/\./g, '/')}`;
        }
        
        // Rute statis (untuk tujuan demo agar tidak error Ziggy atau link yang belum ada rutenya)
        return '#';
    };

    const isRouteActive = (name) => {
        // Cek rute aktif hanya jika fungsi route() tersedia.
        // Untuk link statis, kita asumsikan tidak aktif untuk demo ini kecuali kita cek window.location
        // Kita biarkan logika Inertia.js dan Laravel/Ziggy yang menentukan.
        return typeof route === 'function' && route().current(name);
    }
    
    // Untuk 'Data Kampus' yang menggunakan URL statis, kita tidak bisa menggunakan isRouteActive berbasis Ziggy.
    // Kita akan gunakan properti 'active' yang dikirim dari parent (AuthenticatedLayout) untuk mengontrol styling.
    const isActive = isRouteActive(href) || active; // Menggabungkan cek Ziggy dan properti 'active'

    const baseClasses = 'flex items-center space-x-3 w-full py-2 px-4 text-sm font-medium rounded-lg transition duration-150 ease-in-out';
    const activeClasses = 'bg-indigo-700 text-white shadow-md';
    const inactiveClasses = 'text-indigo-200 hover:bg-indigo-800 hover:text-white';

    const finalHref = getRouteUrl(href);

    return (
        <Link
            href={finalHref}
            method={method}
            as={as}
            // Karena ini adalah link statis yang mungkin tidak dikenali Ziggy, kita gunakan kelas aktif jika prop 'active' true
            className={`${baseClasses} ${isActive ? activeClasses : inactiveClasses}`}
        >
            {icon && <FontAwesomeIcon icon={icon} className="w-5 h-5 flex-shrink-0" />}
            <span>{children}</span>
        </Link>
    );
};


// 3. Dropdown Components
const Dropdown = ({ children }) => {
    const [open, setOpen] = useState(false);
    const toggleOpen = () => setOpen((prev) => !prev);

    return (
        <div className="relative">
            <div onClick={toggleOpen}>
                {children[0]} {/* Trigger */}
            </div>
            {open && (
                <div
                    className="fixed inset-0 z-40"
                    onClick={() => setOpen(false)}
                />
            )}
            {open && (
                <div className="absolute right-0 mt-2 w-48 rounded-xl shadow-2xl bg-white ring-1 ring-black ring-opacity-5 z-50 transform origin-top-right">
                    <div className="py-1" role="menu" aria-orientation="vertical" aria-labelledby="user-menu-button">
                        {children.slice(1)} {/* Content */}
                    </div>
                </div>
            )}
        </div>
    );
};

Dropdown.Trigger = ({ children }) => children;
Dropdown.Content = ({ children }) => children;

Dropdown.Link = ({ href, method = 'get', as = 'a', children, className = '' }) => {
    const baseClasses = 'block w-full text-left px-4 py-2 text-sm leading-5 text-gray-700 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 transition duration-150 ease-in-out';
    
    // Khusus untuk Dropdown Link, kita asumsikan ini rute dinamis (profile.edit, logout)
    const finalHref = typeof route === 'function' ? route(href) : `/${href.replace(/\./g, '/')}`;

    return (
        <Link
            href={finalHref}
            method={method}
            as={as}
            className={`${baseClasses} ${className}`}
        >
            {children}
        </Link>
    );
};


// ================================================================
// KOMPONEN UTAMA: AUTHENTICATED LAYOUT (KHUSUS SUPERADMIN)
// ================================================================

export default function AuthenticatedLayout({ header, children }) {
    
    const { props } = usePage();
    
    // Ambil data user, beri fallback 'Superadmin' dan roleName 'Superadmin'
    const user = props.auth && props.auth.user
        ? props.auth.user
        : { name: 'Super Admin User', email: 'superadmin@pmb.local', role_name: 'Superadmin' };
    
    // ROLE HACK: Mengambil role dari props, jika tidak ada, default ke 'Superadmin'
    const roleName = user.role_name || 'Superadmin';

    const normalizedRole = roleName ? String(roleName).toLowerCase().replace(/\s/g, '') : 'guest';
    const EXPECTED_ROLE = 'superadmin';
    
    const [showingSidebar, setShowingSidebar] = useState(false);

    const mainDashboardRouteName = 'admin.super.dashboard';
    
    // --- Penambahan Logika Baru untuk Rute Statis Data Kampus ---
    const campusManagementUrl = 'http://localhost:8000/admin/super/kampus';
    
    // Fungsi untuk memeriksa apakah URL saat ini cocok dengan URL Data Kampus
    const isCampusManagementActive = window.location.href.includes(campusManagementUrl); 


    // --- Penambahan Logika Baru untuk Rute Statis Data Kampus ---
    const userManagementUrl = 'http://localhost:8000/admin/super/users';
    
    // Fungsi untuk memeriksa apakah URL saat ini cocok dengan URL Data Kampus
    const isUserManagementActive = window.location.href.includes(userManagementUrl); 
    

    // Pengecekan Aktivitas Rute dengan Fallback
    const isRouteActive = (name) => {
        // Cek apakah fungsi route() tersedia (dari Ziggy)
        return typeof route === 'function' && route().current(name);
    }
    const isDashboardActive = isRouteActive(mainDashboardRouteName);
    
    // Logika Akses Ditolak (Dipertahankan untuk Keamanan)
    if (normalizedRole !== EXPECTED_ROLE) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-50 font-sans">
                <div className="p-10 bg-white rounded-xl shadow-2xl text-center max-w-lg mx-auto">
                    <h1 className="text-4xl font-extrabold text-red-600 mb-4">AKSES DITOLAK 🚫</h1>
                    <p className="text-lg text-gray-700">Layout ini hanya dapat diakses oleh **Superadmin**.</p>
                    <p className="text-sm text-gray-500 mt-2">Sistem mendeteksi peran Anda sebagai: <span className="font-mono bg-yellow-100 text-yellow-800 px-2 py-1 rounded-md">{roleName}</span>.</p>
                    <p className="mt-6">
                        <Link
                            href={typeof route === 'function' ? route('dashboard') : '/dashboard'}
                            className="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-lg font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-150 shadow-lg"
                        >
                            Kembali ke Dashboard Umum
                        </Link>
                    </p>
                </div>
            </div>
        );
    }
    
    // Konfigurasi Navigasi Superadmin
    const navigationLinks = (
        <div className="space-y-1">
            {/* 1. Dashboard - Rute Dinamis */}
            <SidebarLink
                href={mainDashboardRouteName}
                active={isDashboardActive}
                icon={faTachometerAlt}
            >
                Dashboard
            </SidebarLink>

            <div className="mt-4 pt-4 border-t border-indigo-700">
                <p className="text-xs uppercase text-indigo-400 font-semibold mb-2 px-4 tracking-wider">Superadmin Tools</p>
                
                {/* 2. Pengaturan Sistem - Rute Statis
                <SidebarLink
                    href='admin.super.settings' // Gunakan '#' sebagai href di komponen SidebarLink
                    active={isRouteActive('admin.super.settings')}
                    icon={faCog}
                >
                    Pengaturan Sistem
                </SidebarLink> */}
                
                {/* 3. Manajemen Pengguna - Rute Statis */}
                <SidebarLink
                    href={userManagementUrl} // Gunakan '#' sebagai href di komponen SidebarLink
                    active={isUserManagementActive}
                    icon={faUsers}
                >
                    Manajemen Pengguna
                </SidebarLink>

                {/* ====================================================
                    --- PENAMBAHAN BARU: DATA KAMPUS ---
                    --- Menggunakan URL Penuh yang diminta ---
                    ====================================================
                */}
                <SidebarLink
                    href={campusManagementUrl} // URL penuh: http://localhost:8000/admin/super/kampus
                    active={isCampusManagementActive} // Menggunakan logika cek URL baru
                    icon={faBuilding}
                >
                    Data Kampus
                </SidebarLink>
                
            </div>
        </div>
    );

    // ================================================================
    // TATA LETAK UTAMA
    // ================================================================

    return (
        <div className="min-h-screen bg-gray-50 lg:grid lg:grid-cols-[280px_1fr] font-sans">
            {/* 1. SIDEBAR (Desktop Fixed) */}
            <aside className="hidden lg:flex lg:flex-col lg:w-[280px] bg-indigo-900 min-h-screen p-6 text-white fixed top-0 left-0 z-40 shadow-2xl">
                
                {/* Logo & Role */}
                <div className="flex flex-col items-start space-y-1 mb-8 border-b border-indigo-700 pb-4">
                    <Link href={typeof route === 'function' ? route(mainDashboardRouteName) : '/admin/super'} className="block">
                        <ApplicationLogo className="block h-10 w-auto fill-current" />
                    </Link>
                    <span className="text-xs uppercase text-indigo-300 font-semibold mt-2">Masuk Sebagai:</span>
                    <span className="text-lg font-bold tracking-tight">{roleName}</span>
                </div>
                
                <div className="flex-1 overflow-y-auto pr-2">
                    {navigationLinks}
                </div>

                {/* Info Pengguna Dasar */}
                <div className="mt-6 pt-4 border-t border-indigo-700">
                    <div className="text-sm font-semibold text-indigo-200">{user.name}</div>
                    <div className="text-xs text-indigo-400">{user.email}</div>
                </div>
            </aside>

            {/* 2. MAIN CONTENT AREA */}
            <div className="lg:col-start-2 w-full flex flex-col">
                
                {/* ====================================================
                    --- A. TOP NAVBAR (Sekarang termasuk Page Header) ---
                    ====================================================
                */}
                <nav className="bg-white border-b border-gray-100 shadow-lg z-30 h-16 flex items-center">
                    <div className="max-w-full mx-auto px-4 sm:px-6 lg:px-8 w-full">
                        <div className="flex justify-between items-center h-full">
                            
                            {/* Kiri: Title (Dashboard Super Admin) & Mobile Logo/Title */}
                            <div className="flex items-center">
                                {/* Desktop Title */}
                                <h1 className="hidden lg:block text-xl font-bold text-gray-900 mr-8">
                                    {header || `Dashboard ${roleName}`}
                                </h1>
                                
                                {/* Mobile Logo & Title */}
                                <div className="flex items-center lg:hidden">
                                    <Link href={typeof route === 'function' ? route(mainDashboardRouteName) : '/admin/super'} className="block text-indigo-800">
                                        <ApplicationLogo className="block h-8 w-auto fill-current" />
                                    </Link>
                                    <span className="text-md font-semibold ml-2 text-gray-700">Dashboard</span>
                                </div>
                            </div>
                            
                            {/* Kanan: Profile Dropdown & Mobile Menu Button */}
                            <div className="flex items-center space-x-4">
                                
                                {/* Profile Dropdown */}
                                <div className="flex items-center">
                                    <Dropdown>
                                        <Dropdown.Trigger>
                                            <span className="inline-flex rounded-md">
                                                <button
                                                    type="button"
                                                    className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-xl text-gray-700 bg-gray-50 hover:bg-gray-100 focus:outline-none transition ease-in-out duration-150 shadow-sm"
                                                >
                                                    <span className='hidden sm:inline'>{user.name}</span>
                                                    <span className='sm:hidden font-bold'>Menu</span>

                                                    <FontAwesomeIcon icon={faChevronDown} className="ms-2 h-4 w-4 text-gray-400" />
                                                </button>
                                            </span>
                                        </Dropdown.Trigger>

                                        <Dropdown.Content>
                                            <div className="block px-4 py-2 text-xs text-gray-400 border-b mb-2">Role: {roleName}</div>
                                            {/* 1. Link Profile: Rute Dinamis */}
                                            <Dropdown.Link href='profile.edit' className="flex items-center">
                                                <FontAwesomeIcon icon={faUser} className="mr-2 w-5 h-5 text-gray-500" />
                                                Profile
                                            </Dropdown.Link>
                                            {/* 2. Link Logout: Rute Dinamis */}
                                            <Dropdown.Link
                                                href='logout'
                                                method="post"
                                                as="button"
                                                className="flex items-center text-red-600 hover:text-white hover:bg-red-500 rounded-b-md"
                                            >
                                                <FontAwesomeIcon icon={faSignOutAlt} className="mr-2 w-5 h-5" />
                                                Log Out
                                            </Dropdown.Link>
                                        </Dropdown.Content>
                                    </Dropdown>
                                </div>

                                {/* Mobile Menu Button */}
                                <div className="flex items-center lg:hidden -mr-2">
                                    <button
                                        onClick={() => setShowingSidebar((previousState) => !previousState)}
                                        className="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out"
                                    >
                                        {showingSidebar ? (
                                            <FontAwesomeIcon icon={faTimes} className="h-6 w-6" />
                                        ) : (
                                            <FontAwesomeIcon icon={faBars} className="h-6 w-6" />
                                        )}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* --- B. MOBILE SIDEBAR DRAWER --- */}
                    {showingSidebar && (
                        <div className="lg:hidden fixed inset-0 z-40 bg-black bg-opacity-50 transition-opacity duration-300 ease-in-out" onClick={() => setShowingSidebar(false)}>
                            <div className="w-[280px] bg-indigo-900 min-h-screen p-6 text-white shadow-2xl" onClick={e => e.stopPropagation()}>
                                
                                <div className="flex justify-between items-center mb-6 border-b border-indigo-700 pb-4">
                                    <div className="flex flex-col">
                                        <Link href={typeof route === 'function' ? route(mainDashboardRouteName) : '/admin/super'} className="block text-indigo-300">
                                            <ApplicationLogo className="block h-8 w-auto fill-current" />
                                        </Link>
                                        <span className="text-sm font-bold mt-2">Role: {roleName}</span>
                                    </div>
                                    <button onClick={() => setShowingSidebar(false)} className="text-indigo-300 hover:text-white p-2 rounded-full">
                                        <FontAwesomeIcon icon={faTimes} className="h-6 w-6" />
                                    </button>
                                </div>

                                <div className="space-y-1 overflow-y-auto max-h-[70vh]">
                                    {navigationLinks}
                                </div>

                                <div className="mt-8 pt-4 border-t border-indigo-700">
                                    <div className="font-medium text-sm text-indigo-200 mb-2">{user.name} ({user.email})</div>
                                    {/* Link Profile: Rute Dinamis */}
                                    <Link href={typeof route === 'function' ? route('profile.edit') : '/profile'} className="flex items-center space-x-2 w-full py-2 px-4 text-sm font-medium rounded-lg text-indigo-100 hover:bg-indigo-700 transition duration-150 ease-in-out">
                                        <FontAwesomeIcon icon={faUser} className="w-5 h-5" />
                                        <span>Profile</span>
                                    </Link>
                                    {/* Link Logout: Rute Dinamis */}
                                    <Link
                                        href={typeof route === 'function' ? route('logout') : '/logout'}
                                        method="post"
                                        as="button"
                                        className="flex items-center space-x-2 w-full py-2 px-4 text-sm font-medium rounded-lg text-red-300 hover:bg-indigo-700 hover:text-white transition duration-150 ease-in-out mt-1 text-left"
                                    >
                                        <FontAwesomeIcon icon={faSignOutAlt} className="w-5 h-5" />
                                        <span>Log Out</span>
                                    </Link>
                                </div>
                            </div>
                        </div>
                    )}
                </nav>

                {/* --- D. PAGE CONTENT --- */}
                <main className="flex-1 p-4 sm:p-6 lg:p-8">
                    {children}
                </main>
            </div>
        </div>
    );
}