/**
 * TASK-CID-027 — indicador `monthly_credit` + agentes criados no mês.
 * Consome `GET /v1/cursor-agents/quota` (addon vscode + Sanctum).
 */

'use client';

import { Alert, Button, Skeleton, Space, Tag, Typography } from 'antd';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import { useQueryCache } from '@/hooks/useQueryCache';
import { getLaravelApiErrorMessage } from '@/lib/api/laravelApiErrorMessage';
import {
    cursorCloudQuotaAlertType,
    formatCursorCloudQuotaPeriod,
    parseCursorCloudCreditQuota,
} from '@/features/projetos/ide-vscode/cursorCloudCreditQuota';

const { Text } = Typography;

export type CursorAgentsQuotaBannerProps = {
    /** Filtra contagem ao projecto (create agents). */
    projetoId?: string | number;
    enabled?: boolean;
};

/**
 * Alerta B2B da quota Cursor Cloud — create agents e status IDE.
 */
export function CursorAgentsQuotaBanner({
    projetoId,
    enabled = true,
}: CursorAgentsQuotaBannerProps) {
    const { data, isLoading, isError, error, isFetching, refetch } = useQueryCache<unknown>({
        queryKey: queryKeys.qa.cursorAgents.quota(projetoId),
        endpoint: API_ENDPOINTS.qa.cursorAgents.quota,
        params: projetoId ? { projeto_id: projetoId } : undefined,
        unwrapApiEnvelope: true,
        enabled,
        staleTime: 60_000,
        gcTime: 5 * 60_000,
        retry: 0,
    });

    if (!enabled) {
        return null;
    }

    if (isLoading && !data) {
        return (
            <div data-testid="cursor-agents-quota-loading" style={{ marginBottom: 16 }}>
                <Skeleton active paragraph={{ rows: 1 }} title={{ width: '45%' }} />
            </div>
        );
    }

    if (isError) {
        return (
            <Alert
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
                message="Quota Cursor Cloud"
                description={getLaravelApiErrorMessage(
                    error,
                    'Não foi possível obter monthly_credit / uso do mês. Verifique o addon VS Code e permissões.',
                )}
                data-testid="cursor-agents-quota-error"
                action={
                    <Button size="small" loading={isFetching} onClick={() => void refetch()}>
                        Tentar novamente
                    </Button>
                }
            />
        );
    }

    const quota = parseCursorCloudCreditQuota(data);
    if (!quota) {
        return (
            <Alert
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
                message="Quota Cursor Cloud"
                description="Resposta inesperada ao ler a quota. Atualize ou contate o suporte."
                data-testid="cursor-agents-quota-error"
                action={
                    <Button size="small" loading={isFetching} onClick={() => void refetch()}>
                        Tentar novamente
                    </Button>
                }
            />
        );
    }

    const alertType = cursorCloudQuotaAlertType(quota);
    const periodLabel = formatCursorCloudQuotaPeriod(quota.period);
    const planLabel = quota.plan ? quota.plan.replace(/_/g, ' ') : null;

    return (
        <Alert
            type={alertType}
            showIcon
            style={{ marginBottom: 16 }}
            data-testid="cursor-agents-quota-banner"
            message={
                <Space wrap size={8} align="center">
                    <span>Quota Cursor Cloud (mês)</span>
                    {planLabel ? <Tag color="blue">{planLabel}</Tag> : null}
                    <Tag>{periodLabel}</Tag>
                </Space>
            }
            description={
                <Space direction="vertical" size={4} style={{ width: '100%' }}>
                    <Space wrap size={8}>
                        <Text>
                            Orçamento configurado:{' '}
                            <strong>US$ {quota.monthly_credit.toFixed(2)}</strong>
                        </Text>
                        <Tag color={alertType === 'info' ? 'blue' : alertType === 'warning' ? 'orange' : 'red'}>
                            Agentes criados este mês
                            {projetoId ? ' (projeto)' : ''}: {quota.agents_created_this_month}
                        </Tag>
                    </Space>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                        Valor de referência da instalação (`CURSOR_MONTHLY_CREDIT`) — não é saldo em
                        tempo real da API Cursor.com. Consulte antes de criar novos agentes.
                    </Text>
                </Space>
            }
            action={
                <Button
                    size="small"
                    loading={isFetching}
                    onClick={() => void refetch()}
                    aria-label="Atualizar quota Cursor Cloud"
                >
                    Atualizar
                </Button>
            }
        />
    );
}
