'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { useAuth } from '@/lib/auth-context';
import type { UserRole } from '@/lib/auth';
import {
  CONTACT_MESSAGES_CHANGED,
  countNewContactMessages,
} from '@/lib/services/contact-messages';

interface NavItem {
  href: string;
  label: string;
  icon: string;
  roles: UserRole[];
  soon?: boolean;
  /** Mostra o contador de mensagens de contato novas */
  showUnread?: boolean;
}

interface NavGroup {
  title: string;
  items: NavItem[];
}

const STAFF: UserRole[] = ['admin', 'receptionist', 'dentist'];
const INBOX: UserRole[] = ['admin', 'receptionist'];

const NAV: NavGroup[] = [
  {
    title: 'Clínica',
    items: [
      { href: '/painel', label: 'Painel', icon: 'bi-speedometer2', roles: STAFF },
      {
        href: '/painel/pacientes',
        label: 'Pacientes',
        icon: 'bi-people',
        roles: STAFF,
      },
      {
        href: '/painel/dentistas',
        label: 'Dentistas',
        icon: 'bi-person-badge',
        roles: STAFF,
      },
      {
        href: '/painel/especialidades',
        label: 'Especialidades',
        icon: 'bi-clipboard2-pulse',
        roles: STAFF,
      },
      {
        href: '/painel/agenda',
        label: 'Agenda',
        icon: 'bi-calendar3',
        roles: STAFF,
      },
      {
        href: '/painel/tratamentos',
        label: 'Tratamentos',
        icon: 'bi-clipboard2-check',
        roles: STAFF,
      },
      {
        href: '/painel/exames',
        label: 'Exames',
        icon: 'bi-file-earmark-medical',
        roles: STAFF,
      },
      {
        href: '/painel/financeiro',
        label: 'Financeiro',
        icon: 'bi-cash-coin',
        roles: STAFF,
      },
      {
        href: '/painel/procedimentos',
        label: 'Procedimentos',
        icon: 'bi-list-check',
        roles: STAFF,
      },
      {
        href: '/painel/mensagens',
        label: 'Mensagens',
        icon: 'bi-envelope',
        roles: INBOX,
        showUnread: true,
      },
    ],
  },
  {
    title: 'Site',
    items: [
      {
        href: '/painel/paginas',
        label: 'Páginas',
        icon: 'bi-window-stack',
        roles: ['admin'],
      },
    ],
  },
  {
    title: 'Administração',
    items: [
      {
        href: '/painel/usuarios',
        label: 'Usuários',
        icon: 'bi-person-gear',
        roles: ['admin'],
      },
      {
        href: '/painel/permissoes',
        label: 'Permissões',
        icon: 'bi-shield-lock',
        roles: ['admin'],
      },
      {
        href: '/painel/auditoria',
        label: 'Auditoria',
        icon: 'bi-journal-text',
        roles: ['admin'],
      },
    ],
  },
  {
    title: 'Portal do paciente',
    items: [
      { href: '/portal', label: 'Início', icon: 'bi-house-heart', roles: ['patient'] },
      {
        href: '/portal/consultas',
        label: 'Minhas consultas',
        icon: 'bi-calendar3',
        roles: ['patient'],
      },
      {
        href: '/portal/tratamentos',
        label: 'Orçamentos',
        icon: 'bi-clipboard2-check',
        roles: ['patient'],
      },
      {
        href: '/portal/financeiro',
        label: 'Financeiro',
        icon: 'bi-wallet2',
        roles: ['patient'],
      },
      {
        href: '/portal/exames',
        label: 'Exames',
        icon: 'bi-file-earmark-medical',
        roles: ['patient'],
      },
      {
        href: '/portal/meus-dados',
        label: 'Meus dados',
        icon: 'bi-person-vcard',
        roles: ['patient'],
      },
      {
        href: '/portal/consentimentos',
        label: 'Consentimentos',
        icon: 'bi-shield-check',
        roles: ['patient'],
      },
      {
        href: '/portal/documentos',
        label: 'Meus documentos',
        icon: 'bi-folder2-open',
        roles: ['patient'],
      },
    ],
  },
];

/** Destaca também subpáginas (/painel/tratamentos/12); as raízes só no exato. */
function isActivePath(pathname: string, href: string): boolean {
  if (href === '/painel' || href === '/portal') return pathname === href;
  return pathname === href || pathname.startsWith(`${href}/`);
}

export default function AppShell({ children }: { children: React.ReactNode }) {
  const { user, logout } = useAuth();
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const [unread, setUnread] = useState(0);
  const canSeeInbox = Boolean(user && INBOX.includes(user.role));

  useEffect(() => {
    if (!canSeeInbox) return;
    let active = true;
    const refresh = () =>
      countNewContactMessages()
        .then((count) => active && setUnread(count))
        .catch(() => undefined);

    refresh();
    window.addEventListener(CONTACT_MESSAGES_CHANGED, refresh);
    return () => {
      active = false;
      window.removeEventListener(CONTACT_MESSAGES_CHANGED, refresh);
    };
  }, [canSeeInbox, pathname]);

  const groups = NAV.map((group) => ({
    ...group,
    items: group.items.filter((item) => user && item.roles.includes(user.role)),
  })).filter((group) => group.items.length > 0);

  async function handleLogout() {
    const result = await Swal.fire({
      icon: 'question',
      title: 'Sair da conta?',
      showCancelButton: true,
      confirmButtonText: 'Sair',
      cancelButtonText: 'Cancelar',
    });
    if (result.isConfirmed) {
      await logout();
    }
  }

  return (
    <div className="app-shell d-flex min-vh-100">
      <aside
        className={`app-sidebar bg-dark text-white ${open ? 'show' : ''}`}
        aria-label="Navegação principal"
      >
        <div className="p-3 border-bottom border-secondary">
          <Link
            href="/"
            className="text-white text-decoration-none fw-bold d-flex align-items-center"
          >
            <i className="bi bi-heart-pulse-fill fs-4 me-2 text-info" />
            DentalFlow
          </Link>
        </div>
        <nav className="nav flex-column p-2">
          {groups.map((group) => (
            <div key={group.title} className="mb-2">
              <span className="text-uppercase text-secondary small px-2 fw-semibold">
                {group.title}
              </span>
              {group.items.map((item) =>
                item.soon ? (
                  <span
                    key={item.href}
                    className="nav-link text-white-50 disabled d-flex align-items-center"
                    aria-disabled="true"
                    title="Em breve"
                  >
                    <i className={`bi ${item.icon} me-2`} />
                    {item.label}
                    <span className="badge text-bg-secondary ms-auto">em breve</span>
                  </span>
                ) : (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`nav-link text-white d-flex align-items-center rounded ${
                      isActivePath(pathname, item.href) ? 'active bg-primary' : ''
                    }`}
                    onClick={() => setOpen(false)}
                  >
                    <i className={`bi ${item.icon} me-2`} />
                    {item.label}
                    {item.showUnread && unread > 0 && (
                      <span
                        className="badge rounded-pill text-bg-danger ms-auto"
                        aria-label={`${unread} nova${unread === 1 ? '' : 's'}`}
                      >
                        {unread}
                      </span>
                    )}
                  </Link>
                ),
              )}
            </div>
          ))}
        </nav>
      </aside>

      <div className="flex-grow-1 d-flex flex-column min-w-0">
        <header className="navbar bg-white border-bottom px-3 sticky-top">
          <button
            className="btn btn-outline-secondary d-lg-none me-2"
            type="button"
            aria-label="Abrir menu"
            onClick={() => setOpen((v) => !v)}
          >
            <i className="bi bi-list" />
          </button>
          <span className="navbar-text fw-semibold text-truncate">
            <i className="bi bi-person-circle me-2 text-primary" />
            {user?.email}
            <span className="badge text-bg-light border ms-2 text-capitalize">
              {user?.role}
            </span>
          </span>
          <button
            className="btn btn-outline-danger btn-sm ms-auto"
            type="button"
            onClick={handleLogout}
          >
            <i className="bi bi-box-arrow-right me-1" />
            Sair
          </button>
        </header>

        <main className="flex-grow-1 bg-light p-3 p-lg-4">{children}</main>
      </div>
    </div>
  );
}
