'use client';

/**
 * Custos compilados do programa (rollup orçamento/realizado por superfície).
 *
 * @route /projetos/[id]/produto/financeiro
 */

import { Coins, TrendingUp } from 'lucide-react';
import Link from 'next/link';
import React from 'react';
import { useParams } from 'next/navigation';
import { Alert, Button, Progress, Table, Tag } from 'antd';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import MetricCard from '@/components/layouts/MetricCard';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import { ICON_SIZE_MD } from '@/components/icons';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useTenantCurrency } from '@/hooks/useTenantCurrency';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { projetoPortfolioFinanceiroQueryKey } from '@/features/projetos/projeto-produto-releases/utils/produtoQueryKeys';
import { portfolioTruncadoBanner } from '@/features/projetos/projeto-portfolio/utils/portfolioTruncadoCopy';
import { ProdutoSoftwareTipoFetchErrorAlert } from '@/features/projetos/components/ProdutoSoftwareTipoFetchErrorAlert';
import {
    CPI_SPI_GLOSSARIO_COPY,
    CpiSpiGlossarioHelp,
    FORMULA_CPI_SPI_VERSION,
} from '@/features/projetos/projeto-produto-releases/utils/cpiSpiGlossario';

type SuperficieFinanceiro = {
    projeto_id: number;
    nome: string;
    codigo_superficie?: string | null;
    orcamento: number;
    valor_realizado: number;
    percentual_utilizado?: number | null;
    status_orcamento?: string;
};

type FinanceiroApiResponse = {
    data: {
        agregado: {
            orcamento_total: number;
            valor_realizado_total: number;
            saldo_orcamento: number;
            percentual_realizado?: number | null;
            cpi_agregado?: number | null;
            spi_medio?: number | null;
            status_orcamento?: string;
        };
        superficies: SuperficieFinanceiro[];
        meta: {
            superficies_visiveis: number;
            superficies_total: number;
            truncado?: boolean;
            superficies_processadas?: number;
        };
    };
};

const STATUS_COLOR: Record<string, string> = {
    ok: 'success',
    atencao: 'warning',
    alerta: 'orange',
    excedido: 'error',
};

export function ProjetoProdutoFinanceiroScreen() {
    const params = useParams();
    const projetoId = params?.id as string;
    const { formatCurrency } = useTenantCurrency();

    const { data, isLoading, isError, error, refetch } = useQueryCache<FinanceiroApiResponse>({
        queryKey: projetoPortfolioFinanceiroQueryKey(projetoId),
        endpoint: API_ENDPOINTS.projetos.portfolioFinanceiro(projetoId),
        enabled: Boolean(projetoId),
    });

    const agregado = data?.data?.agregado;
    const superficies = data?.data?.superficies ?? [];
    const meta = data?.data?.meta;
    const truncadoBanner = portfolioTruncadoBanner(
        meta
            ? {
                  truncado: meta.truncado,
                  superficies_processadas: meta.superficies_processadas,
                  superficies_total: meta.superficies_total,
              }
            : undefined,
    );

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Financeiro do produto"
            titleSection="Custos compilados"
            headerAction={
                <Link href={`/projetos/${projetoId}/produto/financeiro/atual-vs-planned`}>
                    <Button icon={<TrendingUp size={16} aria-hidden />}>Realizado vs planejado</Button>
                </Link>
            }
        >
            {truncadoBanner ? (
                <Alert
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message={truncadoBanner.message}
                    description={truncadoBanner.description}
                    data-testid="financeiro-portfolio-truncado-banner"
                />
            ) : null}

            {meta && !truncadoBanner && meta.superficies_visiveis < meta.superficies_total ? (
                <Alert
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message="Rollup parcial"
                    description="Algumas superfícies não são visíveis com a tua permissão financeira."
                />
            ) : null}

            {isError ? (
                <ProdutoSoftwareTipoFetchErrorAlert
                    error={error}
                    fallbackMessage="Não foi possível carregar o financeiro do produto"
                    onRetry={() => void refetch()}
                />
            ) : (
                <>
                    <Alert
                        type="info"
                        showIcon
                        style={{ marginBottom: 16 }}
                        message={`${CPI_SPI_GLOSSARIO_COPY.aviso} (fórmula ${FORMULA_CPI_SPI_VERSION})`}
                        description="CPI/SPI do rollup Waygest não são Earned Value Management canónico (PMI). Use o ícone de ajuda junto às métricas para o glossário."
                        action={<CpiSpiGlossarioHelp />}
                        data-testid="cpi-spi-glossario-alert"
                    />

                    <MetricsGrid columns={5} style={{ marginBottom: 24 }}>
                        <MetricCard
                            icon={<Coins size={ICON_SIZE_MD} aria-hidden />}
                            label="Orçamento total"
                            value={agregado ? formatCurrency(agregado.orcamento_total) : '—'}
                            variant="financeiro"
                            loading={isLoading}
                        />
                        <MetricCard
                            icon={<Coins size={ICON_SIZE_MD} aria-hidden />}
                            label="Realizado"
                            value={agregado ? formatCurrency(agregado.valor_realizado_total) : '—'}
                            variant="financeiro"
                            loading={isLoading}
                        />
                        <MetricCard
                            icon={<TrendingUp size={ICON_SIZE_MD} aria-hidden />}
                            label="CPI agregado"
                            value={agregado?.cpi_agregado != null ? String(agregado.cpi_agregado) : '—'}
                            variant="ativos"
                            loading={isLoading}
                            helpTooltip={<CpiSpiGlossarioHelp foco="cpi" />}
                        />
                        <MetricCard
                            icon={<TrendingUp size={ICON_SIZE_MD} aria-hidden />}
                            label="SPI médio"
                            value={agregado?.spi_medio != null ? String(agregado.spi_medio) : '—'}
                            variant="ativos"
                            loading={isLoading}
                            helpTooltip={<CpiSpiGlossarioHelp foco="spi" />}
                        />
                        <MetricCard
                            icon={<TrendingUp size={ICON_SIZE_MD} aria-hidden />}
                            label="Utilização"
                            value={
                                agregado?.percentual_realizado != null
                                    ? `${Math.round(agregado.percentual_realizado)}%`
                                    : '—'
                            }
                            variant="projetos"
                            loading={isLoading}
                        />
                    </MetricsGrid>

                    {agregado?.status_orcamento ? (
                        <Alert
                            type={agregado.status_orcamento === 'ok' ? 'success' : 'warning'}
                            showIcon
                            style={{ marginBottom: 16 }}
                            message={`Status orçamento: ${agregado.status_orcamento}`}
                            description={`Saldo: ${formatCurrency(agregado.saldo_orcamento)}`}
                        />
                    ) : null}

                    <ContentCard title="Por superfície">
                        <Table<SuperficieFinanceiro>
                            rowKey="projeto_id"
                            loading={isLoading}
                            pagination={false}
                            dataSource={superficies}
                            columns={[
                                {
                                    title: 'Superfície',
                                    dataIndex: 'codigo_superficie',
                                    render: (c: string | null) => (c ? <Tag>{c}</Tag> : '—'),
                                },
                                {
                                    title: 'Projeto',
                                    dataIndex: 'nome',
                                    render: (nome: string, row) => (
                                        <Link href={`/projetos/${row.projeto_id}/orcamento`}>{nome}</Link>
                                    ),
                                },
                                {
                                    title: 'Orçamento',
                                    dataIndex: 'orcamento',
                                    render: (v: number) => formatCurrency(v),
                                },
                                {
                                    title: 'Realizado',
                                    dataIndex: 'valor_realizado',
                                    render: (v: number) => formatCurrency(v),
                                },
                                {
                                    title: 'Utilização',
                                    dataIndex: 'percentual_utilizado',
                                    render: (p: number | null) =>
                                        p != null ? <Progress percent={Math.round(p)} size="small" /> : '—',
                                },
                                {
                                    title: 'Status',
                                    dataIndex: 'status_orcamento',
                                    render: (s: string) =>
                                        s ? <Tag color={STATUS_COLOR[s] ?? 'default'}>{s}</Tag> : '—',
                                },
                            ]}
                        />
                    </ContentCard>
                </>
            )}
        </ProjetoLayout>
    );
}
