import { useEffect, type ReactNode } from 'react';
import { Alert, App, Button, Flex, Grid, Tooltip } from 'antd';
import { PlusOutlined, WifiOutlined } from '@ant-design/icons';
import { useNavigate } from '@tanstack/react-router';
import { Topbar } from './Topbar';
import { Sidebar } from './Sidebar';
import { BottomNav } from './BottomNav';
import { useNetworkStatus } from '../../lib/hooks/useNetworkStatus';
import { useOfflineSync } from '../../lib/hooks/useOfflineSync';
import { registerMessageApi } from '../../lib/feedback';

const { useBreakpoint } = Grid;

interface AppShellProps {
  children: ReactNode;
}

export function AppShell({ children }: AppShellProps) {
  const navigate = useNavigate();
  const isOnline = useNetworkStatus();
  const screens = useBreakpoint();
  const { message } = App.useApp();
  // sidebar a partir de lg (992px) — abaixo disso usa bottom nav
  const isDesktop = !!screens.lg;
  useOfflineSync();

  // Disponibiliza o message (com tema) para os caches do TanStack Query
  useEffect(() => {
    registerMessageApi(message);
  }, [message]);

  return (
    <Flex vertical style={{ height: '100vh', overflow: 'hidden', background: 'var(--bg-body)' }}>
      {!isOnline && (
        <Alert
          type="warning"
          icon={<WifiOutlined />}
          showIcon
          banner
          message="Sem conexão — pedidos lançados ficam salvos e serão enviados ao reconectar"
          style={{ padding: '6px 16px', fontSize: 13 }}
        />
      )}
      <Topbar />
      <Flex flex={1} style={{ overflow: 'hidden' }}>
        {isDesktop && <Sidebar />}
        <main
          style={{
            flex: 1,
            padding: isDesktop ? 'var(--space-xl)' : 'var(--space-md)',
            paddingBottom: isDesktop
              ? 'var(--space-xl)'
              : 'calc(var(--layout-bottom-nav-height) + var(--space-lg))',
            overflowY: 'auto',
            overflowX: 'hidden',
            minWidth: 0,
          }}
        >
          {children}
        </main>
      </Flex>

      {!isDesktop && <BottomNav />}

      {/* FAB — Novo Pedido: acima do bottom nav em mobile */}
      <Tooltip title="Novo Pedido" placement="left">
        <Button
          type="primary"
          shape="circle"
          icon={<PlusOutlined />}
          onClick={() => void navigate({ to: '/pedidos/novo' })}
          style={{
            position: 'fixed',
            bottom: isDesktop ? 32 : 'calc(var(--layout-bottom-nav-height) + 16px)',
            right: 20,
            width: 52,
            height: 52,
            fontSize: 22,
            backgroundColor: '#389e0d',
            borderColor: '#389e0d',
            boxShadow: '0 4px 16px rgba(56,158,13,0.45)',
            zIndex: 1000,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        />
      </Tooltip>
    </Flex>
  );
}
