'use client';

import { useRouter } from 'next/navigation';
import { Alert, Button, Space } from 'antd';
import { message } from '@/lib/feedback/message';
import { confirmDialog } from '@/lib/feedback/confirmDialog';
import { useMutationCache } from '@/hooks/useMutationCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { getLaravelApiErrorMessage } from '@/lib/api/laravelApiErrorMessage';
import { crmPropostaDetalhePath } from '@/features/crm/propostas-lista/propostasListaPaths';
import type { Proposta } from '@/types';

export type ProjetoPrevendaProximoPassoCtaProps = {
    projetoId: string;
    /** Negócio vinculado — para deep-link CRM e gerar proposta. */
    negocioId?: number | null;
    /** Já existe proposta? */
    temProposta?: boolean;
    /** Após criar proposta a partir da precificação. */
    onPropostaCriada?: (propostaId: number) => void;
};

/**
 * CTA claro na pré-venda: precificação → solicitar proposta (N6 / F2).
 */
export function ProjetoPrevendaProximoPassoCta({
    projetoId,
    negocioId,
    temProposta = false,
    onPropostaCriada,
}: ProjetoPrevendaProximoPassoCtaProps) {
    const router = useRouter();
    const precificacaoHref = `/projetos/${projetoId}/planejamento/financeiro/precificacao`;
    const negocioHref = negocioId != null ? `/crm/negocios/${negocioId}` : null;

    const solicitarPropostaMutation = useMutationCache<
        { data?: Proposta; message?: string },
        { projeto_id?: number }
    >({
        endpoint:
            negocioId != null
                ? API_ENDPOINTS.crm.negocios.propostasFromPrecificacao(negocioId)
                : '',
        method: 'POST',
        onSuccess: (data) => {
            message.success(data?.message ?? 'Proposta criada a partir da precificação.');
            const novaId = data?.data?.id;
            if (typeof novaId === 'number' && novaId > 0) {
                onPropostaCriada?.(novaId);
                router.push(crmPropostaDetalhePath(novaId));
            } else if (negocioHref) {
                router.push(negocioHref);
            }
        },
        onError: (err: unknown) => {
            message.error(
                getLaravelApiErrorMessage(
                    err,
                    'Não foi possível solicitar a proposta. Confirme a precificação e tente de novo.',
                ),
            );
        },
    });

    const handleSolicitarProposta = () => {
        if (negocioId == null) {
            message.warning('Vincule o projeto a um negócio CRM para solicitar a proposta.');
            return;
        }
        confirmDialog({
            title: 'Solicitar proposta',
            content:
                'Será criada uma proposta em rascunho com os valores da precificação deste projeto. Confirma?',
            okText: 'Solicitar proposta',
            cancelText: 'Cancelar',
            onOk: () => {
                const pid = Number(projetoId);
                solicitarPropostaMutation.mutate(
                    Number.isFinite(pid) && pid > 0 ? { projeto_id: pid } : {},
                );
            },
        });
    };

    return (
        <Alert
            type="success"
            showIcon
            style={{ marginBottom: 16 }}
            message="Próximo passo comercial"
            description={
                <Space wrap size={8} style={{ marginTop: 4 }}>
                    <span>
                        {temProposta
                            ? 'Há proposta em andamento — continue no negócio CRM.'
                            : 'Complete discovery e precificação; depois solicite a proposta.'}
                    </span>
                    <Button
                        size="small"
                        onClick={() => router.push(precificacaoHref)}
                        data-testid="crm-prevenda-cta-precificacao"
                    >
                        Abrir precificação
                    </Button>
                    {temProposta && negocioHref ? (
                        <Button
                            size="small"
                            type="primary"
                            onClick={() => router.push(negocioHref)}
                            data-testid="crm-prevenda-cta-negocio"
                        >
                            Abrir negócio / proposta
                        </Button>
                    ) : null}
                    {!temProposta && negocioId != null ? (
                        <Button
                            size="small"
                            type="primary"
                            loading={solicitarPropostaMutation.isPending}
                            onClick={handleSolicitarProposta}
                            data-testid="crm-prevenda-cta-solicitar-proposta"
                        >
                            Solicitar proposta
                        </Button>
                    ) : null}
                </Space>
            }
            data-testid="crm-prevenda-proximo-passo"
        />
    );
}
