'use client';

import { memo, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Menu } from 'lucide-react';
import { usePathname, useRouter } from '@/i18n/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { storeAuthRedirectFromPath } from '@/lib/auth/postAuthRedirect';
import Sidebar from '@/components/ui/shared/Sidebar';
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccountMenu';
import { NotificationBell } from '@/components/ui/notifications/NotificationBell';
import { ToastProvider } from '@/components/ui/shared/ToastProvider';
import { RealtimeProvider } from '@/lib/realtime/RealtimeProvider';
import {
  canAccessDashboardRoute,
  firstAccessibleDashboardPath,
} from '@/components/shared/permissions';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const t = useTranslations('common');
  const { user, currentOrganization, isAuthReady } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  useEffect(() => {
    setSidebarOpen(false);
  }, [pathname]);

  useEffect(() => {
    if (!sidebarOpen) {
      return;
    }
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [sidebarOpen]);

  useEffect(() => {
    if (!isAuthReady) return;

    if (!user) {
      if (pathname && pathname !== '/login') {
        storeAuthRedirectFromPath(pathname);
        router.replace(`/login?from=${encodeURIComponent(pathname)}`);
      } else {
        router.replace('/login');
      }
      return;
    }

    if (!currentOrganization) {
      router.replace('/select-organization');
      return;
    }

    if (!canAccessDashboardRoute(currentOrganization, pathname)) {
      router.replace(firstAccessibleDashboardPath(currentOrganization));
    }
  }, [isAuthReady, user, currentOrganization, router, pathname]);

  if (!isAuthReady) {
    return (
      <div className="h-screen flex items-center justify-center app-web-bg">
        {t('loadingApp')}
      </div>
    );
  }

  if (!user || !currentOrganization) {
    return (
      <div className="h-screen flex items-center justify-center app-web-bg">
        {t('loadingWorkspace')}
      </div>
    );
  }

  // Do not mount clinic-only pages for lab orgs (avoids PERMISSION_CLINIC_ONLY toasts during redirect).
  if (!canAccessDashboardRoute(currentOrganization, pathname)) {
    return (
      <div className="h-screen flex items-center justify-center app-web-bg">
        {t('loadingWorkspace')}
      </div>
    );
  }

  return (
    <ToastProvider>
      <RealtimeProvider>
      <div className="app-dashboard-shell flex h-[100dvh] app-web-bg text-text-primary">
      {sidebarOpen ? (
        <button
          type="button"
          className="fixed inset-0 z-40 bg-black/50 lg:hidden"
          aria-label={t('closeMenu')}
          onClick={() => setSidebarOpen(false)}
        />
      ) : null}

      <Sidebar mobileOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />

      <div className="flex-1 flex flex-col min-w-0">
        <DashboardHeader
          organizationName={currentOrganization.name}
          onOpenSidebar={() => setSidebarOpen(true)}
        />

        <main className="p-3 sm:p-4 lg:p-6 flex-1 min-h-0 overflow-y-auto overscroll-y-contain">
          <div className="surface-panel p-3 sm:p-4 lg:p-6 min-w-0">
            {children}
          </div>
        </main>
      </div>
      </div>
      </RealtimeProvider>
    </ToastProvider>
  );
}

const DashboardHeader = memo(function DashboardHeader({
  organizationName,
  onOpenSidebar,
}: {
  organizationName: string;
  onOpenSidebar: () => void;
}) {
  const t = useTranslations('common');

  return (
    <header className="relative z-50 h-[71px] flex justify-between items-center gap-2 sm:gap-4 px-3 sm:px-6 border-b border-border/70 backdrop-blur-sm shrink-0">
      <div className="flex items-center gap-2 min-w-0 flex-1">
        <button
          type="button"
          className="lg:hidden inline-flex items-center justify-center h-10 w-10 rounded-[var(--radius-md)] border border-border/70 text-text-primary hover:bg-background-card/80 shrink-0"
          onClick={onOpenSidebar}
          aria-label={t('openMenu')}
        >
          <Menu className="h-5 w-5 icon-flat" />
        </button>
        <h2 className="text-base sm:text-lg font-medium truncate min-w-0">{organizationName}</h2>
      </div>

      <div className="flex items-center gap-2 sm:gap-3 shrink-0">
        <TopBarControls />
        <NotificationBell />
        <DashboardAccountMenu />
      </div>
    </header>
  );
});
