'use client';

/**
 * Orçamento e planejamento financeiro do projeto (tabs, sugestão heurística, alertas).
 * FRONT-S2-02 — extraído de `app/(dashboard)/projetos/[id]/orcamento/page.tsx`.
 */

import { BarChart3, Calculator, CheckCircle2, CircleDollarSign, Copy, FileText, Pencil, Sparkles, TrendingUp, TriangleAlert, Zap } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useState, useMemo } from 'react';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
    Row,
    Col,
    Statistic,
    Progress,
    Alert,
    Button,
    Modal,
    Form,
    InputNumber,
    DatePicker,
    Spin,
    Empty,
    Typography,
    Tabs,
    Input,
    Space,
    Table,
    Tag,
    Tooltip,
} from 'antd';
import { message } from '@/lib/feedback/message';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useWaygestFormModalProps } from '@/hooks/useWaygestFormModalProps';
import apiClient from '@/lib/api/client';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { EmptyState } from '@/components/empty';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import styles from './projetoOrcamentoScreen.module.scss';
import { MoneyInputControl } from '@/components/form';
import { useTenantCurrency } from '@/hooks/useTenantCurrency';
import dayjs from 'dayjs';
import type { Projeto } from '@/types';
import type { EntregaResumo, PlanejamentoData, SprintResumo } from './types';
import { buildCronogramaTexto, buildPromptIA, buildResumoPlanejamento, buildPlanejamentoFromProjeto } from './orcamentoHelpers';

const BudgetForecast = dynamic(
    () => import('@/features/projetos/components/financeiro').then((m) => m.BudgetForecast),
    { ssr: false },
);
const BudgetComparison = dynamic(
    () => import('@/features/projetos/components/financeiro').then((m) => m.BudgetComparison),
    { ssr: false },
);

const { Text, Title } = Typography;
const { TextArea } = Input;

function statusLabel(status: string): string {
    switch (status) {
        case 'excedido':
            return 'Excedido';
        case 'alerta':
            return 'Alerta';
        case 'atencao':
            return 'Atenção';
        default:
            return 'Estável';
    }
}

export interface ProjetoOrcamentoScreenProps {
    projetoIdParam: string;
}

export function ProjetoOrcamentoScreen({ projetoIdParam }: ProjetoOrcamentoScreenProps) {
    const router = useRouter();
    const { formatCurrency, currencySymbol } = useTenantCurrency();
    const id = projetoIdParam;
    const projetoId = parseInt(id, 10);
    const [editingPlanejamento, setEditingPlanejamento] = useState(false);
    const [modalPromptOpen, setModalPromptOpen] = useState(false);
    const [modalIaOpen, setModalIaOpen] = useState(false);
    const [sugestaoIa, setSugestaoIa] = useState<{
        orcamento: number;
        percentual_lucro: number;
        observacao?: string;
    } | null>(null);
    const [loadingIa, setLoadingIa] = useState(false);
    const [form] = Form.useForm();
    const modalLayout = useWaygestFormModalProps();

    const {
        data: planejamentoData,
        isLoading,
        isError,
        error,
        refetch,
    } = useQueryCache<PlanejamentoData>({
        queryKey: queryKeys.projetos.budgetPlanejamento(projetoId),
        endpoint: API_ENDPOINTS.projetos.budget.planejamento(projetoId),
        enabled: !!projetoId,
        staleTime: 2 * 60 * 1000,
    });

    const { data: projetoResponse } = useQueryCache<Projeto | { projeto?: Projeto }>({
        queryKey: queryKeys.projetos.detail(String(projetoId)),
        endpoint: API_ENDPOINTS.projetos.show(projetoId),
        enabled: !!projetoId,
        staleTime: 2 * 60 * 1000,
    });
    const projeto =
        projetoResponse && typeof projetoResponse === 'object' && 'projeto' in projetoResponse
            ? (projetoResponse as { projeto?: Projeto }).projeto
            : (projetoResponse as Projeto | undefined);

    const planejamentoEfetivo = useMemo(
        () => planejamentoData ?? buildPlanejamentoFromProjeto(projetoId, projeto),
        [planejamentoData, projetoId, projeto],
    );

    const { data: entregasResponse } = useQueryCache<{ data?: EntregaResumo[] } | EntregaResumo[]>({
        queryKey: queryKeys.entregas.projetoPrompt(projetoId),
        endpoint: API_ENDPOINTS.entregas.index,
        params: { projeto_id: projetoId, per_page: 500, page: 1 },
        enabled: !!projetoId,
        staleTime: 2 * 60 * 1000,
    });
    const { data: sprintsResponse } = useQueryCache<{ data?: SprintResumo[] } | SprintResumo[]>({
        queryKey: queryKeys.desenvolvimento.sprintsPrompt(projetoId),
        endpoint: API_ENDPOINTS.desenvolvimento.sprints.index,
        params: { projeto_id: projetoId, per_page: 100, page: 1 },
        enabled: !!projetoId,
        staleTime: 2 * 60 * 1000,
    });

    const entregasLista = useMemo(
        () => (Array.isArray(entregasResponse) ? entregasResponse : entregasResponse?.data ?? []),
        [entregasResponse],
    );
    const sprintsLista = useMemo(
        () => (Array.isArray(sprintsResponse) ? sprintsResponse : sprintsResponse?.data ?? []),
        [sprintsResponse],
    );

    const resumoPlanejamento = useMemo(() => buildResumoPlanejamento(projeto), [projeto]);
    const cronogramaTexto = useMemo(
        () => buildCronogramaTexto(entregasLista as EntregaResumo[], sprintsLista as SprintResumo[]),
        [entregasLista, sprintsLista],
    );
    const promptIA = useMemo(() => {
        const dadosPlanejamento = planejamentoEfetivo
            ? {
                  orcamento: planejamentoEfetivo.orcamento?.planejado,
                  percentual_lucro: planejamentoEfetivo.percentual_lucro ?? undefined,
                  data_fim_prevista: planejamentoEfetivo.periodo?.fim_prevista ?? undefined,
              }
            : undefined;
        return buildPromptIA(
            resumoPlanejamento,
            planejamentoEfetivo?.projeto_nome || projeto?.nome || 'Projeto',
            cronogramaTexto || undefined,
            dadosPlanejamento,
        );
    }, [resumoPlanejamento, planejamentoEfetivo, projeto?.nome, cronogramaTexto]);

    const { data: alertasData } = useQueryCache<{
        projeto_id: number;
        percentual_utilizado: number;
        alertas: Array<{
            tipo: string;
            severidade: string;
            titulo: string;
            mensagem: string;
            acao: string;
        }>;
        status: string;
    }>({
        queryKey: queryKeys.projetos.budgetAlertas(projetoId),
        endpoint: API_ENDPOINTS.projetos.budget.alertas(projetoId),
        enabled: !!projetoId,
        staleTime: 1 * 60 * 1000,
    });

    const { mutate: atualizarPlanejamento, isPending: isUpdating } = useMutationCache({
        endpoint: API_ENDPOINTS.projetos.budget.atualizarPlanejamento(projetoId),
        method: 'PUT',
        invalidateQueries: [
            ['projetos', 'budget', 'planejamento', projetoId],
            queryKeys.projetos.detail(String(projetoId)),
        ],
        onSuccess: () => {
            setEditingPlanejamento(false);
            refetch();
        },
    });

    const budgetApiIndisponivel = isError && !planejamentoData && !!planejamentoEfetivo;
    const orcamentoNaoDefinido = (planejamentoEfetivo?.orcamento.planejado ?? 0) <= 0;

    const handleEditPlanejamento = () => {
        if (planejamentoEfetivo) {
            form.setFieldsValue({
                orcamento: planejamentoEfetivo.orcamento.planejado || undefined,
                percentual_lucro: planejamentoEfetivo.percentual_lucro ?? undefined,
                data_fim_prevista: planejamentoEfetivo.periodo.fim_prevista
                    ? dayjs(planejamentoEfetivo.periodo.fim_prevista)
                    : null,
            });
        } else {
            form.setFieldsValue({
                orcamento: undefined,
                percentual_lucro: undefined,
                data_fim_prevista: null,
            });
        }
        setEditingPlanejamento(true);
    };

    const handleSavePlanejamento = async () => {
        try {
            const values = await form.validateFields();
            atualizarPlanejamento({
                orcamento: values.orcamento,
                percentual_lucro:
                    values.percentual_lucro != null ? Number(values.percentual_lucro) : null,
                data_fim_prevista: values.data_fim_prevista
                    ? values.data_fim_prevista.format('YYYY-MM-DD')
                    : undefined,
            });
        } catch (error) {
            console.error('Erro ao validar formulário:', error);
        }
    };

    const handleCopyResumo = () => {
        if (!resumoPlanejamento) return;
        void navigator.clipboard.writeText(resumoPlanejamento);
    };

    const handleCopyPrompt = () => {
        void navigator.clipboard.writeText(promptIA);
        message.success('Prompt copiado para a área de transferência.');
    };

    const handleGerarSugestaoOrcamento = async () => {
        setModalIaOpen(true);
        setSugestaoIa(null);
        setLoadingIa(true);
        try {
            const { data } = await apiClient.post<{
                sugestao?: {
                    orcamento: number;
                    percentual_lucro: number;
                    observacao?: string;
                };
            }>(API_ENDPOINTS.projetos.budget.gerarComIa(projetoId));
            if (data.sugestao) {
                setSugestaoIa({
                    orcamento: data.sugestao.orcamento,
                    percentual_lucro: data.sugestao.percentual_lucro,
                    observacao: data.sugestao.observacao,
                });
            }
        } catch {
            message.error('Erro ao obter sugestão. Tente novamente.');
        } finally {
            setLoadingIa(false);
        }
    };

    const handleAplicarSugestaoIa = () => {
        if (!sugestaoIa) return;
        form.setFieldsValue({
            orcamento: sugestaoIa.orcamento,
            percentual_lucro: sugestaoIa.percentual_lucro,
            data_fim_prevista: planejamentoEfetivo?.periodo.fim_prevista
                ? dayjs(planejamentoEfetivo.periodo.fim_prevista)
                : null,
        });
        setModalIaOpen(false);
        setEditingPlanejamento(true);
    };

    if (!projetoId) {
        return (
            <ProjetoLayout projetoId={id} pageTitle="Orçamento" pageIcon="calculator" titleSection="Orçamento">
                <Empty description="Identificador do projeto inválido" />
            </ProjetoLayout>
        );
    }

    if (isLoading && !planejamentoEfetivo) {
        return (
            <ProjetoLayout projetoId={id} pageTitle="Orçamento" pageIcon="calculator" titleSection="Orçamento">
                <div className={styles.loadingWrap}>
                    <Spin size="large" />
                    <Text type="secondary">Carregando planejamento financeiro…</Text>
                </div>
            </ProjetoLayout>
        );
    }

    if (!planejamentoEfetivo) {
        const erroApi =
            (error as { response?: { data?: { message?: string } } })?.response?.data?.message ??
            (isError ? 'Não foi possível carregar o planejamento financeiro.' : undefined);

        return (
            <ProjetoLayout
                projetoId={id}
                pageTitle="Orçamento"
                pageIcon="calculator"
                titleSection="Orçamento"
                breadcrumbItems={[
                    { title: 'PROJETO' },
                    { title: projeto?.nome || 'Projeto' },
                    { title: 'Orçamento' },
                ]}
            >
                {isError ? (
                    <Alert
                        type="error"
                        showIcon
                        style={{ marginBottom: 24 }}
                        message="Erro ao carregar orçamento"
                        description={erroApi}
                        action={
                            <Button size="small" onClick={() => refetch()}>
                                Tentar novamente
                            </Button>
                        }
                    />
                ) : null}
                <EmptyState
                    icon={<Calculator size={40} aria-hidden />}
                    title="Orçamento ainda não definido"
                    description="Defina o valor planejado, a margem de lucro e a data prevista de conclusão para acompanhar baseline, consumo e alertas neste projeto."
                    action={
                        <Space wrap>
                            <Button type="primary" icon={<Pencil size={ICON_SIZE_MD} aria-hidden />} onClick={handleEditPlanejamento}>
                                Definir orçamento
                            </Button>
                            <Button icon={<Sparkles size={ICON_SIZE_MD} aria-hidden />} onClick={handleGerarSugestaoOrcamento}>
                                Sugestão de orçamento (heurística)
                            </Button>
                        </Space>
                    }
                />
                <Modal
                    title="Editar Planejamento"
                    open={editingPlanejamento}
                    onOk={handleSavePlanejamento}
                    onCancel={() => setEditingPlanejamento(false)}
                    confirmLoading={isUpdating}
                    width={modalLayout.width ?? 520}
                    centered={modalLayout.centered ?? true}
                    className={modalLayout.className}
                    styles={modalLayout.styles ?? {}}
                    destroyOnHidden
                    keyboard
                    focusTriggerAfterClose
                    data-testid="projeto-orcamento-editar-planejamento-modal"
                >
                    <Form form={form} layout="vertical">
                        <Form.Item
                            name="orcamento"
                            label="Orçamento"
                            rules={[{ required: true, message: 'Informe o orçamento' }]}
                        >
                            <MoneyInputControl style={{ width: '100%' }} min={0} precision={2} prefix={currencySymbol} />
                        </Form.Item>
                        <Form.Item
                            name="percentual_lucro"
                            label="% de lucro no projeto"
                            help="Percentual de lucro desejado (0–100%). Opcional."
                        >
                            <InputNumber
                                min={0}
                                max={100}
                                precision={1}
                                style={{ width: '100%' }}
                                placeholder="Ex: 30"
                                suffix="%"
                            />
                        </Form.Item>
                        <Form.Item name="data_fim_prevista" label="Data Fim Prevista">
                            <DatePicker style={{ width: '100%' }} />
                        </Form.Item>
                    </Form>
                </Modal>
            </ProjetoLayout>
        );
    }

    const { orcamento, periodo, percentual_lucro } = planejamentoEfetivo;

    const baselineAprovado = orcamento.planejado;
    const consumoAtual = orcamento.utilizado;
    const desvioVsBaselinePct =
        baselineAprovado > 0
            ? ((consumoAtual - baselineAprovado) / baselineAprovado) * 100
            : 0;
    const margemSegurancaPct =
        baselineAprovado > 0 ? (orcamento.saldo / baselineAprovado) * 100 : 0;

    const statusOrcamento =
        orcamento.percentual_utilizado > 100
            ? 'excedido'
            : orcamento.percentual_utilizado > 90
              ? 'alerta'
              : orcamento.percentual_utilizado > 75
                ? 'atencao'
                : 'ok';

    const getStatusColor = () => {
        switch (statusOrcamento) {
            case 'excedido':
                return '#ff4d4f';
            case 'alerta':
                return '#faad14';
            case 'atencao':
                return '#fa8c16';
            default:
                return '#52c41a';
        }
    };

    const statusClass =
        statusOrcamento === 'excedido'
            ? styles.statusExcedido
            : statusOrcamento === 'alerta'
              ? styles.statusAlerta
              : statusOrcamento === 'atencao'
                ? styles.statusAtencao
                : styles.statusOk;

    const utilizationVariant =
        statusOrcamento === 'excedido'
            ? 'gradientRed'
            : statusOrcamento === 'alerta'
              ? 'emAndamento'
              : statusOrcamento === 'atencao'
                ? 'planejamento'
                : 'concluidos';

    return (
        <ProjetoLayout
            projetoId={id}
            pageTitle="Orçamento"
            pageIcon="calculator"
            titleSection="Orçamento"
            breadcrumbItems={[
                { title: 'Projeto' },
                { title: planejamentoEfetivo.projeto_nome || 'Projeto' },
                { title: 'Orçamento' },
            ]}
        >
            <div className={styles.page} data-testid="projeto-orcamento-screen">
                <section className={styles.hero}>
                    <div className={styles.heroTop}>
                        <div className={styles.heroCopy}>
                            <Title level={4} className={styles.heroTitle}>
                                Orçamento e planeamento financeiro
                            </Title>
                            <p className={styles.heroDescription}>
                                {statusOrcamento === 'excedido'
                                    ? `Limite ultrapassado — ${orcamento.percentual_utilizado.toFixed(1)}% do baseline consumido. Revise escopo e backlog antes de novos compromissos.`
                                    : statusOrcamento === 'alerta' || statusOrcamento === 'atencao'
                                      ? `${orcamento.percentual_utilizado.toFixed(1)}% do orçamento utilizado. Acompanhe saldo e forecast para antecipar ajustes.`
                                      : `Situação estável (${orcamento.percentual_utilizado.toFixed(1)}% utilizado). Mantenha o backlog alinhado ao saldo disponível.`}
                            </p>
                        </div>
                        <div className={styles.heroActions}>
                            <Tooltip title="Ajustar valores e parâmetros do planejamento financeiro">
                                <Button
                                    icon={<Pencil size={ICON_SIZE_MD} aria-hidden />}
                                    onClick={handleEditPlanejamento}
                                >
                                    Editar
                                </Button>
                            </Tooltip>
                            <Tooltip title="Ver o prompt enviado à IA (contexto do orçamento)">
                                <Button
                                    icon={<FileText size={ICON_SIZE_MD} aria-hidden />}
                                    onClick={() => setModalPromptOpen(true)}
                                >
                                    Prompt IA
                                </Button>
                            </Tooltip>
                            <Tooltip title="Sugestão heurística de orçamento e margem (valores stub declarados)">
                                <Button
                                    type="primary"
                                    icon={<Sparkles size={ICON_SIZE_MD} aria-hidden />}
                                    onClick={handleGerarSugestaoOrcamento}
                                >
                                    Sugestão de orçamento (heurística)
                                </Button>
                            </Tooltip>
                        </div>
                    </div>

                    <MetricsGrid>
                        <MetricCard
                            icon={<CircleDollarSign size={ICON_SIZE_MD} aria-hidden />}
                            label="Baseline aprovado"
                            value={formatCurrency(baselineAprovado)}
                            subvalue="Orçamento planejado de referência"
                            variant="financeiro"
                        />
                        <MetricCard
                            icon={<TrendingUp size={ICON_SIZE_MD} aria-hidden />}
                            label="Consumo atual"
                            value={formatCurrency(consumoAtual)}
                            subvalue={
                                baselineAprovado > 0
                                    ? `${desvioVsBaselinePct > 0 ? '+' : ''}${desvioVsBaselinePct.toFixed(1)}% vs baseline`
                                    : 'Comprometido no projeto'
                            }
                            variant="emAndamento"
                        />
                        <MetricCard
                            icon={<CircleDollarSign size={ICON_SIZE_MD} aria-hidden />}
                            label="Saldo disponível"
                            value={formatCurrency(orcamento.saldo)}
                            subvalue={
                                baselineAprovado > 0
                                    ? `${margemSegurancaPct.toFixed(1)}% do plano`
                                    : 'Margem sobre o baseline'
                            }
                            variant={orcamento.saldo >= 0 ? 'concluidos' : 'gradientRed'}
                        />
                        <MetricCard
                            icon={<BarChart3 size={ICON_SIZE_MD} aria-hidden />}
                            label="Utilização"
                            value={`${orcamento.percentual_utilizado.toFixed(1)}%`}
                            subvalue={statusLabel(statusOrcamento)}
                            variant={utilizationVariant}
                        />
                    </MetricsGrid>
                </section>

                {budgetApiIndisponivel || orcamentoNaoDefinido ? (
                    <div className={styles.inlineAlerts}>
                        {budgetApiIndisponivel ? (
                            <Alert
                                type="warning"
                                showIcon
                                message="Resumo financeiro limitado"
                                description={'Não foi possível carregar o detalhe de orçamento. A mostrar valores base do projeto; use "Editar" para atualizar.'}
                                action={
                                    <Button size="small" onClick={() => refetch()}>
                                        Recarregar
                                    </Button>
                                }
                            />
                        ) : null}
                        {orcamentoNaoDefinido ? (
                            <Alert
                                type="info"
                                showIcon
                                message="Orçamento ainda não definido"
                                description="Defina o baseline financeiro para acompanhar consumo, margem e alertas ao longo do projeto."
                                action={
                                    <Button size="small" type="primary" onClick={handleEditPlanejamento}>
                                        Definir orçamento
                                    </Button>
                                }
                            />
                        ) : null}
                    </div>
                ) : null}

                <div className={styles.workspace}>
                    <div className={styles.mainPanel}>
                        {alertasData?.alertas && alertasData.alertas.length > 0 ? (
                            <ContentCard title="Alertas e linhas de desvio">
                                <Table
                                    size="small"
                                    pagination={false}
                                    rowKey={(_, i) => String(i)}
                                    dataSource={alertasData.alertas.map((a, i) => ({
                                        key: i,
                                        severidade: a.severidade,
                                        titulo: a.titulo,
                                        mensagem: a.mensagem,
                                        acao: a.acao,
                                    }))}
                                    columns={[
                                        {
                                            title: 'Severidade',
                                            dataIndex: 'severidade',
                                            width: 110,
                                            render: (s: string) => (
                                                <Tag
                                                    color={
                                                        s === 'critica' || s === 'alta'
                                                            ? 'red'
                                                            : s === 'media'
                                                              ? 'orange'
                                                              : 'blue'
                                                    }
                                                >
                                                    {s}
                                                </Tag>
                                            ),
                                        },
                                        { title: 'Título', dataIndex: 'titulo', ellipsis: true },
                                        { title: 'Detalhe', dataIndex: 'mensagem', ellipsis: true },
                                        { title: 'Ação sugerida', dataIndex: 'acao', ellipsis: true },
                                    ]}
                                />
                            </ContentCard>
                        ) : null}

                        <ContentCard title="Análise detalhada" className={styles.tabsCard}>
                            <Tabs
                                defaultActiveKey="resumo"
                                items={[
                                    {
                                        key: 'resumo',
                                        label: 'Resumo',
                                        icon: <BarChart3 size={ICON_SIZE_MD} aria-hidden />,
                                        children: (
                                            <>
                                                {statusOrcamento !== 'ok' ? (
                                                    <Alert
                                                        style={{ marginBottom: 16 }}
                                                        message={
                                                            statusOrcamento === 'excedido'
                                                                ? 'Orçamento excedido'
                                                                : statusOrcamento === 'alerta'
                                                                  ? 'Orçamento próximo do limite (90%+)'
                                                                  : 'Atenção: orçamento acima de 75%'
                                                        }
                                                        description="Consulte o painel lateral para saldo, período e ações de replaneamento."
                                                        type={statusOrcamento === 'excedido' ? 'error' : 'warning'}
                                                        icon={
                                                            statusOrcamento === 'excedido' ? (
                                                                <TriangleAlert size={ICON_SIZE_MD} aria-hidden />
                                                            ) : (
                                                                <CheckCircle2 size={ICON_SIZE_MD} aria-hidden />
                                                            )
                                                        }
                                                        showIcon
                                                    />
                                                ) : null}

                                                <ContentCard
                                                    title="Percentual de lucro no projeto"
                                                    headerActions={
                                                        <Button
                                                            type="link"
                                                            size="small"
                                                            icon={<Pencil size={ICON_SIZE_MD} aria-hidden />}
                                                            onClick={handleEditPlanejamento}
                                                        >
                                                            Editar
                                                        </Button>
                                                    }
                                                >
                                                    <Statistic
                                                        title="% de lucro"
                                                        value={percentual_lucro ?? '—'}
                                                        suffix={percentual_lucro != null ? '%' : ''}
                                                        precision={percentual_lucro != null ? 1 : 0}
                                                        valueStyle={{ color: '#1890ff' }}
                                                    />
                                                    {percentual_lucro == null ? (
                                                        <Text
                                                            type="secondary"
                                                            style={{ display: 'block', marginTop: 8 }}
                                                        >
                                                            Não definido. Use "Editar" no painel lateral ou
                                                            "Sugestão de orçamento (heurística)" para preencher valores stub.
                                                        </Text>
                                                    ) : null}
                                                </ContentCard>
                                            </>
                                        ),
                                    },
                                    {
                                        key: 'resumo-planejamento',
                                        label: 'Resumo do planejamento',
                                        icon: <FileText size={ICON_SIZE_MD} aria-hidden />,
                                        children: (
                                            <ContentCard
                                                title="Informações compiladas do menu Planejamento"
                                                icon={<FileText size={ICON_SIZE_MD} aria-hidden />}
                                                headerActions={
                                                    resumoPlanejamento ? (
                                                        <Button
                                                            type="link"
                                                            icon={<Copy size={ICON_SIZE_MD} aria-hidden />}
                                                            onClick={handleCopyResumo}
                                                        >
                                                            Copiar
                                                        </Button>
                                                    ) : null
                                                }
                                            >
                                                <TextArea
                                                    readOnly
                                                    value={resumoPlanejamento}
                                                    rows={18}
                                                    className={styles.monoArea}
                                                />
                                            </ContentCard>
                                        ),
                                    },
                                    {
                                        key: 'forecast',
                                        label: 'Forecast',
                                        icon: <TrendingUp size={ICON_SIZE_MD} aria-hidden />,
                                        children: <BudgetForecast projetoId={projetoId} />,
                                    },
                                    {
                                        key: 'comparacao',
                                        label: 'Real vs Planejado',
                                        icon: <BarChart3 size={ICON_SIZE_MD} aria-hidden />,
                                        children: <BudgetComparison projetoId={projetoId} />,
                                    },
                                ]}
                            />
                        </ContentCard>
                    </div>

                    <aside className={styles.summaryPanel}>
                        <ContentCard title="Resumo financeiro">
                            <div className={styles.summaryCard}>
                                <span className={`${styles.statusBadge} ${statusClass}`}>
                                    {statusLabel(statusOrcamento)}
                                </span>

                                <div className={styles.progressWrap}>
                                    <div className={styles.progressHeader}>
                                        <span>Utilização do orçamento</span>
                                        <strong style={{ color: getStatusColor() }}>
                                            {orcamento.percentual_utilizado.toFixed(1)}%
                                        </strong>
                                    </div>
                                    <Progress
                                        percent={Math.min(orcamento.percentual_utilizado, 100)}
                                        strokeColor={getStatusColor()}
                                        status={statusOrcamento === 'excedido' ? 'exception' : 'active'}
                                        showInfo={false}
                                    />
                                </div>

                                <div className={styles.summaryBlock}>
                                    <span className={styles.summaryLabel}>Baseline aprovado</span>
                                    <p className={styles.summaryValueLarge}>
                                        {formatCurrency(baselineAprovado)}
                                    </p>
                                </div>

                                <div className={styles.summaryBlock}>
                                    <span className={styles.summaryLabel}>Consumo atual</span>
                                    <p className={styles.summaryValue}>{formatCurrency(consumoAtual)}</p>
                                </div>

                                <div className={styles.summaryBlock}>
                                    <span className={styles.summaryLabel}>Saldo disponível</span>
                                    <p
                                        className={styles.summaryValue}
                                        style={{ color: orcamento.saldo >= 0 ? '#047857' : '#b91c1c' }}
                                    >
                                        {formatCurrency(orcamento.saldo)}
                                    </p>
                                </div>

                                <div className={styles.periodGrid}>
                                    <div className={styles.periodItem}>
                                        <span>Início</span>
                                        <strong>
                                            {periodo.inicio
                                                ? dayjs(periodo.inicio).format('DD/MM/YYYY')
                                                : 'Não definido'}
                                        </strong>
                                    </div>
                                    <div className={styles.periodItem}>
                                        <span>Fim prevista</span>
                                        <strong>
                                            {periodo.fim_prevista
                                                ? dayjs(periodo.fim_prevista).format('DD/MM/YYYY')
                                                : 'Não definido'}
                                        </strong>
                                    </div>
                                    <div className={styles.periodItem}>
                                        <span>Fim real</span>
                                        <strong>
                                            {periodo.fim_real
                                                ? dayjs(periodo.fim_real).format('DD/MM/YYYY')
                                                : 'Não concluído'}
                                        </strong>
                                    </div>
                                </div>

                                <div className={styles.summaryBlock}>
                                    <span className={styles.summaryLabel}>% de lucro</span>
                                    <p className={styles.summaryValue}>
                                        {percentual_lucro != null
                                            ? `${percentual_lucro.toFixed(1)}%`
                                            : 'Não definido'}
                                    </p>
                                </div>

                                <div className={styles.summaryActions}>
                                    <Button
                                        block
                                        icon={<Pencil size={ICON_SIZE_MD} aria-hidden />}
                                        onClick={handleEditPlanejamento}
                                    >
                                        Editar planejamento
                                    </Button>
                                    <Button
                                        block
                                        icon={<Sparkles size={ICON_SIZE_MD} aria-hidden />}
                                        onClick={handleGerarSugestaoOrcamento}
                                    >
                                        Sugestão de orçamento (heurística)
                                    </Button>
                                </div>

                                <div className={styles.quickLinks}>
                                    <Link href={`/projetos/${id}/planejamento/backlog`}>
                                        <Button type="link" size="small" block style={{ textAlign: 'left' }}>
                                            Replanejar backlog
                                        </Button>
                                    </Link>
                                    <Button
                                        type="link"
                                        size="small"
                                        block
                                        style={{ textAlign: 'left' }}
                                        onClick={() => router.push(`/projetos/${id}/planejamento`)}
                                    >
                                        Registar decisão no planeamento
                                    </Button>
                                </div>
                            </div>
                        </ContentCard>
                    </aside>
                </div>
            </div>

            <Modal
                title="Editar Planejamento"
                open={editingPlanejamento}
                onOk={handleSavePlanejamento}
                onCancel={() => setEditingPlanejamento(false)}
                confirmLoading={isUpdating}
                width={modalLayout.width ?? 520}
                centered={modalLayout.centered ?? true}
                className={modalLayout.className}

                styles={modalLayout.styles ?? {}}
                destroyOnHidden
                keyboard
                focusTriggerAfterClose
                data-testid="projeto-orcamento-editar-planejamento-modal"
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="orcamento"
                        label="Orçamento"
                        rules={[{ required: true, message: 'Informe o orçamento' }]}
                    >
                        <MoneyInputControl style={{ width: '100%' }} min={0} precision={2} prefix={currencySymbol} />
                    </Form.Item>
                    <Form.Item
                        name="percentual_lucro"
                        label="% de lucro no projeto"
                        help="Percentual de lucro desejado (0–100%). Opcional."
                    >
                        <InputNumber
                            min={0}
                            max={100}
                            precision={1}
                            style={{ width: '100%' }}
                            placeholder="Ex: 30"
                            suffix="%"
                        />
                    </Form.Item>
                    <Form.Item name="data_fim_prevista" label="Data Fim Prevista">
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title="Prompt para IA analisar o projeto e calcular valor"
                open={modalPromptOpen}
                onCancel={() => setModalPromptOpen(false)}
                width={modalLayout.width ?? 640}
                centered={modalLayout.centered ?? true}
                className={modalLayout.className}

                styles={modalLayout.styles ?? {}}
                destroyOnHidden
                keyboard
                focusTriggerAfterClose
                data-testid="projeto-orcamento-prompt-ia-modal"
                footer={
                    <Space>
                        <Button onClick={() => setModalPromptOpen(false)}>Fechar</Button>
                        <Button type="primary" icon={<Copy />} onClick={handleCopyPrompt}>
                            Copiar prompt
                        </Button>
                    </Space>
                }
            >
                <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Use este texto em uma ferramenta de IA (ex.: ChatGPT, Claude) para obter uma sugestão
                    de orçamento e percentual de lucro.
                </Text>
                <TextArea
                    readOnly
                    value={promptIA}
                    rows={16}
                    style={{ fontFamily: 'monospace', fontSize: 12, whiteSpace: 'pre-wrap' }}
                />
            </Modal>

            <Modal
                title="Sugestão de orçamento (heurística)"
                open={modalIaOpen}
                onCancel={() => {
                    setModalIaOpen(false);
                    setSugestaoIa(null);
                }}
                width={modalLayout.width ?? 720}
                centered={modalLayout.centered ?? true}
                className={modalLayout.className}

                styles={modalLayout.styles ?? {}}
                destroyOnHidden
                keyboard
                focusTriggerAfterClose
                data-testid="projeto-orcamento-analise-ia-modal"
                footer={
                    loadingIa ? null : sugestaoIa ? (
                        <Space>
                            <Button onClick={() => setModalIaOpen(false)}>Fechar</Button>
                            <Button
                                type="primary"
                                icon={<Zap />}
                                onClick={handleAplicarSugestaoIa}
                            >
                                Aplicar sugestão ao planejamento
                            </Button>
                        </Space>
                    ) : (
                        <Button onClick={() => setModalIaOpen(false)}>Fechar</Button>
                    )
                }
            >
                <Alert
                    type="info"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message="Base declarada (sem IA)"
                    description="Heurística stub: reutiliza o orçamento do projeto se existir; senão sugere 25.000. Margem padrão 30% quando não estiver definida."
                />
                {loadingIa && (
                    <div style={{ textAlign: 'center', padding: 24 }}>
                        <Spin size="large" />
                    </div>
                )}
                {!loadingIa && sugestaoIa && (
                    <>
                        <ContentCard title="Sugestão">
                            <Row gutter={16}>
                                <Col span={12}>
                                    <Statistic
                                        title="Orçamento sugerido"
                                        value={sugestaoIa.orcamento}
                                        prefix={currencySymbol}
                                        precision={2}
                                    />
                                </Col>
                                <Col span={12}>
                                    <Statistic
                                        title="% de lucro sugerido"
                                        value={sugestaoIa.percentual_lucro}
                                        suffix="%"
                                        precision={1}
                                    />
                                </Col>
                            </Row>
                            {sugestaoIa.observacao && (
                                <Text type="secondary" style={{ display: 'block', marginTop: 12 }}>
                                    {sugestaoIa.observacao}
                                </Text>
                            )}
                        </ContentCard>
                    </>
                )}
                {!loadingIa && !sugestaoIa && (
                    <Text type="secondary">Nenhuma sugestão retornada.</Text>
                )}
            </Modal>
        </ProjetoLayout>
    );
}
