import { Link } from '@inertiajs/react';
import type { PropsWithChildren } from 'react';
import { useState } from 'react';

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: import.meta.env.VITE_GFIN_APP_URL || 'http://localhost:8002',
        current: false,
        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: '#',
        current: true,
        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 — GLIMS app.
 * Tema: Teal (Lab Information Management)
 */
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-teal-100 bg-white dark:border-teal-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="/" className="flex items-center gap-2.5 group">
                                <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-teal-600 shadow-sm group-hover:bg-teal-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="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23-.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0112 21a48.25 48.25 0 01-8.135-.687c-1.718-.293-2.3-2.379-1.067-3.61L5 14.5" />
                                    </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 || 'GLIMS'}
                                    </span>
                                    <span className="block text-xs text-teal-500 font-mono">
                                        localhost:8004
                                    </span>
                                </div>
                            </Link>

                            {/* Nav links */}
                            <div className="hidden items-center gap-1 sm:flex ml-2">
                                <NavLink href="/" 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-teal-300 hover:text-teal-600 transition-colors dark:border-gray-700 dark:bg-gray-700 dark:text-gray-300 dark:hover:border-teal-700 dark:hover:text-teal-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>

                            {/* Logout goes to SSO auth server logout */}
                            <a
                                href={(import.meta.env.VITE_AUTH_APP_URL || 'http://localhost:8000') + '/logout'}
                                className="rounded-md bg-teal-50 px-3 py-1.5 text-sm font-medium text-teal-600 hover:bg-teal-100 dark:bg-teal-900/30 dark:text-teal-400 dark:hover:bg-teal-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 !== '/') ||
        window.location.pathname === href;

    return (
        <a
            href={href}
            className={`rounded-md px-3 py-2 text-sm font-medium transition-colors ${
                active
                    ? 'bg-teal-50 text-teal-700 dark:bg-teal-900/30 dark:text-teal-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}
        </a>
    );
}

// ─── 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-teal-50 dark:bg-teal-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-teal-700 dark:text-teal-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-teal-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>
    );
}
