'use client';

import { useEffect, useState, type ReactNode } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { getUser, isImpersonating, returnToSuperAdmin, logout, type AuthUser } from '@/lib/auth';
import { ToastProvider } from '@/components/school/toast-context';
import { PlatformSidebarProvider, usePlatformSidebar } from '@/contexts/platform-sidebar-context';
import { PlatformThemeProvider } from '@/contexts/platform-theme-context';
import { ShellBackdrop } from '@/components/platform/shell-backdrop';
import { ShellHeader } from '@/components/platform/shell-header';
import { ShellMain } from '@/components/platform/shell-main';
import { ShellSidebar } from '@/components/platform/shell-sidebar';
import { flattenNavItems, getNavSectionsForRole } from '@/components/platform/platform-nav-data';

function PlatformLayoutInner({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const { closeMobileSidebar } = usePlatformSidebar();
  const [user, setUser] = useState<AuthUser | null>(null);
  const [impersonating, setImpersonating] = useState(false);
  const [expandedCollapsibleHref, setExpandedCollapsibleHref] = useState<string | null>(null);
  const role = user?.role ?? 'ADMIN';
  const navSections = getNavSectionsForRole(role);
  const navItemsFlat = flattenNavItems(navSections);
  const homeHref =
    role === 'SUPER_ADMIN'
      ? '/platform/dashboard'
      : role === 'TEACHER'
        ? '/teacher/dashboard'
        : role === 'PARENT'
          ? '/parent/dashboard'
          : '/school/dashboard';

  const roleSubtitle =
    role === 'SUPER_ADMIN'
      ? 'Super Admin'
      : role === 'TEACHER'
        ? 'Öğretmen paneli'
        : role === 'PARENT'
          ? 'Veli paneli'
          : 'Okul yönetimi';

  const notificationsHref =
    role === 'SUPER_ADMIN'
      ? undefined
      : role === 'TEACHER'
        ? undefined
        : role === 'PARENT'
          ? '/parent/notifications'
          : '/school/notifications';

  const messagesHref =
    role === 'TEACHER'
      ? '/teacher/messages'
      : role === 'PARENT'
        ? '/parent/messages'
        : role === 'ADMIN'
          ? '/school/messages'
          : undefined;

  useEffect(() => {
    const u = getUser();
    if (!u) {
      router.push('/login');
      return;
    }
    setUser(u);
    setImpersonating(isImpersonating());

    const allowedPrefixes =
      u.role === 'SUPER_ADMIN'
        ? ['/platform']
        : u.role === 'TEACHER'
          ? ['/teacher']
          : u.role === 'PARENT'
            ? ['/parent']
            : ['/school'];
    const onAllowedPath = allowedPrefixes.some((p) => pathname.startsWith(p));
    if (!onAllowedPath) router.replace(homeHref);

    const sections = getNavSectionsForRole(u.role);
    let parentHref: string | null = null;
    for (const s of sections) {
      for (const item of s.items) {
        if (
          item.children?.some((c) => pathname === c.href || pathname.startsWith(`${c.href}/`))
        ) {
          parentHref = item.href;
          break;
        }
      }
      if (parentHref) break;
    }
    setExpandedCollapsibleHref(parentHref);
  }, [router, pathname, homeHref]);

  const pageTitle =
    navItemsFlat.find((n) =>
      n.children
        ? n.children.some((c) => pathname === c.href || pathname.startsWith(c.href + '/'))
        : pathname === n.href || pathname.startsWith(n.href + '/'),
    )?.label || 'Panel';

  if (!user) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-shell-canvas text-zinc-500 dark:bg-app-canvas-dark dark:text-zinc-400">
        Yükleniyor…
      </div>
    );
  }

  return (
    <div className="min-h-screen xl:flex">
      <div>
        <ShellSidebar
          navSections={navSections}
          homeHref={homeHref}
          roleSubtitle={roleSubtitle}
          user={user}
          expandedCollapsibleHref={expandedCollapsibleHref}
          setExpandedCollapsibleHref={setExpandedCollapsibleHref}
          onCloseMobile={closeMobileSidebar}
        />
        <ShellBackdrop />
      </div>

      <ShellMain>
        <ShellHeader
          homeHref={homeHref}
          pageTitle={pageTitle}
          user={user}
          onLogout={logout}
          roleSubtitle={roleSubtitle}
          notificationsHref={notificationsHref}
          messagesHref={messagesHref}
        />

        {impersonating && (
          <div className="flex flex-wrap items-center justify-center gap-3 border-b border-amber-600/20 bg-gradient-to-r from-amber-500 to-amber-600 px-4 py-2.5 text-center text-[13px] font-medium text-white shadow-sm">
            <span>Taklit giriş aktif — {user?.name} olarak görüntülüyorsunuz</span>
            <button
              type="button"
              onClick={() => {
                if (returnToSuperAdmin()) {
                  window.location.href = '/platform/schools';
                }
              }}
              className="rounded-md bg-white/20 px-3 py-1 text-xs font-semibold transition hover:bg-white/30"
            >
              Super Admin&apos;e Dön
            </button>
          </div>
        )}

        <main className="flex-1 bg-shell-canvas px-3 pb-8 pt-4 dark:bg-app-canvas-dark sm:px-5 lg:px-8 lg:pb-10 lg:pt-6">
          <div className="mx-auto w-full max-w-[1600px] rounded-3xl border border-white/80 bg-white p-4 shadow-[0_1px_3px_rgba(15,23,42,0.06)] sm:p-6 lg:p-8 dark:border-zinc-800 dark:bg-zinc-900 dark:shadow-none min-h-[calc(100vh-5.5rem)]">
            {children}
          </div>
        </main>
      </ShellMain>
    </div>
  );
}

export default function PlatformLayout({ children }: { children: ReactNode }) {
  return (
    <ToastProvider>
      <PlatformThemeProvider>
        <PlatformSidebarProvider>
          <PlatformLayoutInner>{children}</PlatformLayoutInner>
        </PlatformSidebarProvider>
      </PlatformThemeProvider>
    </ToastProvider>
  );
}
