'use client';

import { memo, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { usePathname, useRouter } from '@/i18n/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import Sidebar from '@/components/ui/shared/Sidebar';
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
import { DashboardAccountMenu } from '@/components/ui/dashboard/DashboardAccountMenu';
import {
  canAccessAppointmentsSection,
  firstAccessibleDashboardPath,
  getRequiredReadPermissionForPath,
  hasPermission,
} 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();

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

    if (!user) {
      router.replace('/login');
      return;
    }

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

    const required = getRequiredReadPermissionForPath(pathname);
    if (required) {
      const allowed =
        hasPermission(currentOrganization, required) ||
        (required === 'TAB_APPOINTMENTS_READ' &&
          canAccessAppointmentsSection(currentOrganization));
      if (!allowed) {
        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>
    );
  }

  return (
    <div className="flex h-screen app-web-bg text-text-primary">
      <Sidebar />

      <div className="flex-1 flex flex-col">
        <DashboardHeader organizationName={currentOrganization.name} />

        <main className="p-6 flex-1 overflow-y-auto">
          <div className="surface-panel p-6 min-h-full">
            {children}
          </div>
        </main>
      </div>
    </div>
  );
}

const DashboardHeader = memo(function DashboardHeader({
  organizationName,
}: {
  organizationName: string;
}) {
  return (
    <header className="relative z-40 h-[71px] flex justify-between items-center gap-4 px-6 border-b border-border/70 backdrop-blur-sm">
      <h2 className="text-lg font-medium truncate min-w-0">{organizationName}</h2>

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