'use client';

import { clearSession, fetchCurrentUser, readSessionToken } from '@/lib/auth';
import { AppShell, Button, NavLink, Stack, Text } from '@mantine/core';
import { EnvelopeSimpleIcon, FilesIcon, HouseSimpleIcon, ImagesIcon, PackageIcon, SquaresFourIcon, StorefrontIcon } from '@phosphor-icons/react/ssr';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

const navigation = [
  { label: 'Visão geral', mobileLabel: 'Visão', href: '/', icon: SquaresFourIcon },
  { label: 'Página inicial', mobileLabel: 'Home', href: '/home', icon: HouseSimpleIcon },
  { label: 'Páginas internas', mobileLabel: 'Páginas', href: '/paginas', icon: FilesIcon },
  { label: 'Representantes', mobileLabel: 'Revendas', href: '/representantes', icon: StorefrontIcon },
  { label: 'Catálogo', mobileLabel: 'Catálogo', href: '/catalogo', icon: PackageIcon },
  { label: 'Ambientes', mobileLabel: 'Ambientes', href: '/ambientes', icon: ImagesIcon },
  { label: 'Leads', mobileLabel: 'Leads', href: '/leads', icon: EnvelopeSimpleIcon },
];

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

export default function Layout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    let active = true;
    const token = readSessionToken();
    if (!token) {
      router.replace('/login');
      return;
    }
    fetchCurrentUser(token)
      .then(() => {
        if (active) setAllowed(true);
      })
      .catch(() => {
        clearSession();
        router.replace('/login');
      });
    return () => {
      active = false;
    };
  }, [router]);

  function logout() {
    clearSession();
    router.replace('/login');
  }

  if (!allowed) return null;

  return (
    <AppShell header={{ height: 68 }} navbar={{ width: 264, breakpoint: 'md', collapsed: { mobile: true } }} padding={0} transitionDuration={180} withBorder={false}>
      <AppShell.Header className="flex items-center justify-between border-b border-line bg-elevated px-4 sm:px-7">
        <div className="flex items-center gap-3">
          <div className="flex size-9 items-center justify-center rounded-md bg-orange text-white">
            <HouseSimpleIcon size={20} weight="fill" />
          </div>
          <Text c="var(--mantine-color-forest-deep)" fw={700} size="lg">
            HidroTintas
          </Text>
        </div>
        <div className="flex items-center gap-4">
          <Text c="var(--mantine-color-muted)" className="hidden sm:block" size="sm">
            Administração de conteúdo
          </Text>
          <Button color="forest" onClick={logout} radius="md" size="xs" variant="subtle">
            Sair
          </Button>
        </div>
      </AppShell.Header>

      <AppShell.Navbar className="border-r border-line bg-elevated" p="md">
        <Stack className="h-full" gap="lg">
          <Text c="var(--mantine-color-muted)" fw={700} px="sm" size="xs" tt="uppercase">
            Painel
          </Text>
          <nav aria-label="Navegação do painel" className="-mt-3">
            {navigation.map(({ label, href, icon: Icon }) => (
              <NavLink
                active={itemActive(pathname, href)}
                aria-current={itemActive(pathname, href) ? 'page' : undefined}
                className="mb-1"
                component={Link}
                href={href}
                key={href}
                label={label}
                leftSection={<Icon aria-hidden="true" size={20} weight={itemActive(pathname, href) ? 'fill' : 'regular'} />}
              />
            ))}
          </nav>
          <div className="mt-auto border-t border-line px-3 pt-4">
            <Text c="var(--mantine-color-ink-soft)" fw={600} size="sm">
              Conteúdo do site
            </Text>
            <Text c="var(--mantine-color-muted)" mt={4} size="xs">
              Áreas administrativas HidroTintas
            </Text>
          </div>
        </Stack>
      </AppShell.Navbar>

      <AppShell.Main className="min-h-dvh bg-page">
        <div className="mx-auto w-full max-w-7xl px-4 py-6 pb-40 sm:px-7 md:py-8 md:pb-10">{children}</div>
        <nav
          aria-label="Navegação principal"
          className="fixed inset-x-3 bottom-3 z-50 grid grid-cols-3 gap-1 rounded-lg border border-line bg-elevated p-2 shadow-soft md:hidden"
        >
          {navigation.slice(1).map(({ mobileLabel, href, icon: Icon }) => (
            <Link
              aria-current={itemActive(pathname, href) ? 'page' : undefined}
              className="flex min-h-12 flex-col items-center justify-center gap-1 rounded-md px-1 text-center text-xs font-medium text-ink-soft transition-colors hover:bg-page focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange"
              href={href}
              key={href}
            >
              <Icon aria-hidden="true" size={19} />
              <span>{mobileLabel}</span>
            </Link>
          ))}
        </nav>
      </AppShell.Main>
    </AppShell>
  );
}
