import { Link } from '@inertiajs/react';
import type { PropsWithChildren} from 'react';
import { useState } from 'react';
import { dashboard, profile } from '@/routes';

interface Props extends PropsWithChildren {
    header?: React.ReactNode;
}

// ─── App list for switcher ────────────────────────────────────────────────────
const SWITCH_APPS = [
    {
        id: 'auth',
        name: 'GMP Auth',
        description: 'Identity & SSO',
        url: import.meta.env.VITE_AUTH_APP_URL || 'http://localhost:8000',
        current: false,
        bg: 'bg-indigo-600',
    },
    {
        id: 'gfin',
        name: 'GMP Finance',
        description: 'Keuangan & Akuntansi',
        url: '#',
        current: true,
        bg: 'bg-emerald-600',
    },
    {
        id: 'portal',
        name: 'Portal',
        description: 'Customer Portal',
        url: import.meta.env.VITE_PORTAL_APP_URL || 'http://localhost:8001',
        current: false,
        bg: 'bg-blue-500',
        disabled: true,
    },
    {
        id: 'gris',
        name: 'GRIS',
        description: 'Governance & Risk',
        url: import.meta.env.VITE_GRIS_APP_URL || 'http://localhost:8003',
        current: false,
        bg: 'bg-orange-500',
        disabled: true,
    },
    {
        id: 'glims',
        name: 'GLIMS',
        description: 'Lab Information Management',
        url: import.meta.env.VITE_GLIMS_APP_URL || 'http://localhost:8004',
        current: false,
        bg: 'bg-teal-600',
    },
    {
        id: 'gwin',
        name: 'GWIN',
        description: 'Warehouse & Inventory',
        url: import.meta.env.VITE_GWIN_APP_URL || 'http://localhost:8006',
        current: false,
        bg: 'bg-amber-600',
    },
] as const;

/**
 * Layout untuk halaman yang memerlukan autentikasi — Finance app.
 * Tema: Emerald (Keuangan)
 */
export default function AuthenticatedLayout({ header, children }: Props) {
    const [switcherOpen, setSwitcherOpen] = useState(false);

    return (
        <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
            {/* Navigation */}
            <nav className="border-b border-emerald-100 bg-white dark:border-emerald-900/30 dark:bg-gray-800">
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    <div className="flex h-16 items-center justify-between">

                        {/* Left — Brand */}
                        <div className="flex items-center gap-4">
                            <Link href={dashboard.url()} className="flex items-center gap-2.5 group">
                                <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-600 shadow-sm group-hover:bg-emerald-700 transition-colors">
                                    <svg className="text-white" style={{width:'18px',height:'18px'}} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                </div>
                                <div className="leading-none">
                                    <span className="block text-sm font-semibold text-gray-900 dark:text-gray-100">
                                        {import.meta.env.VITE_APP_NAME || 'Finance'}
                                    </span>
                                    <span className="block text-xs text-emerald-500 font-mono">
                                        localhost:8002
                                    </span>
                                </div>
                            </Link>

                            {/* Nav links */}
                            <div className="hidden items-center gap-1 sm:flex ml-2">
                                <NavLink href={dashboard.url()} label="Dashboard" />
                            </div>
                        </div>

                        {/* Right — App switcher + user actions */}
                        <div className="flex items-center gap-3">

                            {/* App Switcher */}
                            <div className="relative">
                                <button
                                    onClick={() => setSwitcherOpen((o) => !o)}
                                    className="flex items-center gap-1.5 rounded-lg border border-gray-200 bg-gray-50 px-3 py-1.5 text-xs font-medium text-gray-600 hover:bg-white hover:border-emerald-300 hover:text-emerald-600 transition-colors dark:border-gray-700 dark:bg-gray-700 dark:text-gray-300 dark:hover:border-emerald-700 dark:hover:text-emerald-400"
                                >
                                    <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" />
                                    </svg>
                                    Aplikasi
                                    <svg className={`h-3 w-3 transition-transform ${switcherOpen ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                                    </svg>
                                </button>

                                {switcherOpen && (
                                    <>
                                        {/* Backdrop */}
                                        <div className="fixed inset-0 z-10" onClick={() => setSwitcherOpen(false)} />
                                        {/* Dropdown */}
                                        <div className="absolute right-0 top-full z-20 mt-2 w-64 rounded-xl border border-gray-200 bg-white p-2 shadow-lg dark:border-gray-700 dark:bg-gray-800">
                                            <p className="px-2 pb-1.5 pt-1 text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500">
                                                GMP Platform
                                            </p>
                                            {SWITCH_APPS.map((app) => (
                                                <SwitcherItem key={app.id} app={app} />
                                            ))}
                                        </div>
                                    </>
                                )}
                            </div>

                            <Link
                                href={profile.url()}
                                className="text-sm text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100"
                            >
                                Profile
                            </Link>
                            {/* Logout goes to SSO auth server logout */}
                            <a
                                href={(import.meta.env.VITE_AUTH_APP_URL || 'http://localhost:8000') + '/logout'}
                                className="rounded-md bg-emerald-50 px-3 py-1.5 text-sm font-medium text-emerald-600 hover:bg-emerald-100 dark:bg-emerald-900/30 dark:text-emerald-400 dark:hover:bg-emerald-900/50"
                            >
                                Logout
                            </a>
                        </div>
                    </div>
                </div>
            </nav>

            {/* Page Header */}
            {header && (
                <header className="bg-white shadow-sm dark:bg-gray-800">
                    <div className="mx-auto max-w-7xl px-4 py-5 sm:px-6 lg:px-8">{header}</div>
                </header>
            )}

            {/* Content */}
            <main>{children}</main>
        </div>
    );
}

// ─── NavLink ──────────────────────────────────────────────────────────────────
function NavLink({ href, label }: { href: string; label: string }) {
    const active =
        (window.location.pathname.startsWith(href) && href !== '/dashboard') ||
        window.location.pathname === href;

    return (
        <Link
            href={href}
            className={`rounded-md px-3 py-2 text-sm font-medium transition-colors ${
                active
                    ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300'
                    : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-100'
            }`}
        >
            {label}
        </Link>
    );
}

// ─── SwitcherItem ─────────────────────────────────────────────────────────────
function SwitcherItem({ app }: { app: (typeof SWITCH_APPS)[number] }) {
    const isDisabled = 'disabled' in app && app.disabled;

    const inner = (
        <div
            className={`flex items-center gap-3 rounded-lg px-2 py-2 transition-colors ${
                app.current
                    ? 'bg-emerald-50 dark:bg-emerald-900/30'
                    : isDisabled
                    ? 'opacity-50 cursor-not-allowed'
                    : 'hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer'
            }`}
        >
            <div className={`flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md ${app.bg}`}>
                <span className="h-2 w-2 rounded-full bg-white/80" />
            </div>
            <div className="min-w-0 flex-1">
                <p className={`text-sm font-medium ${app.current ? 'text-emerald-700 dark:text-emerald-300' : 'text-gray-700 dark:text-gray-200'}`}>
                    {app.name}
                </p>
                <p className="truncate text-xs text-gray-400 dark:text-gray-500">{app.description}</p>
            </div>
            {app.current && (
                <span className="flex-shrink-0 text-xs font-medium text-emerald-500">✓</span>
            )}
            {isDisabled && (
                <span className="flex-shrink-0 rounded-full bg-gray-100 px-1.5 py-0.5 text-xs text-gray-400 dark:bg-gray-700">
                    Soon
                </span>
            )}
        </div>
    );

    if (app.current || isDisabled) {
return inner;
}

    return (
        <a href={app.url} className="block">
            {inner}
        </a>
    );
}
