'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, hasRestaurantAccess, readSession, type AppSession } from './lib/auth-session';

const navigation = [
  { href: '/', label: 'Dashboard' },
  { href: '/orders', label: 'Pedidos' },
  { href: '/products', label: 'Produtos' },
  { href: '/categories', label: 'Categorias' },
  { href: '/additionals', label: 'Adicionais' },
  { href: '/variations', label: 'Variacoes' },
  { href: '/promotions', label: 'Promocoes' },
  { href: '/coupons', label: 'Cupons' },
  { href: '/ads', label: 'Anuncios' },
  { href: '/finance', label: 'Financeiro' },
  { href: '/support', label: 'Suporte' },
  { href: '/subscriptions', label: 'Assinaturas' },
  { href: '/delivery-tracking', label: 'Entregas ao vivo' },
  { href: '/reviews', label: 'Avaliacoes' },
  { href: '/settings', label: 'Configuracoes' },
];

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 isPublic = pathname === '/login' || pathname === '/cadastro' || pathname.startsWith('/public-order');
  const [ready, setReady] = useState(isPublic);
  const [session, setSession] = useState<AppSession | null>(null);
  const [storeStatus, setStoreStatus] = useState<{ isOpen: boolean; isPaused: boolean } | null>(null);

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

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

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

    const validatedSession = currentSession as AppSession;

    const validateSession = async () => {
      try {
        const authResponse = await fetch(`${apiBase}/auth/me`, {
          headers: { Authorization: `Bearer ${validatedSession.accessToken}` },
        });

        if (!authResponse.ok) {
          clearSession();
          if (active) {
            router.replace('/login');
            setReady(false);
          }
          return;
        }

        const profileResponse = await fetch(`${apiBase}/restaurant/profile`, {
          headers: { Authorization: `Bearer ${validatedSession.accessToken}` },
        });
        const profile = await profileResponse.json().catch(() => null);

        if (!active) {
          return;
        }

        setSession(validatedSession);
        if (profileResponse.ok && profile) {
          setStoreStatus({ isOpen: Boolean(profile.isOpen), isPaused: Boolean(profile.isPaused) });
        }
        setReady(true);
      } catch {
        clearSession();
        if (active) {
          router.replace('/login');
          setReady(false);
        }
      }
    };

    void validateSession();

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

  const toggleStoreField = async (field: 'isOpen' | 'isPaused', value: boolean) => {
    const currentSession = readSession();
    if (!currentSession?.accessToken) {
      return;
    }

    const response = await fetch(`${apiBase}/restaurant/profile`, {
      method: 'PATCH',
      headers: {
        Authorization: `Bearer ${currentSession.accessToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ [field]: value }),
    });
    const payload = await response.json().catch(() => null);

    if (response.ok && payload) {
      setStoreStatus({ isOpen: Boolean(payload.isOpen), isPaused: Boolean(payload.isPaused) });
    }
  };

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

  if (isPublic) {
    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-[#f5f7fb] 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.4rem] 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 Restaurante</p>
            <h1 className="mt-2 text-2xl font-black tracking-tight text-slate-900">Area da loja</h1>
            <p className="mt-2 text-sm leading-6 text-slate-600">Pedidos, produtos, repasses e operacao somente desta loja.</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 ?? 'RESTAURANT'}</p>
          </div>

          <div className="mt-6 rounded-[1.1rem] border border-slate-200 bg-white p-3">
            <p className="px-2 pb-3 text-[11px] font-black uppercase tracking-[0.24em] text-slate-500">Operacao da loja</p>
            <nav className="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>
          </div>
        </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 do parceiro</p>
              <p className="mt-1 text-sm text-slate-600">Fluxo direto, menos poluicao e foco na operacao da loja.</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>
              <button
                type="button"
                onClick={() => void toggleStoreField('isOpen', !(storeStatus?.isOpen ?? false))}
                className={[
                  'rounded-full px-4 py-2 text-xs font-bold uppercase tracking-[0.18em]',
                  storeStatus?.isOpen ? 'border border-emerald-500/20 bg-emerald-500/10 text-emerald-700' : 'border border-slate-200 bg-slate-100 text-slate-700',
                ].join(' ')}
              >
                {storeStatus?.isOpen ? 'Loja aberta' : 'Loja fechada'}
              </button>
              <button
                type="button"
                onClick={() => void toggleStoreField('isPaused', !(storeStatus?.isPaused ?? false))}
                className={[
                  'rounded-full px-4 py-2 text-xs font-bold uppercase tracking-[0.18em]',
                  storeStatus?.isPaused ? 'border border-amber-500/20 bg-amber-500/10 text-amber-700' : 'border border-slate-200 bg-slate-100 text-slate-700',
                ].join(' ')}
              >
                {storeStatus?.isPaused ? 'Loja pausada' : 'Loja em operacao'}
              </button>
              <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 ?? 'RESTAURANT'}
              </span>
              <LogoutButton />
            </div>
          </header>

          <main className="px-4 py-5 lg:px-8 lg:py-8">{children}</main>
        </div>
      </div>
    </div>
  );
}
