import { Link, usePage } from "@inertiajs/react";
import { useState, useEffect } from "react";

export default function MainLayout({ children }) {
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [isMobile, setIsMobile] = useState(false);
    const { url } = usePage();

    const menus = [
        { name: "Dashboard", href: "/", icon: "🏠" },
        { name: "Buku", href: "/buku", icon: "📚" },
        { name: "Kategori", href: "/kategori", icon: "🏷️" },
        { name: "Anggota", href: "/anggota", icon: "👥" },
        { name: "Peminjaman", href: "/peminjaman", icon: "📋" },
    ];

    // Deteksi ukuran layar
    useEffect(() => {
        const checkScreen = () => {
            const mobile = window.innerWidth < 1024;
            setIsMobile(mobile);
            // Sidebar terbuka default di desktop, tertutup di mobile/tablet
            if (!mobile) {
                setSidebarOpen(true);
            } else {
                setSidebarOpen(false);
            }
        };

        checkScreen();
        window.addEventListener("resize", checkScreen);
        return () => window.removeEventListener("resize", checkScreen);
    }, []);

    // Tutup sidebar saat navigasi di mobile
    const handleMenuClick = () => {
        if (isMobile) setSidebarOpen(false);
    };

    return (
        <div className="flex h-screen bg-gray-100 overflow-hidden">
            {/* Overlay untuk mobile/tablet */}
            {isMobile && sidebarOpen && (
                <div
                    className="fixed inset-0 bg-black bg-opacity-50 z-20 lg:hidden"
                    onClick={() => setSidebarOpen(false)}
                />
            )}

            {/* Sidebar */}
            <aside
                className={`
                    ${
                        isMobile
                            ? `fixed inset-y-0 left-0 z-30 w-64 transform transition-transform duration-300 ease-in-out
                           ${sidebarOpen ? "translate-x-0" : "-translate-x-full"}`
                            : `relative shrink-0 transition-all duration-300
                           ${sidebarOpen ? "w-64" : "w-16"}`
                    }
                    bg-indigo-800 text-white flex flex-col
                `}
            >
                {/* Sidebar Header */}
                <div className="flex items-center justify-between p-4 border-b border-indigo-700 min-h-16">
                    {sidebarOpen && (
                        <h1 className="text-lg font-bold truncate">
                            📖 Perpustakaanku
                        </h1>
                    )}
                    {/* Tombol tutup di mobile */}
                    {isMobile ? (
                        <button
                            onClick={() => setSidebarOpen(false)}
                            className="p-2 rounded-lg hover:bg-indigo-700 ml-auto"
                        >
                            ✕
                        </button>
                    ) : (
                        <button
                            onClick={() => setSidebarOpen(!sidebarOpen)}
                            className="p-2 rounded-lg hover:bg-indigo-700 ml-auto shrink-0"
                        >
                            {/* Hamburger icon */}
                            <div className="w-5 h-4 flex flex-col justify-between">
                                <span className="block w-full h-0.5 bg-white"></span>
                                <span className="block w-full h-0.5 bg-white"></span>
                                <span className="block w-full h-0.5 bg-white"></span>
                            </div>
                        </button>
                    )}
                </div>

                {/* Menu Navigasi */}
                <nav className="flex-1 p-2 space-y-1 overflow-y-auto">
                    {menus.map((menu) => (
                        <Link
                            key={menu.href}
                            href={menu.href}
                            onClick={handleMenuClick}
                            className={`flex items-center gap-3 px-3 py-3 rounded-lg transition-colors ${
                                url === menu.href
                                    ? "bg-indigo-600 text-white"
                                    : "hover:bg-indigo-700 text-indigo-200"
                            }`}
                        >
                            <span className="text-xl shrink-0">
                                {menu.icon}
                            </span>
                            {(sidebarOpen || isMobile) && (
                                <span className="font-medium text-sm">
                                    {menu.name}
                                </span>
                            )}
                        </Link>
                    ))}
                </nav>

                {/* Sidebar Footer */}
                {(sidebarOpen || isMobile) && (
                    <div className="p-4 border-t border-indigo-700">
                        <p className="text-xs text-indigo-300 text-center">
                            © {new Date().getFullYear()} Perpustakaanku
                        </p>
                    </div>
                )}
            </aside>

            {/* Main Content */}
            <div className="flex-1 flex flex-col overflow-hidden min-w-0">
                {/* Header */}
                <header className="bg-white shadow-sm px-4 py-3 flex items-center justify-between shrink-0 min-h-16">
                    <div className="flex items-center gap-3">
                        {/* Hamburger Menu - hanya tampil di mobile/tablet */}
                        {isMobile && (
                            <button
                                onClick={() => setSidebarOpen(!sidebarOpen)}
                                className="p-2 rounded-lg hover:bg-gray-100 text-gray-600 transition-colors"
                            >
                                <div className="w-5 h-4 flex flex-col justify-between">
                                    <span className="block w-full h-0.5 bg-gray-600"></span>
                                    <span className="block w-full h-0.5 bg-gray-600"></span>
                                    <span className="block w-full h-0.5 bg-gray-600"></span>
                                </div>
                            </button>
                        )}
                        <h2 className="text-base font-semibold text-gray-700 hidden sm:block">
                            Sistem Perpustakaanku
                        </h2>
                        <h2 className="text-base font-semibold text-gray-700 sm:hidden">
                            Perpustakaanku
                        </h2>
                    </div>

                    <span className="text-xs text-gray-500 hidden md:block">
                        📅{" "}
                        {new Date().toLocaleDateString("id-ID", {
                            weekday: "long",
                            year: "numeric",
                            month: "long",
                            day: "numeric",
                        })}
                    </span>

                    {/* Tanggal singkat untuk mobile */}
                    <span className="text-xs text-gray-500 md:hidden">
                        📅{" "}
                        {new Date().toLocaleDateString("id-ID", {
                            day: "numeric",
                            month: "short",
                            year: "numeric",
                        })}
                    </span>
                </header>

                {/* Flash Message */}
                <FlashMessage />

                {/* Content */}
                <main className="flex-1 overflow-y-auto p-4 md:p-6">
                    {children}
                </main>
            </div>

            {/* Bottom Navigation Bar - Khusus Mobile */}
            {isMobile && (
                <nav className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 z-20 lg:hidden">
                    <div className="flex items-center justify-around py-2">
                        {menus.map((menu) => (
                            <Link
                                key={menu.href}
                                href={menu.href}
                                className={`flex flex-col items-center gap-1 px-3 py-1 rounded-lg transition-colors ${
                                    url === menu.href
                                        ? "text-indigo-600"
                                        : "text-gray-500 hover:text-indigo-500"
                                }`}
                            >
                                <span className="text-xl">{menu.icon}</span>
                                <span className="text-xs font-medium">
                                    {menu.name}
                                </span>
                            </Link>
                        ))}
                    </div>
                </nav>
            )}
        </div>
    );
}

function FlashMessage() {
    const { flash } = usePage().props;
    const [visible, setVisible] = useState(true);

    // Auto hide setelah 4 detik
    useEffect(() => {
        if (flash?.success || flash?.error) {
            setVisible(true);
            const timer = setTimeout(() => setVisible(false), 4000);
            return () => clearTimeout(timer);
        }
    }, [flash]);

    if (!visible) return null;
    if (!flash?.success && !flash?.error) return null;

    return (
        <div className="mx-4 md:mx-6 mt-4 space-y-2">
            {flash?.success && (
                <div className="p-3 md:p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                        <span>✅</span>
                        <span className="text-sm">{flash.success}</span>
                    </div>
                    <button
                        onClick={() => setVisible(false)}
                        className="text-green-500 hover:text-green-700 shrink-0"
                    >
                        ✕
                    </button>
                </div>
            )}
            {flash?.error && (
                <div className="p-3 md:p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                        <span>❌</span>
                        <span className="text-sm">{flash.error}</span>
                    </div>
                    <button
                        onClick={() => setVisible(false)}
                        className="text-red-500 hover:text-red-700 shrink-0"
                    >
                        ✕
                    </button>
                </div>
            )}
        </div>
    );
}
