'use client';

/**
 * Inventário completo do menu tipológico (escape hatch MENU-DS-004).
 * Sem política de fase — lista todos os grupos/itens do tipo.
 */
import React, { useMemo } from 'react';
import Link from 'next/link';
import { Card, Empty, List, Typography } from 'antd';
import { useParams } from 'next/navigation';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { getMenuByTipo } from '@/components/layouts/ProjetoLayout/projetoMenuConfig';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import { useAddons } from '@/hooks/useAddons';
import type { Projeto } from '@/types';
import { normalizeProjetoShowResponse } from '@/features/projetos/utils/normalizeProjetoShowResponse';

export function ProjetoMenuInventarioScreen() {
    const params = useParams();
    const projetoId = String(params?.id ?? '');
    const { hasAddon, isLoading: addonsLoading } = useAddons();
    const dsAtivo = hasAddon('desenvolvimento_software');

    const { data: projetoResponse } = useQueryCache<Projeto | { projeto?: Projeto }>({
        endpoint: API_ENDPOINTS.projetos.show(projetoId),
        queryKey: queryKeys.projetos.detail(projetoId),
        enabled: Boolean(projetoId),
    });

    const projeto = useMemo(
        () => normalizeProjetoShowResponse(projetoResponse),
        [projetoResponse],
    );

    const codigo = projeto?.categoria_projeto?.codigo ?? null;

    const groups = useMemo(
        () =>
            getMenuByTipo(projetoId, codigo, {
                desenvolvimentoSoftwareAtivo: dsAtivo,
                inventarioCompleto: true,
                cursorPackConectado: projeto?.cursor_pack?.conectado === true,
                hasAddon: addonsLoading ? undefined : hasAddon,
            }),
        [projetoId, codigo, dsAtivo, addonsLoading, hasAddon, projeto?.cursor_pack?.conectado],
    );

    if (!projetoId) {
        return <Empty description="Projeto não encontrado" />;
    }

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Menu"
            titleSection="Menu"
            showPageTitleIcon={false}
        >
            <div style={{ maxWidth: 960, margin: '0 auto', padding: '16px 0 48px' }}>
                <Typography.Title level={3} style={{ marginBottom: 8 }}>
                    Todos os itens do menu
                </Typography.Title>
                <Typography.Paragraph type="secondary" style={{ marginBottom: 24 }}>
                    Inventário completo deste tipo de projeto, independente do status atual. Use esta
                    lista quando um item não estiver em destaque na barra.
                </Typography.Paragraph>

                {groups.length === 0 ? (
                    <Empty description="Nenhum item de menu para este tipo" />
                ) : (
                    groups.map((group) => (
                        <Card
                            key={group.label}
                            size="small"
                            title={group.label}
                            style={{ marginBottom: 16 }}
                        >
                            <List
                                size="small"
                                dataSource={group.items.filter((i) => !i.route.endsWith('/menu'))}
                                renderItem={(item) => (
                                    <List.Item>
                                        <Link href={item.route}>{item.label}</Link>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    ))
                )}
            </div>
        </ProjetoLayout>
    );
}
