'use client';

/**
 * F7A + F7C UI — painel de MRs/branches na ficha da entrega + mesclar elegíveis.
 */

import React, { useState } from 'react';
import Link from 'next/link';
import { Alert, Button, Empty, List, Space, Tag, Typography } from 'antd';
import { GitMerge } from 'lucide-react';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { confirmDialog } from '@/lib/feedback/confirmDialog';
import { message } from '@/lib/feedback/message';
import { getLaravelApiErrorMessage } from '@/lib/api/laravelApiErrorMessage';
import { isGitEndpointUnavailable } from '@/features/tarefas/screens/tarefa-detalhe/utils/tarefaGitActions';
import { queryKeys } from '@/lib/cache/queryKeys';

const { Text, Title } = Typography;

export type EntregaMrRow = {
    tarefa_id: number;
    titulo: string;
    status?: string | null;
    branch?: string | null;
    pull_request?: string | null;
    mr_iid?: number | null;
    entrega_id?: number | null;
    sprint_id?: number | null;
    is_conflito?: boolean;
};

type EntregaMrsResponse = {
    entrega_id: number;
    mrs: EntregaMrRow[];
};

export type EntregaMesclarElegiveisResult = {
    message?: string;
    mesclados?: Array<{ tarefa_id?: number; branch?: string; pull_request?: string }>;
    sucessos?: Array<{ tarefa_id?: number; message?: string }>;
    erros?: Array<{ tarefa_id?: number; message?: string; erro?: string }>;
    failures?: Array<{ tarefa_id?: number; message?: string }>;
};

export type EntregaFichaMrsPanelProps = {
    entregaId: number;
};

function collectMesclarErrors(result: EntregaMesclarElegiveisResult | undefined): string[] {
    const rows = [...(result?.erros ?? []), ...(result?.failures ?? [])];
    return rows
        .map((row) => {
            const msg = row.message || row.erro || 'Falha ao mesclar';
            return row.tarefa_id != null ? `Tarefa #${row.tarefa_id}: ${msg}` : msg;
        })
        .filter(Boolean);
}

/**
 * Lista MRs/branches das tarefas com `entrega_id`, com deep-link em `pull_request`
 * e ação «Mesclar PRs elegíveis» (F7C; API pode responder 404 até GitService).
 */
export function EntregaFichaMrsPanel({ entregaId }: EntregaFichaMrsPanelProps) {
    const [ultimoResultado, setUltimoResultado] = useState<EntregaMesclarElegiveisResult | null>(
        null,
    );

    const { data, isLoading, isError, refetch } = useQueryCache<EntregaMrsResponse>({
        queryKey: queryKeys.entregas.mrs(entregaId),
        endpoint: API_ENDPOINTS.entregas.mrs(entregaId),
        staleTime: 30 * 1000,
        enabled: Number.isFinite(entregaId) && entregaId > 0,
    });

    const mesclarMutation = useMutationCache<EntregaMesclarElegiveisResult, Record<string, unknown>>({
        endpoint: API_ENDPOINTS.entregas.git.mesclarElegiveis(entregaId),
        method: 'POST',
        buildBody: () => ({}),
        invalidateQueries: [['entregas', entregaId, 'mrs']],
    });

    const mrs = data?.mrs ?? [];
    const elegiveisCount = mrs.filter((row) => Boolean(row.pull_request?.trim())).length;

    const onMesclarElegiveis = () => {
        void confirmDialog({
            title: 'Mesclar PRs elegíveis?',
            content:
                'Serão mesclados os merge requests elegíveis desta entrega (CI ok / sem conflito, conforme a API). Confirme apenas se a revisão coletiva estiver concluída.',
            okText: 'Mesclar elegíveis',
            cancelText: 'Cancelar',
            okType: 'danger',
            onOk: async () => {
                try {
                    const result = await mesclarMutation.mutateAsync({});
                    setUltimoResultado(result ?? {});
                    const erros = collectMesclarErrors(result);
                    const okCount =
                        (result?.mesclados?.length ?? 0) + (result?.sucessos?.length ?? 0);
                    if (erros.length > 0 && okCount === 0) {
                        message.error(result?.message || 'Nenhum PR foi mesclado.');
                    } else if (erros.length > 0) {
                        message.warning(
                            result?.message ||
                                `Mesclagem parcial: ${okCount} ok, ${erros.length} com erro.`,
                        );
                    } else {
                        message.success(
                            result?.message ||
                                (okCount > 0
                                    ? `${okCount} PR(s) mesclado(s) com sucesso.`
                                    : 'Nenhum PR elegível para mesclar.'),
                        );
                    }
                    void refetch();
                } catch (error) {
                    setUltimoResultado(null);
                    if (isGitEndpointUnavailable(error)) {
                        message.error(
                            'Mesclar PRs elegíveis ainda não está disponível neste ambiente (API Git em preparação).',
                        );
                        return;
                    }
                    message.error(getLaravelApiErrorMessage(error, 'Não foi possível mesclar os PRs elegíveis.'));
                }
            },
        });
    };

    const errosTexto = collectMesclarErrors(ultimoResultado ?? undefined);

    return (
        <div data-testid="entrega-ficha-mrs-panel" style={{ marginTop: 16 }}>
            <Space
                align="start"
                style={{ width: '100%', justifyContent: 'space-between', marginBottom: 8 }}
                wrap
            >
                <Title level={5} style={{ marginTop: 0, marginBottom: 0 }}>
                    Merge requests / branches
                </Title>
                <Button
                    size="small"
                    danger
                    icon={<GitMerge size={14} aria-hidden />}
                    onClick={onMesclarElegiveis}
                    loading={mesclarMutation.isPending}
                    disabled={elegiveisCount === 0 || isLoading}
                    data-testid="entrega-git-mesclar-elegiveis"
                >
                    Mesclar PRs elegíveis
                </Button>
            </Space>
            <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                Leitura a partir das tarefas da entrega. Merge em lote depende da API Git (F7C) e
                das regras de elegibilidade no servidor.
            </Text>

            {ultimoResultado ? (
                <Alert
                    style={{ marginBottom: 12 }}
                    type={errosTexto.length > 0 ? 'warning' : 'success'}
                    showIcon
                    closable
                    onClose={() => setUltimoResultado(null)}
                    message={ultimoResultado.message || 'Resultado da mesclagem'}
                    description={
                        errosTexto.length > 0 ? (
                            <ul style={{ margin: 0, paddingLeft: 18 }}>
                                {errosTexto.map((linha) => (
                                    <li key={linha}>{linha}</li>
                                ))}
                            </ul>
                        ) : (
                            'Sem erros reportados pela API.'
                        )
                    }
                    data-testid="entrega-git-mesclar-resultado"
                />
            ) : null}

            {isLoading ? (
                <Text type="secondary">Carregando MRs…</Text>
            ) : isError ? (
                <Text type="danger">Não foi possível carregar os MRs desta entrega.</Text>
            ) : mrs.length === 0 ? (
                <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="Nenhuma branch ou MR registrada nas tarefas desta entrega."
                />
            ) : (
                <List
                    size="small"
                    dataSource={mrs}
                    renderItem={(item) => (
                        <List.Item>
                            <Space direction="vertical" size={4} style={{ width: '100%' }}>
                                <Space wrap size={8}>
                                    <Link href={`/minhas-tarefas/tarefas/${item.tarefa_id}`}>
                                        {item.titulo || `Tarefa #${item.tarefa_id}`}
                                    </Link>
                                    {item.status ? <Tag>{item.status}</Tag> : null}
                                    {item.is_conflito ? (
                                        <Tag color="error">Conflito</Tag>
                                    ) : null}
                                    {item.mr_iid != null ? (
                                        <Tag color="blue">MR !{item.mr_iid}</Tag>
                                    ) : null}
                                </Space>
                                <Space wrap size={8}>
                                    {item.branch ? (
                                        <Text type="secondary" code>
                                            {item.branch}
                                        </Text>
                                    ) : null}
                                    {item.pull_request ? (
                                        <Typography.Link
                                            href={item.pull_request}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                        >
                                            Abrir MR
                                        </Typography.Link>
                                    ) : (
                                        <Text type="secondary">Sem URL de MR</Text>
                                    )}
                                </Space>
                            </Space>
                        </List.Item>
                    )}
                />
            )}
        </div>
    );
}
