'use client';

/**
 * Diagnóstico tipológico (TASK-PPS-036) — card ou alert compacto.
 * AuthZ API: admin / AddonPolicy; 403 → não renderiza (sem 403 surpresa).
 */

import { Activity } from 'lucide-react';
import Link from 'next/link';
import React, { useMemo } from 'react';
import { Alert, List, Space, Tag, Typography } from 'antd';
import ContentCard from '@/components/layouts/ContentCard';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { projetoProdutoHealthQueryKey } from '@/features/projetos/projeto-produto-releases/utils/produtoQueryKeys';

const { Text } = Typography;

export type ProdutoHealthCheck = {
    id: string;
    status: string;
    descricao: string;
    impacto: string;
    correcao: string;
    link: string | null;
};

export type ProdutoHealthResponse = {
    checks: ProdutoHealthCheck[];
    meta: {
        status_geral?: string;
        ok_geral: boolean;
        projeto_id: number;
        checked_at: string;
    };
};

type Props = {
    projetoId: string;
};

function isForbidden(error: unknown): boolean {
    const status = (error as { response?: { status?: number } })?.response?.status;
    return status === 403 || status === 401;
}

/**
 * Painel "Diagnóstico" no dashboard produto.
 */
export function ProdutoDiagnosticoHealthCard({ projetoId }: Props) {
    const { data, isError, error, isLoading } = useQueryCache<ProdutoHealthResponse>({
        queryKey: projetoProdutoHealthQueryKey(projetoId),
        endpoint: API_ENDPOINTS.projetos.produto.health(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
        retry: 0,
    });

    const falhas = useMemo(
        () => (data?.checks ?? []).filter((c) => c.status === 'fail' || c.status === 'warn'),
        [data?.checks],
    );

    if (isError && isForbidden(error)) {
        return null;
    }

    if (isError) {
        return (
            <Alert
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
                message="Diagnóstico indisponível"
                description="Não foi possível carregar o health tipológico. Tente novamente mais tarde."
            />
        );
    }

    if (isLoading || !data) {
        return null;
    }

    const okGeral = data.meta.ok_geral;

    if (!okGeral) {
        return (
            <Alert
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
                data-testid="produto-diagnostico-alert"
                message="Diagnóstico do produto — atenção"
                description={
                    <List
                        size="small"
                        dataSource={falhas.length ? falhas : data.checks}
                        renderItem={(item) => (
                            <List.Item style={{ padding: '4px 0', border: 0 }}>
                                <Space direction="vertical" size={0} style={{ width: '100%' }}>
                                    <Text>
                                        <Tag color="orange">{item.id}</Tag> {item.descricao}
                                    </Text>
                                    <Text type="secondary" style={{ fontSize: 12 }}>
                                        {item.correcao}
                                        {item.link ? (
                                            <>
                                                {' '}
                                                <Link href={item.link}>Corrigir</Link>
                                            </>
                                        ) : null}
                                    </Text>
                                </Space>
                            </List.Item>
                        )}
                    />
                }
            />
        );
    }

    return (
        <div data-testid="produto-diagnostico-ok">
            <ContentCard
                title="Diagnóstico"
                icon={<Activity size={18} aria-hidden />}
                style={{ marginBottom: 16 }}
            >
                <Space wrap>
                    <Tag color="success">OK</Tag>
                    <Text type="secondary">
                        Health tipológico sem falhas · verificado{' '}
                        {new Date(data.meta.checked_at).toLocaleString('pt-BR')}
                    </Text>
                </Space>
            </ContentCard>
        </div>
    );
}
