'use client';

import { useEffect } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from './AuthContext';
import Sidebar from './Sidebar';
import MainContent from './MainContent';
import { adminPanelUrl, allowedNavHrefs, canUseKasirApp } from '@/lib/roles';

export default function AppShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const { user, loading, logout } = useAuth();

  // Redirect kasir-only away from finance routes; gudang away from app
  useEffect(() => {
    if (loading || !user || pathname === '/login') return;

    if (!canUseKasirApp(user)) {
      return; // rendered as notice below
    }

    const allowed = allowedNavHrefs(user);
    const path = pathname === '' ? '/' : pathname;
    const ok = allowed.some((href) =>
      href === '/' ? path === '/' : path === href || path.startsWith(`${href}/`)
    );
    if (!ok && allowed.length > 0) {
      router.replace(allowed[0]);
    }
  }, [user, loading, pathname, router]);

  // Login page — no sidebar, no shell
  if (pathname === '/login') {
    return <>{children}</>;
  }

  // Loading state
  if (loading) {
    return (
      <div className="flex h-[100dvh] w-full items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-3">
          <div className="h-10 w-10 animate-spin rounded-full border-3 border-brand-200 border-t-brand-500" />
          <p className="text-sm text-brand-400">Memuat...</p>
        </div>
      </div>
    );
  }

  // Not authenticated — show nothing (AuthContext will redirect)
  if (!user) {
    return null;
  }

  // Gudang should use Filament admin panel, not kasir SPA
  if (!canUseKasirApp(user)) {
    return (
      <div className="flex h-[100dvh] w-full items-center justify-center bg-background px-6">
        <div className="max-w-md w-full rounded-2xl border border-blue-100 bg-white p-8 shadow-lg text-center space-y-4">
          <h1 className="text-lg font-bold text-gray-900">Panel Kasir tidak untuk Gudang</h1>
          <p className="text-sm text-gray-600 leading-relaxed">
            Akun <span className="font-semibold">gudang</span> mengelola stok &amp; PO lewat Admin Panel
            (<span className="font-mono text-xs">/app</span>), bukan aplikasi kasir ecer.
          </p>
          <div className="flex flex-col sm:flex-row gap-2 justify-center pt-2">
            <a
              href={adminPanelUrl()}
              className="inline-flex items-center justify-center rounded-xl bg-blue-900 px-4 py-2.5 text-sm font-semibold text-white hover:bg-blue-800"
            >
              Buka Admin Panel
            </a>
            <button
              type="button"
              onClick={() => logout()}
              className="inline-flex items-center justify-center rounded-xl border border-gray-200 px-4 py-2.5 text-sm font-semibold text-gray-700 hover:bg-gray-50 cursor-pointer"
            >
              Keluar
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Authenticated — full app shell with sidebar
  return (
    <div className="flex flex-col h-[100dvh] w-full">
      <div className="flex-1 flex min-h-0 overflow-hidden relative w-full">
        <Sidebar />
        <MainContent>{children}</MainContent>
      </div>
    </div>
  );
}
