import { Avatar, Badge, Button, Dropdown, Flex, Grid, Typography } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBell, faBuilding, faRightFromBracket } from '@fortawesome/free-solid-svg-icons';
import { useNavigate } from '@tanstack/react-router';
import { brandTokens } from '../../lib/theme';
import { FoundationStatus } from './FoundationStatus';
import { usePendingCount } from '../../lib/queries/notifications';
import { useCurrentUser } from '../../lib/queries/auth';
import { useCompany } from '../../lib/queries/company';
import { authStore } from '../../lib/auth-store';

const { useBreakpoint } = Grid;

function logout() {
  authStore.clear();
  window.location.reload();
}

export function Topbar() {
  const navigate = useNavigate();
  const screens = useBreakpoint();
  const isDesktop = !!screens.lg;
  const { data: pendingData } = usePendingCount();
  const pendingCount = pendingData?.count ?? 0;
  const { data: user } = useCurrentUser();
  const { data: company } = useCompany();
  const nomeFantasia = company?.nomeFantasia?.trim() ?? null;
  const razaoSocial = company?.razaoSocial?.trim() ?? null;
  const nomeEmpresa = nomeFantasia ?? razaoSocial ?? '—';
  const mostrarRazao = nomeFantasia && razaoSocial && nomeFantasia !== razaoSocial;
  const initials = user?.nome
    ? user.nome
        .split(' ')
        .slice(0, 2)
        .map((w) => w[0])
        .join('')
        .toUpperCase()
    : '?';

  const userMenuItems = [
    {
      key: 'profile',
      label: (
        <Flex vertical gap={2} style={{ padding: '4px 0', minWidth: 180 }}>
          <Typography.Text strong style={{ fontSize: 'var(--text-sm)' }}>
            {user?.nome?.trim() ?? '—'}
          </Typography.Text>
          <Typography.Text
            type="secondary"
            style={{ fontSize: 'var(--text-xs)', textTransform: 'capitalize' }}
          >
            {user?.role ?? ''}
          </Typography.Text>
        </Flex>
      ),
      disabled: true,
    },
    { type: 'divider' as const },
    {
      key: 'logout',
      danger: true,
      icon: <FontAwesomeIcon icon={faRightFromBracket} />,
      label: 'Sair',
      onClick: logout,
    },
  ];

  return (
    <Flex
      align="center"
      justify="space-between"
      style={{
        height: isDesktop ? 'var(--layout-topbar-height)' : 56,
        padding: isDesktop ? '0 var(--space-lg)' : '0 var(--space-md)',
        background: 'var(--bg-surface)',
        borderBottom: '1px solid var(--border-subtle)',
        position: 'sticky',
        top: 0,
        zIndex: 'var(--z-sticky)',
        flexShrink: 0,
      }}
    >
      {/* Logo */}
      <Flex align="center" gap={isDesktop ? 12 : 8}>
        <img src="/sar-icon.png" alt="SAR" style={{ height: isDesktop ? 40 : 32, width: 'auto' }} />
        {isDesktop && (
          <Flex vertical gap={0}>
            <span
              style={{
                fontSize: 'var(--text-lg)',
                fontWeight: 'var(--font-weight-bold)',
                color: 'var(--text-main)',
                lineHeight: 1.1,
              }}
            >
              SAR
            </span>
            <span
              style={{
                fontSize: 'var(--text-2xs)',
                color: 'var(--text-muted)',
                letterSpacing: '0.05em',
                textTransform: 'uppercase',
                fontWeight: 'var(--font-weight-medium)',
              }}
            >
              Força de Vendas
            </span>
          </Flex>
        )}
      </Flex>

      {/* Centro: empresa ativa */}
      <Flex
        flex={1}
        justify="center"
        style={{
          margin: `0 ${isDesktop ? 'var(--space-2xl)' : 'var(--space-sm)'}`,
          overflow: 'hidden',
        }}
      >
        <Flex align="center" gap={isDesktop ? 10 : 6} style={{ overflow: 'hidden' }}>
          <FontAwesomeIcon
            icon={faBuilding}
            style={{ color: 'var(--text-muted)', fontSize: isDesktop ? 16 : 13, flexShrink: 0 }}
          />
          <Flex vertical gap={0} style={{ overflow: 'hidden' }}>
            <Typography.Text
              ellipsis
              style={{
                fontSize: isDesktop ? 'var(--text-xl)' : 'var(--text-sm)',
                fontWeight: 'var(--font-weight-semibold)',
                color: 'var(--text-main)',
                lineHeight: 1.2,
              }}
            >
              {nomeEmpresa}
            </Typography.Text>
            {isDesktop && mostrarRazao && (
              <Typography.Text
                style={{
                  fontSize: 'var(--text-2xs)',
                  color: 'var(--text-muted)',
                  lineHeight: 1.3,
                  whiteSpace: 'nowrap',
                }}
              >
                {razaoSocial}
              </Typography.Text>
            )}
          </Flex>
        </Flex>
      </Flex>

      {/* Lado direito */}
      <Flex align="center" gap={isDesktop ? 16 : 8}>
        {isDesktop && (
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => void navigate({ to: '/pedidos/novo' })}
            style={{ borderRadius: 8, fontWeight: 'var(--font-weight-semibold)' }}
          >
            Novo Pedido
          </Button>
        )}
        {isDesktop && <FoundationStatus />}
        <Badge count={pendingCount} color={brandTokens.red} offset={[-4, 4]}>
          <Button
            type="text"
            size={isDesktop ? 'large' : 'middle'}
            icon={<FontAwesomeIcon icon={faBell} />}
            aria-label="Notificações"
          />
        </Badge>
        <Dropdown menu={{ items: userMenuItems }} trigger={['click']} placement="bottomRight">
          <Avatar
            size={isDesktop ? 40 : 32}
            style={{
              background: 'var(--jcs-blue-light)',
              color: 'var(--jcs-blue)',
              fontWeight: 'var(--font-weight-semibold)',
              cursor: 'pointer',
              flexShrink: 0,
            }}
          >
            {initials}
          </Avatar>
        </Dropdown>
      </Flex>
    </Flex>
  );
}
