'use client';

/**
 * Painel portfolio do programa (`GET …/projetos/{id}/portfolio`) — ADR-0040 Fase 2.
 */

import { BarChart3, CirclePlay, FolderTree, Gauge, ListChecks } from 'lucide-react';
import Link from 'next/link';
import React, { useMemo } from 'react';
import { Alert, Button, Progress, Space, Table, Tag, Typography } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
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 { CpiSpiGlossarioHelp } from '@/features/projetos/projeto-produto-releases/utils/cpiSpiGlossario';
import { projetoPortfolioQueryKey } from '@/features/projetos/projeto-produto-releases/utils/produtoQueryKeys';
import { portfolioTruncadoBanner } from './utils/portfolioTruncadoCopy';
import { projetoDetalhesStatusColor } from '../projeto-detalhes/projetoDetalhesUtils';

export { projetoPortfolioQueryKey } from '@/features/projetos/projeto-produto-releases/utils/produtoQueryKeys';

const { Text } = Typography;

export type ProjetoPortfolioSuperficie = {
    id: number;
    nome: string;
    codigo_superficie: string | null;
    status?: string;
    rag_status?: string | null;
    progresso_percentual?: number | null;
    tipo?: string | null;
    kpis?: {
        total_tarefas?: number;
        tarefas_concluidas?: number;
        progresso_geral?: number;
    };
    sprint_ativa?: {
        id: number;
        nome: string;
        data_inicio?: string | null;
        data_fim?: string | null;
    } | null;
};

export type ProjetoPortfolioData = {
    programa: {
        id: number;
        nome: string;
        subprojetos_count?: number;
    };
    kpis_agregados: {
        total_tarefas?: number;
        tarefas_concluidas?: number;
        tarefas_em_andamento?: number;
        progresso_por_tarefas?: number;
        progresso_medio_superficies?: number;
        sprints_ativas?: number;
    };
    superficies: ProjetoPortfolioSuperficie[];
    sprints_ativas: Array<{
        id: number;
        nome: string;
        projeto_id: number;
        projeto_nome: string;
        codigo_superficie?: string | null;
        tarefas_total?: number;
        tarefas_concluidas?: number;
    }>;
    meta: {
        total_subprojetos: number;
        total_subprojetos_sistema?: number;
        superficies_visiveis_count?: number;
        /** TASK-PPS-047 — rollup cortado pelo limite de processamento. */
        truncado?: boolean;
        superficies_processadas?: number;
        superficies_total?: number;
        duracao_ms?: number;
        limite?: number;
    };
    financeiro_agregado?: {
        orcamento_total?: number;
        valor_realizado_total?: number;
        percentual_realizado?: number | null;
    };
    cronograma_agregado?: {
        data_inicio_min?: string | null;
        data_fim_prevista_max?: string | null;
    };
};

type ProjetoPortfolioApiResponse = {
    data: ProjetoPortfolioData;
};

type ProjetoPortfolioPanelProps = {
    projetoId: string;
    programaNome?: string;
};

export function ProjetoPortfolioPanel({ projetoId, programaNome }: ProjetoPortfolioPanelProps) {
    const { data, isLoading, isError, refetch } = useQueryCache<ProjetoPortfolioApiResponse>({
        queryKey: projetoPortfolioQueryKey(projetoId),
        endpoint: API_ENDPOINTS.projetos.portfolio(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
    });

    const portfolio = data?.data;
    const kpis = portfolio?.kpis_agregados;
    const progresso = kpis?.progresso_por_tarefas ?? kpis?.progresso_medio_superficies ?? 0;

    const superficiesVisiveis =
        portfolio?.meta?.superficies_visiveis_count ?? portfolio?.meta?.total_subprojetos;
    const superficiesTotal =
        portfolio?.meta?.total_subprojetos_sistema ?? portfolio?.meta?.total_subprojetos;
    const portfolioParcial =
        superficiesVisiveis != null &&
        superficiesTotal != null &&
        superficiesVisiveis < superficiesTotal;
    const truncadoBanner = portfolioTruncadoBanner(portfolio?.meta);

    const columns = useMemo(
        () => [
            {
                title: 'Superfície',
                dataIndex: 'codigo_superficie',
                key: 'codigo_superficie',
                width: 110,
                render: (codigo: string | null) => (codigo ? <Tag>{codigo}</Tag> : '—'),
            },
            {
                title: 'Projeto',
                dataIndex: 'nome',
                key: 'nome',
                render: (nome: string, row: ProjetoPortfolioSuperficie) => (
                    <Link href={`/projetos/${row.id}`}>{nome}</Link>
                ),
            },
            {
                title: 'Status',
                dataIndex: 'status',
                key: 'status',
                width: 130,
                render: (status: string | undefined) =>
                    status ? <Tag color={projetoDetalhesStatusColor(status)}>{status}</Tag> : '—',
            },
            {
                title: 'Progresso',
                key: 'progresso',
                width: 160,
                render: (_: unknown, row: ProjetoPortfolioSuperficie) => {
                    const pct = row.progresso_percentual ?? row.kpis?.progresso_geral ?? 0;
                    return <Progress percent={Math.round(pct)} size="small" />;
                },
            },
            {
                title: 'Tarefas',
                key: 'tarefas',
                width: 100,
                render: (_: unknown, row: ProjetoPortfolioSuperficie) => {
                    const total = row.kpis?.total_tarefas ?? 0;
                    const done = row.kpis?.tarefas_concluidas ?? 0;
                    return (
                        <Text type="secondary">
                            {done}/{total}
                        </Text>
                    );
                },
            },
            {
                title: 'Sprint ativa',
                key: 'sprint',
                ellipsis: true,
                render: (_: unknown, row: ProjetoPortfolioSuperficie) =>
                    row.sprint_ativa?.nome ?? <Text type="secondary">—</Text>,
            },
        ],
        [],
    );

    if (isError) {
        return (
            <Alert
                type="error"
                showIcon
                message="Não foi possível carregar o portfolio"
                action={
                    <Button size="small" onClick={() => void refetch()}>
                        Tentar novamente
                    </Button>
                }
            />
        );
    }

    return (
        <div>
            {programaNome ? (
                <Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
                    Saúde consolidada do programa <strong>{programaNome}</strong> nas superfícies
                    técnicas (API, Front, Gestão…).
                    <Space size={4} style={{ marginLeft: 8 }}>
                        <Text type="secondary">CPI/SPI</Text>
                        <CpiSpiGlossarioHelp />
                    </Space>
                </Typography.Paragraph>
            ) : null}

            {truncadoBanner ? (
                <Alert
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message={truncadoBanner.message}
                    description={truncadoBanner.description}
                    data-testid="portfolio-truncado-banner"
                />
            ) : null}

            {portfolioParcial && !truncadoBanner ? (
                <Alert
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message={`${superficiesVisiveis} de ${superficiesTotal} superfícies visíveis`}
                    description="A visão do programa está parcial — permissões não herdam do programa para todas as superfícies."
                    data-testid="portfolio-parcial-banner"
                />
            ) : null}

            <MetricsGrid columns={4} style={{ marginBottom: 24 }}>
                <MetricCard
                    icon={<FolderTree size={ICON_SIZE_MD} aria-hidden />}
                    label="Subprojetos"
                    value={String(portfolio?.meta.total_subprojetos ?? '—')}
                    variant="projetos"
                    loading={isLoading}
                />
                <MetricCard
                    icon={<ListChecks size={ICON_SIZE_MD} aria-hidden />}
                    label="Tarefas (programa)"
                    value={
                        isLoading
                            ? '—'
                            : `${kpis?.tarefas_concluidas ?? 0}/${kpis?.total_tarefas ?? 0}`
                    }
                    variant="concluidos"
                    loading={isLoading}
                />
                <MetricCard
                    icon={<Gauge size={ICON_SIZE_MD} aria-hidden />}
                    label="Progresso agregado"
                    value={isLoading ? '—' : `${Math.round(progresso)}%`}
                    variant="ativos"
                    loading={isLoading}
                />
                <MetricCard
                    icon={<CirclePlay size={ICON_SIZE_MD} aria-hidden />}
                    label="Sprints ativas"
                    value={String(kpis?.sprints_ativas ?? 0)}
                    variant="clientes"
                    loading={isLoading}
                />
            </MetricsGrid>

            <ContentCard
                title="Superfícies"
                icon={<BarChart3 size={18} aria-hidden />}
                style={{ marginBottom: 24 }}
            >
                <Table<ProjetoPortfolioSuperficie>
                    rowKey="id"
                    loading={isLoading}
                    columns={columns}
                    dataSource={portfolio?.superficies ?? []}
                    pagination={false}
                    size="small"
                />
            </ContentCard>

            {(portfolio?.sprints_ativas?.length ?? 0) > 0 && (
                <ContentCard title="Sprints ativas por superfície">
                    <Table
                        rowKey="id"
                        loading={isLoading}
                        size="small"
                        pagination={false}
                        dataSource={portfolio?.sprints_ativas ?? []}
                        columns={[
                            {
                                title: 'Superfície',
                                dataIndex: 'codigo_superficie',
                                render: (c: string | null) => (c ? <Tag>{c}</Tag> : '—'),
                            },
                            {
                                title: 'Sprint',
                                dataIndex: 'nome',
                                render: (nome: string, row: { projeto_id: number }) => (
                                    <Link href={`/projetos/${row.projeto_id}/planejamento/sprints`}>
                                        {nome}
                                    </Link>
                                ),
                            },
                            {
                                title: 'Tarefas',
                                key: 'tarefas',
                                render: (_: unknown, row: { tarefas_concluidas?: number; tarefas_total?: number }) =>
                                    `${row.tarefas_concluidas ?? 0}/${row.tarefas_total ?? 0}`,
                            },
                        ]}
                    />
                </ContentCard>
            )}
        </div>
    );
}
