import { useState, useMemo } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
  App,
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  Modal,
  Dropdown,
  Grid,
  Row,
  Select,
  Space,
  Spin,
  Table,
  Tag,
  Timeline,
  Typography,
  Divider,
} from 'antd';
import type { TableColumnsType } from 'antd';
import type { MenuProps } from 'antd';
import type { Dayjs } from 'dayjs';
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  CopyOutlined,
  DollarOutlined,
  EditOutlined,
  EllipsisOutlined,
  EyeOutlined,
  FilePdfOutlined,
  PlusOutlined,
  ShoppingCartOutlined,
  ClearOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { Link, useNavigate } from '@tanstack/react-router';
import type { PedidoSummary } from '@sar/api-interface';
import { SITUA_LABEL } from '@sar/api-interface';
import { useOrderList, useOrderDetail } from '../../lib/queries/orders';
import { usePendingOrders } from '../../lib/hooks/usePendingOrders';
import { removePendingOrder, retryPendingOrder } from '../../lib/offline/order-queue';
import { apiFetch } from '../../lib/api-client';

const { RangePicker } = DatePicker;

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmt(v: number | string) {
  return Number(v).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

function fmtDate(v: string) {
  return new Date(v).toLocaleDateString('pt-BR');
}

function toISO(d: Date) {
  return d.toISOString().split('T')[0];
}

function periodRange(p: string): { from?: string; to?: string } {
  const today = new Date();
  if (p === 'today') return { from: toISO(today), to: toISO(today) };
  if (p === '7d') {
    const d = new Date(today);
    d.setDate(d.getDate() - 7);
    return { from: toISO(d), to: toISO(today) };
  }
  if (p === '30d') {
    const d = new Date(today);
    d.setDate(d.getDate() - 30);
    return { from: toISO(d), to: toISO(today) };
  }
  return {};
}

// ─── WhatsApp ─────────────────────────────────────────────────────────────────

function WhatsAppIcon({ size = 14 }: { size?: number }) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="currentColor"
      style={{ verticalAlign: '-2px' }}
    >
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
    </svg>
  );
}

function buildWhatsAppUrl(order: {
  id: string;
  numPedSar: string;
  situa: number;
  statusDescr?: string | null;
  total: number | string;
  dtPedido: string;
  razaoCliente?: string | null;
  nomeCliente?: string | null;
  idCliente: number | string;
}): string {
  const nome = order.razaoCliente ?? order.nomeCliente ?? `Cód. ${order.idCliente}`;
  const status =
    order.statusDescr ??
    STATUS[order.situa]?.label ??
    SITUA_LABEL[order.situa] ??
    String(order.situa);
  const pdfUrl = `${window.location.origin}/pedidos/${order.id}/imprimir`;
  const text = [
    `*Pedido ${order.numPedSar}*`,
    `Cliente: ${nome}`,
    `Data: ${fmtDate(order.dtPedido)}`,
    `Total: ${fmt(order.total)}`,
    `Status: ${status}`,
    ``,
    `PDF: ${pdfUrl}`,
  ].join('\n');
  return `https://wa.me/?text=${encodeURIComponent(text)}`;
}

// ─── Status Config ────────────────────────────────────────────────────────────

const STATUS: Record<number, { label: string; color: string; rowBg: string; tagColor: string }> = {
  0: { label: 'Orçamento', color: '#475569', rowBg: '#f8fafc', tagColor: 'default' },
  1: { label: 'Ag. Aprovação', color: '#d46b08', rowBg: '#fffbe6', tagColor: 'orange' },
  2: { label: 'Transmitido', color: '#389e0d', rowBg: '#f6ffed', tagColor: 'green' },
  3: { label: 'Cancelado', color: '#cf1322', rowBg: '#fff1f0', tagColor: 'red' },
  4: { label: 'Faturado', color: '#1d39c4', rowBg: '#f0f5ff', tagColor: 'geekblue' },
};

// ─── useOrderStats ────────────────────────────────────────────────────────────

function useOrderStats() {
  const all = useOrderList({ limit: 1 });
  const pendentes = useOrderList({ limit: 1, situa: 1 });
  const aprovados = useOrderList({ limit: 1, situa: 2 });
  const faturados = useOrderList({ limit: 1, situa: 4 });
  return {
    total: all.data?.total ?? 0,
    pendentes: pendentes.data?.total ?? 0,
    aprovados: aprovados.data?.total ?? 0,
    faturados: faturados.data?.total ?? 0,
    loaded: !!all.data,
  };
}

type OrderStats = ReturnType<typeof useOrderStats>;

// ─── OrdersMetrics ────────────────────────────────────────────────────────────

function OrdersMetrics({ stats }: { stats: OrderStats }) {
  const metrics = [
    {
      label: 'Total de Pedidos',
      value: stats.total,
      icon: <ShoppingCartOutlined />,
      color: '#003B8E',
    },
    {
      label: 'Ag. Aprovação',
      value: stats.pendentes,
      icon: <ClockCircleOutlined />,
      color: '#d46b08',
    },
    { label: 'Aprovados', value: stats.aprovados, icon: <CheckCircleOutlined />, color: '#389e0d' },
    { label: 'Faturados', value: stats.faturados, icon: <DollarOutlined />, color: '#1d39c4' },
  ];

  return (
    <Row gutter={[12, 12]} style={{ marginBottom: 20 }}>
      {metrics.map((m) => (
        <Col key={m.label} xs={12} sm={6}>
          <Card
            style={{
              borderRadius: 10,
              border: '1px solid #EBF0F5',
              boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
            }}
            styles={{ body: { padding: '14px 18px' } }}
          >
            <Space size={10} align="center">
              <div
                style={{
                  width: 36,
                  height: 36,
                  borderRadius: 8,
                  background: `${m.color}15`,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 16,
                  color: m.color,
                  flexShrink: 0,
                }}
              >
                {m.icon}
              </div>
              <div>
                <Text
                  style={{
                    fontSize: 11,
                    color: '#64748B',
                    fontWeight: 600,
                    textTransform: 'uppercase',
                    letterSpacing: '0.06em',
                    display: 'block',
                  }}
                >
                  {m.label}
                </Text>
                <Text strong style={{ fontSize: 20, color: '#1F2937', lineHeight: 1.2 }}>
                  {stats.loaded ? m.value.toLocaleString('pt-BR') : <Spin size="small" />}
                </Text>
              </div>
            </Space>
          </Card>
        </Col>
      ))}
    </Row>
  );
}

// ─── OrderStatusBadge ─────────────────────────────────────────────────────────

function OrderStatusBadge({ situa, descr }: { situa: number; descr?: string }) {
  const cfg = STATUS[situa];
  const label = descr ?? cfg?.label ?? SITUA_LABEL[situa] ?? String(situa);
  return (
    <Tag
      color={cfg?.tagColor ?? 'default'}
      style={{ borderRadius: 20, fontWeight: 600, fontSize: 11, padding: '1px 10px' }}
    >
      {label}
    </Tag>
  );
}

// ─── OrderActionsMenu ─────────────────────────────────────────────────────────

const MOTIVOS_CANCELAMENTO = [
  'Cliente desistiu',
  'Preço',
  'Prazo de entrega',
  'Erro de lançamento',
  'Outro',
];

function OrderActionsMenu({
  order,
  onView,
}: {
  order: PedidoSummary;
  onView: (id: string) => void;
}) {
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { message: msg } = App.useApp();
  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelForm] = Form.useForm<{ motivo: string; descricao?: string }>();

  const cancelMutation = useMutation({
    mutationFn: (body: { motivo: string; descricao?: string }) =>
      apiFetch(`/orders/${order.id}/cancel`, { method: 'PATCH', body }),
    onSuccess: () => {
      void msg.success('Orçamento cancelado.');
      setCancelOpen(false);
      void qc.invalidateQueries({ queryKey: ['orders'] });
    },
    onError: (e: unknown) => void msg.error(e instanceof Error ? e.message : 'Erro ao cancelar'),
  });

  // Orçamento (situa 0) pode ser editado e cancelado; transmitido, não.
  const canCancel = order.situa === 0 && order.fonte !== 'erp';
  const canEdit = canCancel;

  const items: MenuProps['items'] = [
    {
      key: 'view',
      icon: <EyeOutlined />,
      label: 'Ver detalhes',
      onClick: () => onView(order.id),
    },
    {
      key: 'edit',
      icon: <EditOutlined />,
      label: 'Editar orçamento',
      disabled: !canEdit,
      onClick: () => {
        if (!canEdit) return;
        void navigate({ to: '/pedidos/novo', search: { editar: order.id } });
      },
    },
    {
      key: 'duplicate',
      icon: <CopyOutlined style={{ color: '#0057D9' }} />,
      label: <span style={{ color: '#0057D9', fontWeight: 600 }}>Duplicar pedido</span>,
      onClick: () =>
        void navigate({ to: '/pedidos/novo', search: { clientId: String(order.idCliente) } }),
    },
    { type: 'divider' },
    {
      key: 'pdf',
      icon: <FilePdfOutlined />,
      label: 'Gerar PDF',
      onClick: () => void navigate({ to: '/pedidos/$id/imprimir', params: { id: order.id } }),
    },
    {
      key: 'whatsapp',
      icon: (
        <span style={{ color: '#25D366' }}>
          <WhatsAppIcon />
        </span>
      ),
      label: <span style={{ color: '#25D366', fontWeight: 600 }}>Enviar pelo WhatsApp</span>,
      onClick: () => window.open(buildWhatsAppUrl(order), '_blank'),
    },
    {
      key: 'cancel',
      icon: <CloseCircleOutlined />,
      label: 'Cancelar pedido',
      danger: true,
      disabled: !canCancel,
      onClick: () => {
        if (!canCancel) return;
        cancelForm.resetFields();
        setCancelOpen(true);
      },
    },
  ];

  return (
    // stopPropagation: o clique nos "..." não pode acionar o clique da LINHA
    // (que abre o detalhe) — o menu abre sozinho e só a opção escolhida age.
    <span onClick={(e) => e.stopPropagation()}>
      <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
        <Button type="text" icon={<EllipsisOutlined />} size="small" />
      </Dropdown>

      <Modal
        title={`Cancelar orçamento ${order.numPedSar}?`}
        open={cancelOpen}
        onCancel={() => setCancelOpen(false)}
        okText="Cancelar pedido"
        okButtonProps={{ danger: true }}
        cancelText="Voltar"
        confirmLoading={cancelMutation.isPending}
        onOk={() =>
          void cancelForm.validateFields().then((values) => cancelMutation.mutate(values))
        }
        centered
        width={480}
      >
        <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
          O pedido será marcado como cancelado. Esta ação não pode ser desfeita.
        </Typography.Text>
        <Form form={cancelForm} layout="vertical">
          <Form.Item
            name="motivo"
            label="Motivo do cancelamento"
            rules={[{ required: true, message: 'Informe o motivo' }]}
          >
            <Select
              placeholder="Selecione o motivo"
              options={MOTIVOS_CANCELAMENTO.map((m) => ({ value: m, label: m }))}
            />
          </Form.Item>
          <Form.Item name="descricao" label="Descrição (opcional)">
            <Input.TextArea
              rows={3}
              maxLength={500}
              showCount
              placeholder="Detalhe o que aconteceu, se quiser"
            />
          </Form.Item>
        </Form>
      </Modal>
    </span>
  );
}

// ─── OrderDetailModal ─────────────────────────────────────────────────────────

function OrderDetailModal({ id, onClose }: { id: string | null; onClose: () => void }) {
  const navigate = useNavigate();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const { data, isLoading } = useOrderDetail(id ?? undefined);

  const timelineItems = (data?.historico ?? []).map((h) => ({
    dot:
      h.situaNova === 2 ? (
        <CheckCircleOutlined style={{ color: '#389e0d' }} />
      ) : h.situaNova === 3 ? (
        <CloseCircleOutlined style={{ color: '#cf1322' }} />
      ) : (
        <ClockCircleOutlined style={{ color: '#d46b08' }} />
      ),
    content: (
      <span style={{ fontSize: 13 }}>
        <Text type="secondary">{new Date(h.changedAt).toLocaleString('pt-BR')}</Text>
        {' — '}
        {h.situaAnterior === null ? (
          <strong>Pedido criado</strong>
        ) : (
          <>
            Status alterado para{' '}
            <strong>{STATUS[h.situaNova]?.label ?? SITUA_LABEL[h.situaNova] ?? h.situaNova}</strong>
          </>
        )}
        {h.nota && <Text type="secondary"> · {h.nota}</Text>}
      </span>
    ),
  }));

  const label: React.CSSProperties = {
    fontSize: 11,
    fontWeight: 700,
    letterSpacing: '0.08em',
    textTransform: 'uppercase',
    color: '#94A3B8',
    marginBottom: 2,
    display: 'block',
  };

  return (
    <Modal
      title={data ? `Pedido ${data.numPedSar}` : 'Detalhes do Pedido'}
      open={!!id}
      onCancel={onClose}
      centered
      width={isMobile ? '95vw' : 860}
      destroyOnHidden
      styles={{
        body: { padding: '20px 24px', maxHeight: 'calc(85vh - 110px)', overflowY: 'auto' },
      }}
      footer={
        <Space>
          <Button onClick={onClose}>Fechar</Button>
          {data && (
            <Button
              icon={
                <span style={{ color: '#25D366' }}>
                  <WhatsAppIcon />
                </span>
              }
              style={{ color: '#25D366', borderColor: '#25D366' }}
              onClick={() => window.open(buildWhatsAppUrl(data), '_blank')}
            >
              WhatsApp
            </Button>
          )}
          {data && (
            <Button
              type="primary"
              icon={<FilePdfOutlined />}
              onClick={() =>
                void navigate({ to: '/pedidos/$id/imprimir', params: { id: data.id } })
              }
            >
              Gerar PDF
            </Button>
          )}
        </Space>
      }
    >
      {isLoading && <Spin style={{ display: 'block', margin: '48px auto' }} />}

      {data && (
        <Space orientation="vertical" size={20} style={{ width: '100%' }}>
          {/* Status */}
          <div>
            <OrderStatusBadge situa={data.situa} descr={data.statusDescr} />
          </div>

          {/* Dados principais */}
          <Card
            styles={{ body: { padding: '14px 16px' } }}
            style={{ borderRadius: 8, background: '#F8FAFC', border: '1px solid #EBF0F5' }}
          >
            <Row gutter={[16, 10]}>
              <Col span={6}>
                <span style={label}>Pedido</span>
                <Text strong>{data.numPedSar}</Text>
              </Col>
              <Col span={6}>
                <span style={label}>Data</span>
                <Text>{fmtDate(data.dtPedido)}</Text>
              </Col>
              <Col span={6}>
                <span style={label}>Total</span>
                <Text strong style={{ color: '#003B8E', fontSize: 16 }}>
                  {fmt(data.total)}
                </Text>
              </Col>
              {data.descontoPerc && Number(data.descontoPerc) > 0 && (
                <Col span={6}>
                  <span style={label}>Desconto</span>
                  <Text>{Number(data.descontoPerc).toLocaleString('pt-BR')}%</Text>
                </Col>
              )}
              <Col span={12}>
                <span style={label}>Cliente</span>
                <Text strong style={{ display: 'block' }}>
                  {data.razaoCliente ?? data.nomeCliente ?? `Cód. ${data.idCliente}`}
                </Text>
                {data.nomeCliente && data.razaoCliente && (
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {data.nomeCliente}
                  </Text>
                )}
              </Col>
              <Col span={12}>
                <span style={label}>Representante</span>
                <Text>{data.nomeVendedor ?? `Cód. ${data.codVendedor}`}</Text>
              </Col>
              {data.endEntrega && (
                <Col span={24}>
                  <span style={label}>End. Entrega</span>
                  <Text type="secondary">{data.endEntrega}</Text>
                </Col>
              )}
              {data.obs && (
                <Col span={24}>
                  <span style={label}>Observações</span>
                  <Text type="secondary">{data.obs}</Text>
                </Col>
              )}
            </Row>
          </Card>

          {/* Itens */}
          {data.itens?.length > 0 && (
            <div>
              <Text style={{ ...label, marginBottom: 8 }}>
                Itens do Pedido ({data.itens.length})
              </Text>
              <Table
                rowKey="id"
                dataSource={data.itens}
                size="small"
                pagination={false}
                style={{ borderRadius: 8, border: '1px solid #EBF0F5' }}
                columns={[
                  {
                    title: 'Produto',
                    key: 'produto',
                    render: (_: unknown, item) => (
                      <Space orientation="vertical" size={0}>
                        <Text style={{ fontSize: 11, color: '#94A3B8' }}>{item.codProduto}</Text>
                        <Text style={{ fontWeight: 500 }}>{item.descProduto}</Text>
                      </Space>
                    ),
                  },
                  {
                    title: 'Qtd.',
                    dataIndex: 'qtd',
                    width: 70,
                    align: 'right' as const,
                    render: (v: string) => <Text className="tabular-nums">{Number(v)}</Text>,
                  },
                  {
                    title: 'Preço Un.',
                    dataIndex: 'precoUnitario',
                    width: 120,
                    align: 'right' as const,
                    render: (v: string) => <Text className="tabular-nums">{fmt(Number(v))}</Text>,
                  },
                  {
                    title: 'Total',
                    dataIndex: 'total',
                    width: 120,
                    align: 'right' as const,
                    render: (v: string) => (
                      <Text strong className="tabular-nums" style={{ color: '#003B8E' }}>
                        {fmt(Number(v))}
                      </Text>
                    ),
                  },
                ]}
                summary={() => (
                  <Table.Summary.Row>
                    <Table.Summary.Cell index={0} colSpan={3} align="right">
                      <Text strong>Total do Pedido</Text>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={1} align="right">
                      <Text strong style={{ color: '#003B8E' }}>
                        {fmt(data.total)}
                      </Text>
                    </Table.Summary.Cell>
                  </Table.Summary.Row>
                )}
              />
            </div>
          )}

          {/* Histórico */}
          {timelineItems.length > 0 && (
            <div>
              <Text style={{ ...label, marginBottom: 10 }}>Histórico</Text>
              <Timeline items={timelineItems} />
            </div>
          )}
        </Space>
      )}
    </Modal>
  );
}

// ─── MobileOrderCard ──────────────────────────────────────────────────────────

function MobileOrderCard({
  order,
  onView,
}: {
  order: PedidoSummary;
  onView: (id: string) => void;
}) {
  const navigate = useNavigate();
  const cfg = STATUS[order.situa];
  const nome = order.razaoCliente ?? order.nomeCliente;

  return (
    <Card
      style={{
        borderRadius: 10,
        marginBottom: 10,
        border: `1px solid ${cfg?.rowBg ?? '#EBF0F5'}`,
        background: cfg?.rowBg ?? '#fff',
        boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
      }}
      styles={{ body: { padding: '14px 16px' } }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
        <Text strong style={{ fontSize: 15, color: '#003B8E' }}>
          {order.numPedSar}
        </Text>
        <OrderStatusBadge situa={order.situa} descr={order.statusDescr} />
      </div>
      {nome && (
        <Text style={{ fontSize: 13, fontWeight: 500, display: 'block', marginBottom: 2 }}>
          {nome}
        </Text>
      )}
      <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 6 }}>
        {fmtDate(order.dtPedido)}
      </Text>
      <Text strong style={{ fontSize: 16, color: '#003B8E' }}>
        {fmt(order.total)}
      </Text>
      <div style={{ marginTop: 10, display: 'flex', gap: 8 }}>
        <Button
          size="small"
          icon={<EyeOutlined />}
          onClick={() =>
            order.situa === 0
              ? void navigate({ to: '/pedidos/$id', params: { id: order.id } })
              : onView(order.id)
          }
          style={{ borderRadius: 6 }}
        >
          Ver
        </Button>
        <Button
          size="small"
          icon={<CopyOutlined />}
          style={{ borderRadius: 6 }}
          onClick={() =>
            void navigate({ to: '/pedidos/novo', search: { clientId: String(order.idCliente) } })
          }
        >
          Duplicar
        </Button>
        <Button
          size="small"
          icon={
            <span style={{ color: '#25D366' }}>
              <WhatsAppIcon />
            </span>
          }
          style={{ borderRadius: 6 }}
          onClick={() => window.open(buildWhatsAppUrl(order), '_blank')}
        >
          WhatsApp
        </Button>
      </div>
    </Card>
  );
}

// ─── OrdersPage ───────────────────────────────────────────────────────────────

export function OrdersPage() {
  const navigate = useNavigate();
  const screens = useBreakpoint();
  const isMobile = !screens.md;
  const { message: msg } = App.useApp();
  const { orders: pendingOrders, refresh: refreshPending } = usePendingOrders();

  const stats = useOrderStats();

  const [search, setSearch] = useState('');
  const [query, setQuery] = useState('');
  const [situaFilter, setSituaFilter] = useState<number | undefined>();
  const [period, setPeriod] = useState('');
  const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [page, setPage] = useState(1);
  const [drawerOrderId, setDrawerOrderId] = useState<string | null>(null);
  const limit = 20;

  // Intervalo customizado (datas antigas) tem prioridade sobre o atalho de período.
  const periodR = period ? periodRange(period) : {};
  const from = range ? range[0].format('YYYY-MM-DD') : periodR.from;
  const to = range ? range[1].format('YYYY-MM-DD') : periodR.to;

  const { data, isLoading, isFetching } = useOrderList({
    numPedSar: query || undefined,
    situa: situaFilter,
    from,
    to,
    page,
    limit,
  });

  const rows = useMemo(() => data?.data ?? [], [data]);
  const total = data?.total ?? 0;

  const hasFilters = !!query || !!situaFilter || !!period || !!range;

  function commitSearch() {
    setQuery(search.trim());
    setPage(1);
  }

  function clearFilters() {
    setSearch('');
    setQuery('');
    setSituaFilter(undefined);
    setPeriod('');
    setRange(null);
    setPage(1);
  }

  // Valor total da página atual (sem query separada)
  const valorPagina = useMemo(() => rows.reduce((a, o) => a + Number(o.total), 0), [rows]);

  // ── Colunas desktop ─────────────────────────────────────────────────────────
  const columns: TableColumnsType<PedidoSummary> = [
    {
      title: 'Pedido',
      key: 'pedido',
      width: 140,
      render: (_: unknown, row: PedidoSummary) => (
        <Link to="/pedidos/$id" params={{ id: row.id }}>
          <Text strong className="tabular-nums" style={{ color: '#003B8E' }}>
            {row.numPedSar}
          </Text>
        </Link>
      ),
    },
    {
      title: 'Cliente',
      key: 'cliente',
      minWidth: 240,
      render: (_: unknown, row: PedidoSummary) => {
        const nome = row.razaoCliente ?? row.nomeCliente;
        const subtit = row.nomeCliente && row.razaoCliente ? row.nomeCliente : null;
        return (
          <div>
            {nome ? (
              <Text
                strong
                style={{ fontSize: 14, color: '#1F2937', display: 'block', lineHeight: 1.3 }}
              >
                {nome}
              </Text>
            ) : (
              <Text type="secondary" style={{ fontSize: 13 }}>
                Cód. {row.idCliente}
              </Text>
            )}
            {subtit && (
              <Text style={{ fontSize: 12, color: '#64748B', display: 'block', lineHeight: 1.3 }}>
                {subtit}
              </Text>
            )}
          </div>
        );
      },
    },
    {
      title: 'Status',
      dataIndex: 'situa',
      key: 'status',
      width: 140,
      render: (s: number, row: PedidoSummary) => (
        <OrderStatusBadge situa={s} descr={row.statusDescr} />
      ),
    },
    {
      title: 'Total',
      dataIndex: 'total',
      key: 'total',
      width: 130,
      align: 'right' as const,
      render: (v: string) => (
        <Text strong className="tabular-nums" style={{ color: '#003B8E', fontSize: 14 }}>
          {fmt(v)}
        </Text>
      ),
    },
    {
      title: 'Data',
      dataIndex: 'dtPedido',
      key: 'dtPedido',
      width: 110,
      render: (v: string) => <Text style={{ fontSize: 13, color: '#475569' }}>{fmtDate(v)}</Text>,
    },
    {
      title: '',
      key: 'actions',
      width: 100,
      render: (_: unknown, row: PedidoSummary) => (
        <Space size={4}>
          <Button
            size="small"
            icon={<EyeOutlined />}
            type="primary"
            style={{ borderRadius: 6 }}
            title="Ver detalhes"
            onClick={() =>
              row.situa === 0
                ? void navigate({ to: '/pedidos/$id', params: { id: row.id } })
                : setDrawerOrderId(row.id)
            }
          />
          <OrderActionsMenu order={row} onView={(id) => setDrawerOrderId(id)} />
        </Space>
      ),
    },
  ];

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      {/* ── Cabeçalho ─────────────────────────────────────────────────── */}
      <div
        style={{
          display: 'flex',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
          marginBottom: 20,
        }}
      >
        <div>
          <Title level={3} style={{ margin: 0, color: '#003B8E' }}>
            Pedidos
          </Title>
          <p style={{ margin: '4px 0 0', color: '#64748B', fontSize: 14 }}>
            Acompanhe seus pedidos, status de aprovação e histórico comercial.
          </p>
        </div>
        {!isMobile && (
          <Button
            type="primary"
            icon={<PlusOutlined />}
            size="large"
            style={{
              borderRadius: 8,
              fontWeight: 600,
              backgroundColor: '#389e0d',
              borderColor: '#389e0d',
            }}
            onClick={() => void navigate({ to: '/pedidos/novo' })}
          >
            Novo Pedido
          </Button>
        )}
      </div>

      {/* ── Métricas ──────────────────────────────────────────────────── */}
      <OrdersMetrics stats={stats} />

      {/* ── Filtros ───────────────────────────────────────────────────── */}
      <Card
        style={{
          borderRadius: 10,
          border: '1px solid #EBF0F5',
          boxShadow: '0 1px 4px rgba(0,0,0,0.05)',
          marginBottom: 20,
        }}
        styles={{ body: { padding: '14px 20px' } }}
      >
        <Row gutter={[12, 12]} align="middle">
          {/* Busca */}
          <Col xs={24} md={6}>
            <div style={{ position: 'relative' }}>
              <SearchOutlined
                style={{
                  position: 'absolute',
                  left: 10,
                  top: '50%',
                  transform: 'translateY(-50%)',
                  color: '#94A3B8',
                  zIndex: 1,
                }}
              />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') commitSearch();
                }}
                onBlur={commitSearch}
                placeholder="Buscar por nº do pedido..."
                style={{
                  width: '100%',
                  height: 32,
                  padding: '0 11px 0 32px',
                  border: '1px solid #d9d9d9',
                  borderRadius: 6,
                  fontSize: 13,
                  outline: 'none',
                  color: '#1F2937',
                  boxSizing: 'border-box',
                }}
              />
            </div>
          </Col>

          {/* Status */}
          <Col xs={12} sm={8} md={4}>
            <Select
              style={{ width: '100%' }}
              placeholder="Status"
              allowClear
              value={situaFilter}
              onChange={(v) => {
                setSituaFilter(v);
                setPage(1);
              }}
              options={[
                { value: 0, label: 'Orçamento' },
                { value: 1, label: 'Ag. Aprovação' },
                { value: 2, label: 'Transmitido' },
                { value: 3, label: 'Cancelado' },
                { value: 4, label: 'Faturado' },
              ]}
            />
          </Col>

          {/* Período (atalho) */}
          <Col xs={12} sm={8} md={4}>
            <Select
              style={{ width: '100%' }}
              placeholder="Período"
              allowClear
              value={period || undefined}
              onChange={(v) => {
                setPeriod(v ?? '');
                if (v) setRange(null); // atalho limpa o intervalo customizado
                setPage(1);
              }}
              options={[
                { value: 'today', label: 'Hoje' },
                { value: '7d', label: 'Últimos 7 dias' },
                { value: '30d', label: 'Últimos 30 dias' },
              ]}
            />
          </Col>

          {/* Intervalo de datas (para pedidos antigos) */}
          <Col xs={24} sm={16} md={6}>
            <RangePicker
              style={{ width: '100%' }}
              value={range}
              format="DD/MM/YYYY"
              allowClear
              placeholder={['Data inicial', 'Data final']}
              onChange={(dates) => {
                if (dates && dates[0] && dates[1]) {
                  setRange([dates[0], dates[1]]);
                  setPeriod(''); // intervalo customizado tem prioridade
                } else {
                  setRange(null);
                }
                setPage(1);
              }}
            />
          </Col>

          {/* Limpar */}
          <Col xs={12} sm={8} md={4}>
            <Button
              style={{ width: '100%', borderRadius: 6 }}
              icon={<ClearOutlined />}
              disabled={!hasFilters}
              onClick={clearFilters}
            >
              Limpar
            </Button>
          </Col>

          {/* Contador */}
          <Col>
            <Text style={{ fontSize: 12, color: '#94A3B8' }}>
              {data?.total !== undefined ? `${total.toLocaleString('pt-BR')} pedidos` : '…'}
            </Text>
          </Col>
        </Row>
      </Card>

      {/* ── Pedidos offline pendentes ─────────────────────────────────── */}
      {pendingOrders.length > 0 && (
        <Card
          style={{ borderRadius: 10, border: '1px solid #faad14', marginBottom: 16 }}
          styles={{ body: { padding: '12px 16px' } }}
        >
          <div style={{ fontWeight: 600, marginBottom: 8, color: '#d48806' }}>
            {pendingOrders.length === 1
              ? '1 pedido aguardando sincronização'
              : `${pendingOrders.length} pedidos aguardando sincronização`}
          </div>
          {pendingOrders.map((o) => (
            <div
              key={o.idempotencyKey}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '6px 0',
                borderTop: '1px solid #fde8a4',
                fontSize: 13,
              }}
            >
              <span>
                <Tag color={o.status === 'failed' ? 'error' : 'warning'}>
                  {o.status === 'failed' ? 'Falha' : 'Pendente'}
                </Tag>
                <span style={{ fontWeight: 500 }}>{o.clienteNome}</span>
                {o.failReason && (
                  <span style={{ color: '#cf1322', marginLeft: 8 }}>— {o.failReason}</span>
                )}
                <span style={{ color: '#94a3b8', marginLeft: 8 }}>
                  {new Date(o.createdAt).toLocaleString('pt-BR')}
                </span>
              </span>
              <Space size={4}>
                {o.status === 'failed' && (
                  <Button
                    size="small"
                    onClick={() => {
                      void retryPendingOrder(o.idempotencyKey).then(refreshPending);
                    }}
                  >
                    Tentar novamente
                  </Button>
                )}
                <Button
                  size="small"
                  danger
                  onClick={() => {
                    void removePendingOrder(o.idempotencyKey).then(refreshPending);
                    void msg.success('Pedido removido da fila');
                  }}
                >
                  Descartar
                </Button>
              </Space>
            </div>
          ))}
        </Card>
      )}

      {/* ── Lista / tabela ────────────────────────────────────────────── */}
      {isLoading ? (
        <div style={{ textAlign: 'center', padding: 64 }}>
          <Spin size="large" />
        </div>
      ) : rows.length === 0 ? (
        <Card
          style={{ borderRadius: 10, border: '1px solid #EBF0F5' }}
          styles={{ body: { padding: 0 } }}
        >
          <div style={{ padding: '48px 0', textAlign: 'center' }}>
            <ShoppingCartOutlined
              style={{ fontSize: 56, color: '#D9E2EC', display: 'block', marginBottom: 16 }}
            />
            <Text strong style={{ fontSize: 15, display: 'block' }}>
              Nenhum pedido encontrado
            </Text>
            <Text type="secondary">Tente alterar os filtros ou crie um novo pedido.</Text>
            <div style={{ marginTop: 20 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => void navigate({ to: '/pedidos/novo' })}
                style={{ borderRadius: 8 }}
              >
                Novo Pedido
              </Button>
            </div>
          </div>
        </Card>
      ) : isMobile ? (
        /* ── Mobile ────────────────────────────────────────────────────── */
        <div>
          {rows.map((o) => (
            <MobileOrderCard key={o.id} order={o} onView={(id) => setDrawerOrderId(id)} />
          ))}
          <Text
            style={{
              fontSize: 12,
              color: '#94A3B8',
              display: 'block',
              textAlign: 'center',
              padding: '8px 0 16px',
            }}
          >
            Mostrando {rows.length} de {total} pedidos
          </Text>
        </div>
      ) : (
        /* ── Desktop ────────────────────────────────────────────────────── */
        <Card
          style={{
            borderRadius: 10,
            border: '1px solid #EBF0F5',
            boxShadow: '0 1px 6px rgba(0,0,0,0.06)',
          }}
          styles={{ body: { padding: 0 } }}
        >
          <Table<PedidoSummary>
            rowKey="id"
            columns={columns}
            dataSource={rows}
            size="middle"
            loading={isFetching}
            scroll={{ x: 900 }}
            onRow={(row) => ({
              onClick: () => {
                if (row.situa === 0) void navigate({ to: '/pedidos/$id', params: { id: row.id } });
                else setDrawerOrderId(row.id);
              },
              style: {
                background: STATUS[row.situa]?.rowBg ?? '#fff',
                cursor: 'pointer',
                verticalAlign: 'top',
              },
            })}
            pagination={{
              current: page,
              pageSize: limit,
              total,
              showSizeChanger: false,
              showTotal: (t, [s, e]) => `Mostrando ${s}–${e} de ${t} pedidos`,
              onChange: (p) => setPage(p),
              style: { padding: '12px 24px' },
            }}
            style={{ borderRadius: 10, overflow: 'hidden' }}
            footer={() => (
              <div style={{ textAlign: 'right', padding: '4px 8px' }}>
                <Text style={{ fontSize: 12, color: '#64748B' }}>
                  Valor nesta página:{' '}
                  <Text strong style={{ color: '#003B8E' }}>
                    {fmt(valorPagina)}
                  </Text>
                </Text>
              </div>
            )}
          />
        </Card>
      )}

      {/* ── Drawer de detalhe ─────────────────────────────────────────── */}
      <OrderDetailModal id={drawerOrderId} onClose={() => setDrawerOrderId(null)} />

      {/* FAB mobile */}
      {isMobile && (
        <Button
          type="primary"
          shape="circle"
          icon={<PlusOutlined />}
          size="large"
          onClick={() => void navigate({ to: '/pedidos/novo' })}
          style={{
            position: 'fixed',
            bottom: 24,
            right: 24,
            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',
          }}
        />
      )}

      {/* Aviso de novo pedido via mensagem se tentativa em mobile */}
      {isMobile && (
        <Button
          style={{ display: 'none' }}
          onClick={() => void msg.info('Use o botão + para criar um novo pedido.')}
        />
      )}

      <Divider style={{ display: 'none' }} />

      <style>{`
        .ant-table-row:hover td { background: inherit !important; filter: brightness(0.97); }
      `}</style>
    </div>
  );
}
