'use client';

/**
 * Chip discreto de completude do entendimento Cursor Pack (CUR-423).
 * Consome `GET …/entendimento` → `score_completude` (0–100).
 */

import React from 'react';
import Link from 'next/link';
import { Progress, Space, Tag, Tooltip, Typography } from 'antd';
import { FileText, Lightbulb } from 'lucide-react';
import { ICON_SIZE_SM } from '@/components/icons';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import { projetosProjetoCanonical } from '@/lib/routes/projetosProjetoCanonical';
import type { ProjetoEntendimentoSnapshotDto } from './types';

export type EntendimentoCompletudeChipProps = {
    projetoId: string;
    /** Exibe links para documentação técnica e sugestões Cursor (default true). */
    showLinks?: boolean;
    className?: string;
    'data-testid'?: string;
};

function tagColorForScore(score: number): string {
    if (score >= 80) return 'success';
    if (score >= 50) return 'processing';
    return 'warning';
}

/**
 * Indicador de completude tipológica pós-sync (snapshot).
 * Silencioso em loading; se sem snapshot, Tag neutra com CTA.
 */
export function EntendimentoCompletudeChip({
    projetoId,
    showLinks = true,
    className,
    'data-testid': dataTestId = 'entendimento-completude-chip',
}: EntendimentoCompletudeChipProps) {
    const { data, isLoading, isError } = useQueryCache<ProjetoEntendimentoSnapshotDto | null>({
        queryKey: queryKeys.projetos.entendimento(projetoId),
        endpoint: API_ENDPOINTS.projetos.entendimento(projetoId),
        enabled: Boolean(projetoId),
        unwrapApiEnvelope: true,
        staleTime: 60 * 1000,
    });

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

    if (isError) {
        return null;
    }

    const score =
        data != null && typeof data.score_completude === 'number'
            ? Math.max(0, Math.min(100, Math.round(data.score_completude)))
            : null;

    const tooltipTitle =
        score != null
            ? `Completude do entendimento: ${score}% (último sync tipológico)`
            : 'Ainda sem snapshot de entendimento. Sincronize o Cursor Pack ou revise as sugestões.';

    return (
        <Space
            wrap
            size={8}
            align="center"
            className={className}
            data-testid={dataTestId}
            style={{ maxWidth: '100%' }}
        >
            <Tooltip title={tooltipTitle}>
                <Tag
                    color={score != null ? tagColorForScore(score) : 'default'}
                    style={{ marginInlineEnd: 0, display: 'inline-flex', alignItems: 'center', gap: 6 }}
                    data-testid={`${dataTestId}-tag`}
                >
                    {score != null ? (
                        <>
                            <Progress
                                type="circle"
                                percent={score}
                                size={14}
                                strokeWidth={12}
                                showInfo={false}
                                aria-hidden
                            />
                            <span>Entendimento {score}%</span>
                        </>
                    ) : (
                        <span>Sem snapshot de entendimento</span>
                    )}
                </Tag>
            </Tooltip>

            {showLinks ? (
                <>
                    <Link
                        href={projetosProjetoCanonical.projetoRelatorioDocumentacaoTecnica(projetoId)}
                        data-testid={`${dataTestId}-doc-tecnica`}
                    >
                        <Typography.Link style={{ fontSize: 13 }}>
                            <FileText size={ICON_SIZE_SM} aria-hidden style={{ marginInlineEnd: 4, verticalAlign: -2 }} />
                            Documentação técnica
                        </Typography.Link>
                    </Link>
                    <Link
                        href={projetosProjetoCanonical.desenvolvimentoSugestoesCursor(projetoId)}
                        data-testid={`${dataTestId}-sugestoes`}
                    >
                        <Typography.Link style={{ fontSize: 13 }}>
                            <Lightbulb size={ICON_SIZE_SM} aria-hidden style={{ marginInlineEnd: 4, verticalAlign: -2 }} />
                            Sugestões Cursor
                        </Typography.Link>
                    </Link>
                </>
            ) : null}
        </Space>
    );
}
