'use client';

import { message } from '@/lib/feedback/message';

import React, { useState, useMemo, useCallback } from 'react';
import dynamic from 'next/dynamic';
/**
 * Listagem Cursor Agents (`/projetos/[id]/qualidade/cursor-agents`). FRONT-S2-02.ek
 */

import { BarChart3, Bot, CheckCircle2, CirclePlay, Filter, Menu, XCircle } from 'lucide-react';
import {
    Alert,
    Badge,
    Button,
    Col,
    Input,
    Modal,
    Row,
    Select,
    Space,
    Tooltip,
} from 'antd';
import { ICON_SIZE_MD } from '@/components/icons';
import { LazyDataTable, LazyExportButton } from '@/components/lazy';
import btnHeaderStyles from '@/components/ui/buttons/ButtonHeaderIcon/ButtonHeaderIcon.module.scss';
import type { ColumnsType } from 'antd/es/table';
import { useRouter } from 'next/navigation';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useResponsiveModalProps } from '@/hooks/useResponsiveModalProps';
import { useIsMobile } from '@/hooks/useIsMobile';
import { queryKeys } from '@/lib/cache/queryKeys';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { formatDate } from '@/lib/utils/export';
import dayjs from 'dayjs';
import Link from 'next/link';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { DetailPageLayout } from '@/components/layouts/DetailPageLayout';
import { FormGroup } from '@/components/form';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import { ButtonHeaderIcon } from '@/components/ui';
import { OperativeRouteHint } from '@/components/layouts/OperativeRouteHint/OperativeRouteHint';
import { MobileFiltersDrawer, MobilePageActionBar } from '@/components/filters';
import type { DetailPageFetchState } from '@/components/layouts/DetailPageLayout';
import { detailPageQueryErrorSubTitle } from '@/lib/utils/detailPageQueryErrorSubTitle';
import type { CursorAgent, CursorAgentsPaginatedResponse } from './types';
import { renderCursorAgentStatusTag } from './cursorAgentsDisplay';
import {
        projetoQualidadeCursorAgentsCreatePath,
        projetoQualidadeCursorAgentsDashboardPath,
        projetoQualidadeCursorAgentDetalhePath} from './cursorAgentsPaths';
import { FiltrosModalFooterPadrao,
    ListPageCreateFloatButton} from '@/components/listings';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';

const ModalOpcoesCursorAgent = dynamic(
    () => import('./ModalOpcoesCursorAgent').then((m) => m.ModalOpcoesCursorAgent),
    { ssr: false },
);

const { Search } = Input;

const STATUS_CURSOR_LABEL: Record<string, string> = {
    CREATING: 'Criando',
    RUNNING: 'Rodando',
    FINISHED: 'Finalizado',
    FAILED: 'Falhou',
    CANCELLED: 'Cancelado'};

export interface ProjetoQualidadeCursorAgentsListaScreenProps {
    projetoId: string;
}

export function ProjetoQualidadeCursorAgentsListaScreen({
    projetoId}: ProjetoQualidadeCursorAgentsListaScreenProps) {
    const router = useRouter();
    const isMobile = useIsMobile();
    const { canEditar, permsLoading } = useProjetoWriteGates();
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(15);
    const [searchValue, setSearchValue] = useState('');
    const [projetoFilter, setProjetoFilter] = useState<string>('');
    const [agenteIaFilter, setAgenteIaFilter] = useState<string>('');
    const [statusFilter, setStatusFilter] = useState<string>('');
    const [filtrosModalOpen, setFiltrosModalOpen] = useState(false);
    const [draftSearchInput, setDraftSearchInput] = useState('');
    const [draftProjetoFilter, setDraftProjetoFilter] = useState('');
    const [draftAgenteIaFilter, setDraftAgenteIaFilter] = useState('');
    const [draftStatusFilter, setDraftStatusFilter] = useState('');
    const [opcoesItem, setOpcoesItem] = useState<CursorAgent | null>(null);
    const filtrosModalLayout = useResponsiveModalProps();

    const listFilters = {
        page: currentPage,
        per_page: pageSize,
        search: searchValue,
        projeto_id: projetoFilter,
        agente_ia_id: agenteIaFilter,
        status: statusFilter};

    const {
        data: agents,
        isLoading,
        isError: agentsQueryIsError,
        error: agentsQueryError,
        refetch} = useQueryCache<CursorAgentsPaginatedResponse<CursorAgent>>({
        queryKey: queryKeys.qa.cursorAgents.listForProjeto(listFilters, projetoId),
        endpoint: API_ENDPOINTS.qa.cursorAgents.index,
        params: {
            page: currentPage,
            per_page: pageSize,
            ...(searchValue && { search: searchValue }),
            ...(projetoFilter && { projeto_id: projetoFilter }),
            ...(agenteIaFilter && { agente_ia_id: agenteIaFilter }),
            ...(statusFilter && { status: statusFilter })},
        staleTime: 30 * 1000,
        gcTime: 5 * 60 * 1000,
        enabled: Boolean(projetoId.trim())});

    const syncStatusMutation = useMutationCache<void, number>({
        endpoint: (agentId) => API_ENDPOINTS.qa.cursorAgents.syncStatus(agentId),
        method: 'POST',
        invalidateQueries: [queryKeys.qa.cursorAgents.all],
        onSuccess: () => {
            message.success('Status sincronizado com sucesso!');
            refetch();
        },
        onError: (err: unknown) => {
            message.error(err instanceof Error ? err.message : 'Erro ao sincronizar status');
        }});

    const handleVer = useCallback(
        (item: CursorAgent) => {
            setOpcoesItem(null);
            router.push(projetoQualidadeCursorAgentDetalhePath(projetoId, item.id));
        },
        [router, projetoId]
    );

    const handleSincronizar = useCallback(
        (item: CursorAgent) => {
            setOpcoesItem(null);
            syncStatusMutation.mutate(item.id);
        },
        [syncStatusMutation]
    );

    const columns: ColumnsType<CursorAgent> = useMemo(
        () => [
            {
                title: 'Nome',
                dataIndex: 'name',
                key: 'name',
                sorter: (a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''), 'pt'),
                render: (text: string) => (
                    <span style={{ fontWeight: 600, color: '#2c3e50' }}>{text}</span>
                )},
            {
                title: 'Status',
                dataIndex: 'status',
                key: 'status',
                sorter: (a, b) => String(a.status ?? '').localeCompare(String(b.status ?? ''), 'pt'),
                render: (status: string) => renderCursorAgentStatusTag(status),
                filters: [
                    { text: 'Criando', value: 'CREATING' },
                    { text: 'Rodando', value: 'RUNNING' },
                    { text: 'Finalizado', value: 'FINISHED' },
                    { text: 'Falhou', value: 'FAILED' },
                    { text: 'Cancelado', value: 'CANCELLED' },
                ],
                onFilter: (value, record) => record.status === value},
            {
                title: 'Projeto',
                dataIndex: ['projeto', 'nome'],
                key: 'projeto',
                sorter: (a, b) =>
                    String(a.projeto?.nome ?? '').localeCompare(String(b.projeto?.nome ?? ''), 'pt'),
                render: (text: string, record: CursorAgent) =>
                    record.projeto ? (
                        <Link href={`/projetos/${record.projeto.id}`}>{text}</Link>
                    ) : (
                        <span style={{ color: '#999' }}>Sem projeto</span>
                    )},
            {
                title: 'Agente IA',
                dataIndex: ['agente_ia', 'nome'],
                key: 'agente_ia',
                sorter: (a, b) =>
                    String(a.agente_ia?.nome ?? '').localeCompare(String(b.agente_ia?.nome ?? ''), 'pt'),
                render: (text: string) => text || <span style={{ color: '#999' }}>N/A</span>},
            {
                title: 'Branch',
                dataIndex: 'branch_name',
                key: 'branch_name',
                sorter: (a, b) =>
                    String(a.branch_name ?? '').localeCompare(String(b.branch_name ?? ''), 'pt'),
                render: (text: string) => text || <span style={{ color: '#999' }}>-</span>},
            {
                title: 'PR',
                dataIndex: 'pr_url',
                key: 'pr_url',
                sorter: (a, b) => String(a.pr_url ?? '').localeCompare(String(b.pr_url ?? ''), 'pt'),
                render: (url: string) =>
                    url ? (
                        <a href={url} target="_blank" rel="noopener noreferrer">
                            Ver PR
                        </a>
                    ) : (
                        <span style={{ color: '#999' }}>-</span>
                    )},
            {
                title: 'Criado em',
                dataIndex: 'created_at',
                key: 'created_at',
                sorter: (a, b) =>
                    dayjs(a.created_at).valueOf() - dayjs(b.created_at).valueOf(),
                render: (date: string) => formatDate(date, true)},
            {
                title: '',
                key: 'acoes',
                width: 56,
                align: 'center',
                onCell: () => ({ onClick: (e: React.MouseEvent) => e.stopPropagation() }),
                render: (_: unknown, record: CursorAgent) => (
                    <Button
                        type="text"
                        size="small"
                        icon={<Menu />}
                        onClick={() => setOpcoesItem(record)}
                        aria-label="Opções"
                    />
                )},
        ],
        []
    );

    const limparTodosFiltros = useCallback(() => {
        setSearchValue('');
        setProjetoFilter('');
        setAgenteIaFilter('');
        setStatusFilter('');
        setDraftSearchInput('');
        setDraftProjetoFilter('');
        setDraftAgenteIaFilter('');
        setDraftStatusFilter('');
        setCurrentPage(1);
    }, []);

    const abrirModalFiltros = useCallback(() => {
        setDraftSearchInput(searchValue);
        setDraftProjetoFilter(projetoFilter);
        setDraftAgenteIaFilter(agenteIaFilter);
        setDraftStatusFilter(statusFilter);
        setFiltrosModalOpen(true);
    }, [searchValue, projetoFilter, agenteIaFilter, statusFilter]);

    const reporRascunhoFiltros = useCallback(() => {
        setDraftSearchInput('');
        setDraftProjetoFilter('');
        setDraftAgenteIaFilter('');
        setDraftStatusFilter('');
    }, []);

    const aplicarFiltrosModal = useCallback(() => {
        const q = draftSearchInput.trim();
        setSearchValue(q);
        setProjetoFilter(draftProjetoFilter.trim());
        setAgenteIaFilter(draftAgenteIaFilter.trim());
        setStatusFilter(draftStatusFilter);
        setCurrentPage(1);
        setFiltrosModalOpen(false);
    }, [draftSearchInput, draftProjetoFilter, draftAgenteIaFilter, draftStatusFilter]);

    const onPageChange = useCallback((page: number, size?: number) => {
        setCurrentPage(page);
        setPageSize(size || pageSize);
    }, [pageSize]);

    const idValid = Boolean(projetoId.trim());

    const fetchState: DetailPageFetchState = useMemo(() => {
        if (!idValid) return 'not_found';
        if (agentsQueryIsError && !agents) return 'error';
        if (isLoading && !agents) return 'loading';
        return 'ready';
    }, [idValid, agentsQueryIsError, agents, isLoading]);

    const agentsQueryErr =
        agentsQueryError instanceof Error
            ? agentsQueryError
            : agentsQueryError
              ? new Error(String(agentsQueryError))
              : null;

    const listErrorSubTitle = useMemo(
        () => detailPageQueryErrorSubTitle(agentsQueryError),
        [agentsQueryError]
    );

    const filtrosAtivosCount = useMemo(() => {
        let n = 0;
        if (searchValue.trim()) n += 1;
        if (statusFilter) n += 1;
        if (projetoFilter) n += 1;
        if (agenteIaFilter) n += 1;
        return n;
    }, [searchValue, statusFilter, projetoFilter, agenteIaFilter]);
    const filtrosComAlgumAtivo = filtrosAtivosCount > 0;

    const resumoFiltrosAplicados = useMemo(() => {
        const partes: string[] = [];
        const q = searchValue.trim();
        if (q) partes.push(`Pesquisa: "${q}"`);
        if (statusFilter) {
            partes.push(`Status: ${STATUS_CURSOR_LABEL[statusFilter] ?? statusFilter}`);
        }
        if (projetoFilter) partes.push(`Projeto (id): ${projetoFilter}`);
        if (agenteIaFilter) partes.push(`Agente IA (id): ${agenteIaFilter}`);
        return partes.length ? partes.join(' · ') : '';
    }, [searchValue, statusFilter, projetoFilter, agenteIaFilter]);

    /** Lista paginada — API pode devolver `data` não-array em erro/envelope atípico. */
    const agentsList = useMemo(
        () => (Array.isArray(agents?.data) ? agents.data : []),
        [agents?.data],
    );

    const cursorAgentsExportRows = useMemo(
        () =>
            agentsList.map((a) => ({
                name: a.name,
                status: a.status,
                projeto: a.projeto?.nome ?? '',
                agente_ia: a.agente_ia?.nome ?? '',
                branch_name: a.branch_name ?? '',
                pr_url: a.pr_url ?? '',
                created_at: a.created_at ? formatDate(a.created_at) : ''})),
        [agentsList]
    );

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Cursor Agents"
            showPageTitleIcon={false}
            titleSection="Cursor Agents"
            headerAction={
                fetchState === 'ready' ? (
                        <Space wrap size={8} align="center">
                            {!isMobile ? (
                                <Tooltip
                                    title={
                                        filtrosComAlgumAtivo
                                            ? `Filtros ativos (${filtrosAtivosCount}) — abrir para alterar pesquisa, status, projeto ou agente IA`
                                            : 'Definir pesquisa, status, projeto e agente IA na listagem'
                                    }
                                >
                                    <span style={{ display: 'inline-block' }}>
                                    <Badge dot={filtrosComAlgumAtivo} color="geekblue">
                                        <ButtonHeaderIcon
                                            data-testid="projeto-qualidade-cursor-agents-abrir-filtros"
                                            icon={<Filter size={ICON_SIZE_MD} aria-hidden />}
                                            title={
                                                filtrosAtivosCount > 0
                                                    ? `Filtros (${filtrosAtivosCount})`
                                                    : 'Filtros'
                                            }
                                            aria-label="Abrir filtros de agentes Cursor"
                                            aria-expanded={filtrosModalOpen}
                                            aria-haspopup="dialog"
                                            onClick={abrirModalFiltros}
                                            className={btnHeaderStyles.btnHeaderIcon}
                                        />
                                    </Badge>
                                    </span>
                                </Tooltip>
                            ) : null}
                            {!isMobile ? (
                                <Tooltip title="Exportar os agentes visíveis nesta página (Excel, PDF, CSV ou JSON)">
                                    <span style={{ display: 'inline-block' }}>
                                        <LazyExportButton
                                            data={cursorAgentsExportRows as unknown as Record<string, unknown>[]}
                                            columns={[
                                                { key: 'name', label: 'Nome' },
                                                { key: 'status', label: 'Status' },
                                                { key: 'projeto', label: 'Projeto' },
                                                { key: 'agente_ia', label: 'Agente IA' },
                                                { key: 'branch_name', label: 'Branch' },
                                                { key: 'pr_url', label: 'PR' },
                                                { key: 'created_at', label: 'Criado em' },
                                            ]}
                                            filename={`projeto-${projetoId}-cursor-agents`}
                                            title="Exportar agentes Cursor"
                                            iconOnly
                                            size="large"
                                            exportMenuMode="modal"
                                            className={btnHeaderStyles.btnHeaderIcon}
                                        />
                                    </span>
                                </Tooltip>
                            ) : null}
                            <Button
                                onClick={() =>
                                    router.push(projetoQualidadeCursorAgentsDashboardPath(projetoId))
                                }
                                icon={<BarChart3 size={ICON_SIZE_MD} aria-hidden />}
                            >
                                {isMobile ? 'Métricas' : 'Dashboard'}
                            </Button>
                        </Space>
                    ) : undefined
            }
        >
        <DetailPageLayout
            breadcrumbItems={[
                { title: 'Projetos', path: '/projetos' },
                ...(idValid
                    ? [
                          { title: 'Projeto', path: `/projetos/${projetoId}` },
                          {
                              title: 'Agentes Cursor',
                              path: `/projetos/${projetoId}/qualidade/cursor-agents`},
                      ]
                    : [{ title: 'Agentes Cursor' }]),
            ]}
            header={{
                title: 'Cursor Agents',
                titleContent: '',
                description: isMobile
                    ? 'Agentes de desenvolvimento automatizado via Cursor.'
                    : 'Gerenciar os agentes de desenvolvimento automatizado via API do Cursor — refine a listagem com Filtros no cabeçalho.',
            }}
            fetchState={fetchState}
            error={agentsQueryErr}
            onRetry={() => void refetch()}
            errorSubTitle={listErrorSubTitle}
            notFoundTitle="Projeto inválido"
            notFoundSubTitle="O identificador do projeto está ausente ou é inválido na rota."
            notFoundExtra={
                <Button type="primary" onClick={() => router.push('/projetos')}>
                    Voltar para projetos
                </Button>
            }
            wrapChildrenInCard={false}
        >
            {fetchState === 'ready' ? (
                <OperativeRouteHint
                    type="warning"
                    message="Governança operacional"
                    description="Agentes em falha ou há muito tempo em execução merecem sincronização e revisão do prompt ou permissões. Use Filtros no cabeçalho para refinar a lista; use o dashboard para visão agregada e o detalhe para evidências."
                >
                    <Space wrap>
                        <Button
                            type="primary"
                            onClick={() =>
                                router.push(projetoQualidadeCursorAgentsDashboardPath(projetoId))
                            }
                        >
                            Abrir dashboard
                        </Button>
                    </Space>
                </OperativeRouteHint>
            ) : null}

            {agents ? (
                <MetricsGrid columns={4} style={{ marginBottom: 24 }}>
                    <MetricCard
                        icon={<Bot size={ICON_SIZE_MD} aria-hidden />}
                        label="Total de Agentes"
                        value={agents.total.toString()}
                        variant="projetos"
                    />
                    <MetricCard
                        icon={<CirclePlay size={ICON_SIZE_MD} aria-hidden />}
                        label="Ativos"
                        value={agentsList
                            .filter((a) => a.status === 'RUNNING' || a.status === 'CREATING')
                            .length.toString()}
                        variant="concluidos"
                    />
                    <MetricCard
                        icon={<CheckCircle2 size={ICON_SIZE_MD} aria-hidden />}
                        label="Finalizados"
                        value={agentsList.filter((a) => a.status === 'FINISHED').length.toString()}
                        variant="concluidos"
                    />
                    <MetricCard
                        icon={<XCircle size={ICON_SIZE_MD} aria-hidden />}
                        label="Falhados"
                        value={agentsList.filter((a) => a.status === 'FAILED').length.toString()}
                        variant="projetos"
                    />
                </MetricsGrid>
            ) : null}

            {(() => {
                const filtrosFields = (
                    <Row gutter={16}>
                        <Col xs={24} md={12}>
                            <FormGroup label="Pesquisa">
                                <Search
                                    placeholder={'Buscar por nome — confirme com "Filtrar" ou Enter em "Pesquisar"'}
                                    allowClear
                                    value={draftSearchInput}
                                    onChange={(e) => setDraftSearchInput(e.target.value)}
                                    onSearch={() => aplicarFiltrosModal()}
                                    enterButton="Pesquisar"
                                    style={{ width: '100%' }}
                                    aria-label="Pesquisar agentes por nome"
                                />
                            </FormGroup>
                        </Col>
                        <Col xs={24} md={12}>
                            <FormGroup label="Status">
                                <Select
                                    placeholder="Todos"
                                    allowClear
                                    style={{ width: '100%' }}
                                    value={draftStatusFilter || undefined}
                                    onChange={(value) => setDraftStatusFilter(value ?? '')}
                                >
                                    <Select.Option value="CREATING">Criando</Select.Option>
                                    <Select.Option value="RUNNING">Rodando</Select.Option>
                                    <Select.Option value="FINISHED">Finalizado</Select.Option>
                                    <Select.Option value="FAILED">Falhou</Select.Option>
                                    <Select.Option value="CANCELLED">Cancelado</Select.Option>
                                </Select>
                            </FormGroup>
                        </Col>
                        <Col xs={24} md={12}>
                            <FormGroup label="Projeto (id)">
                                <Input
                                    placeholder="Filtrar por id de projeto"
                                    allowClear
                                    value={draftProjetoFilter}
                                    onChange={(e) => setDraftProjetoFilter(e.target.value)}
                                    aria-label="Id de projeto para filtro"
                                />
                            </FormGroup>
                        </Col>
                        <Col xs={24} md={12}>
                            <FormGroup label="Agente IA (id)">
                                <Input
                                    placeholder="Filtrar por id de agente IA"
                                    allowClear
                                    value={draftAgenteIaFilter}
                                    onChange={(e) => setDraftAgenteIaFilter(e.target.value)}
                                    aria-label="Id de agente IA para filtro"
                                />
                            </FormGroup>
                        </Col>
                    </Row>
                );
                if (isMobile) {
                    return (
                        <MobileFiltersDrawer
                            open={filtrosModalOpen}
                            onClose={() => setFiltrosModalOpen(false)}
                            onApply={aplicarFiltrosModal}
                            onReset={reporRascunhoFiltros}
                            title="Filtrar agentes Cursor"
                            dataTestId="projeto-qualidade-cursor-agents-filtros-modal"
                        >
                            <div style={{ padding: '12px 16px' }}>{filtrosFields}</div>
                        </MobileFiltersDrawer>
                    );
                }
                return (
                    <Modal
                        title="Filtrar agentes Cursor"
                        data-testid="projeto-qualidade-cursor-agents-filtros-modal"
                        open={filtrosModalOpen}
                        onCancel={() => setFiltrosModalOpen(false)}
                        width={filtrosModalLayout.width ?? 720}
                        centered={filtrosModalLayout.centered}
                        styles={filtrosModalLayout.styles}
                        footer={
                            <FiltrosModalFooterPadrao
                                onLimparTodos={reporRascunhoFiltros}
                                onFechar={() => setFiltrosModalOpen(false)}
                                showFiltrarPrimary
                                onFiltrar={aplicarFiltrosModal}
                                dataTestIdLimparTodos="projeto-qualidade-cursor-agents-filtros-modal-limpar-todos"
                            />
                        }
                        destroyOnHidden
                        keyboard
                        focusTriggerAfterClose
                    >
                        {filtrosFields}
                    </Modal>
                );
            })()}

            {filtrosComAlgumAtivo ? (
                <Alert
                    type="info"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message={`Filtros aplicados (${filtrosAtivosCount})`}
                    description={
                        <>
                            {resumoFiltrosAplicados}
                            <Button type="link" onClick={limparTodosFiltros} style={{ paddingLeft: 8 }}>
                                Limpar filtros
                            </Button>
                        </>
                    }
                />
            ) : null}

            <div style={{ marginTop: filtrosComAlgumAtivo ? 0 : undefined }}>
            <LazyDataTable<CursorAgent>
                columns={columns}
                data={agentsList}
                loading={isLoading}
                pageSize={pageSize}
                onPageChange={onPageChange}
                onRefresh={() => void refetch()}
                onRow={(record: unknown) => ({
                    onClick: () => setOpcoesItem(record as CursorAgent),
                    style: { cursor: 'pointer' }})}
                autoMobileFromColumns={{
                    testIdPrefix: 'qualidade-cursor-agents',
                    listHeading: 'Lista de agentes Cursor',
                    getFallbackTitle: (record: any) =>
                        record.name?.trim() || `Agente ${record.id}`,
                    getSubtitle: (record: any) => {
                        const statusLabel =
                            STATUS_CURSOR_LABEL[record.status] ?? record.status ?? '';
                        const agente = record.agente_ia?.nome?.trim();
                        return [statusLabel, agente].filter(Boolean).join(' · ') || undefined;
                    },
                    excludeFieldKeys: ['name', 'status', 'acoes'],
                    onCardClick: (item) => setOpcoesItem(item),
                    onOpenOptions: (item) => setOpcoesItem(item),
                }}
            />
</div>

            {fetchState === 'ready' && isMobile ? (
                <MobilePageActionBar
                    onOpenFilters={abrirModalFiltros}
                    activeFiltersCount={filtrosAtivosCount}
                    filterButtonLabel="Filtros"
                    onRefresh={() => void refetch()}
                    refreshLoading={isLoading}
                    hideOpcoes
                />
            ) : null}

            <ModalOpcoesCursorAgent
                open={opcoesItem !== null}
                onClose={() => setOpcoesItem(null)}
                item={opcoesItem}
                onVer={handleVer}
                onSincronizar={handleSincronizar}
            />

            {fetchState === 'ready' && !permsLoading && canEditar ? (
                <ListPageCreateFloatButton
                    data-testid="projeto-qualidade-cursor-agents-fab-novo"
                    tooltip={{
                        title: 'Cadastrar novo agente Cursor — refine a listagem com Filtros no cabeçalho',
                    }}
                    onClick={() => router.push(projetoQualidadeCursorAgentsCreatePath(projetoId))}
                />
            ) : null}
        </DetailPageLayout>
        </ProjetoLayout>
    );
}
