'use client';

import Image from 'next/image';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { LogoutButton } from './logout-button';
import { clearSession, hasAdminAccess, readSession, type AppSession } from './lib/auth-session';

const navigation = [
  { href: '/', label: 'Dashboard' },
  { href: '/access', label: 'Acessos' },
  { href: '/orders', label: 'Pedidos' },
  { href: '/payments', label: 'Pagamentos' },
  { href: '/notifications', label: 'Notificacoes' },
  { href: '/restaurants', label: 'Restaurantes' },
  { href: '/drivers', label: 'Entregadores' },
  { href: '/customers', label: 'Clientes' },
  { href: '/coupons', label: 'Cupons' },
  { href: '/withdrawals', label: 'Saques' },
  { href: '/support', label: 'Suporte' },
  { href: '/finance', label: 'Financeiro' },
  { href: '/reports', label: 'Relatorios' },
  { href: '/subscriptions', label: 'Assinaturas' },
  { href: '/audit', label: 'Auditoria' },
  { href: '/settings', label: 'Configuracoes' },
  { href: '/live-map', label: 'Mapa ao vivo' },
  { href: '/metrics', label: 'Metricas' },
];

const apiBase = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api';

function isActive(pathname: string, href: string) {
  return href === '/' ? pathname === '/' : pathname === href || pathname.startsWith(`${href}/`);
}

function BrandLogo({ className = '' }: { className?: string }) {
  return (
    <div className={className}>
      <Image src="/brand/chego-logo.png" alt="Chego" width={440} height={160} className="h-auto w-full object-contain" priority />
    </div>
  );
}

export function DashboardShell({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();
  const [ready, setReady] = useState(pathname === '/login');
  const [session, setSession] = useState<AppSession | null>(null);
  const isLogin = pathname === '/login';

  useEffect(() => {
    let active = true;

    if (isLogin) {
      setReady(true);
      return;
    }

    const currentSession = readSession();
    if (!hasAdminAccess(currentSession)) {
      router.replace('/login');
      setReady(false);
      return;
    }

    const validatedSession = currentSession as AppSession;

    const validateSession = async () => {
      try {
        const response = await fetch(`${apiBase}/auth/me`, {
          headers: { Authorization: `Bearer ${validatedSession.accessToken}` },
        });
        if (!response.ok) {
          clearSession();
          if (active) {
            router.replace('/login');
            setReady(false);
          }
          return;
        }

        if (active) {
          setSession(validatedSession);
          setReady(true);
        }
      } catch {
        clearSession();
        if (active) {
          router.replace('/login');
          setReady(false);
        }
      }
    };

    void validateSession();

    return () => {
      active = false;
    };
  }, [isLogin, pathname, router]);

  const displayIdentity = useMemo(() => session?.user.email ?? session?.user.phone ?? 'Sessao administrativa', [session]);

  if (isLogin) {
    return <div className="min-h-screen bg-[#0b1117] text-slate-100">{children}</div>;
  }

  if (!ready) {
    return <div className="min-h-screen bg-[#0b1117]" />;
  }

  return (
    <div className="min-h-screen bg-[#f4f7fb] text-slate-900">
      <div className="mx-auto grid min-h-screen max-w-[1600px] lg:grid-cols-[300px_minmax(0,1fr)]">
        <aside className="border-b border-slate-200 bg-white px-5 py-6 text-slate-900 shadow-[0_10px_30px_rgba(15,23,42,0.05)] lg:min-h-screen lg:border-b-0 lg:border-r">
          <div className="rounded-[1.35rem] border border-slate-200 bg-slate-50 p-5">
            <BrandLogo className="max-w-[180px]" />
            <p className="mt-4 text-xs font-semibold uppercase tracking-[0.24em] text-[#b45309]">Chego Admin</p>
            <h1 className="mt-2 text-2xl font-black tracking-tight text-slate-900">Central segura</h1>
            <p className="mt-2 text-sm leading-6 text-slate-600">Operacao, financeiro e auditoria com acesso filtrado por sessao e papel.</p>
          </div>

          <div className="mt-5 rounded-[1.1rem] border border-slate-200 bg-white p-4">
            <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500">Sessao</p>
            <p className="mt-2 text-sm font-bold text-slate-900">{displayIdentity}</p>
            <p className="mt-1 text-xs uppercase tracking-[0.16em] text-[#b45309]">{session?.user.role ?? 'ADMIN'}</p>
          </div>

          <nav className="mt-6 grid gap-2">
            {navigation.map((item) => {
              const active = isActive(pathname, item.href);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={[
                    'rounded-xl px-4 py-2.5 text-sm font-bold transition',
                    active ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900',
                  ].join(' ')}
                >
                  {item.label}
                </Link>
              );
            })}
          </nav>
        </aside>

        <div className="min-w-0">
          <header className="flex flex-col gap-4 border-b border-slate-200 bg-white px-5 py-4 lg:flex-row lg:items-center lg:justify-between lg:px-8">
            <div>
              <div className="max-w-[120px] lg:hidden">
                <BrandLogo />
              </div>
              <p className="text-xs font-semibold uppercase tracking-[0.28em] text-slate-500">Painel administrativo</p>
              <p className="mt-1 text-sm text-slate-600">Leitura rapida, velocidade operacional e menos ruido visual.</p>
            </div>
            <div className="flex flex-wrap items-center gap-3">
              <span className="rounded-full border border-emerald-500/20 bg-emerald-500/10 px-4 py-2 text-xs font-bold uppercase tracking-[0.18em] text-emerald-700">Sessao validada</span>
              <span className="rounded-full border border-slate-200 bg-slate-100 px-4 py-2 text-xs font-bold uppercase tracking-[0.18em] text-slate-700">{session?.user.role ?? 'ADMIN'}</span>
              <LogoutButton />
            </div>
          </header>
          <main className="px-4 py-5 lg:px-8 lg:py-8">{children}</main>
        </div>
      </div>
    </div>
  );
}
