'use client';

/**
 * Ficha embutida na edição de entrega: tarefas ligadas, progresso % e link da sprint (WG-ENT-041).
 */

import React, { useMemo } from 'react';
import Link from 'next/link';
import { Alert, Empty, List, Progress, Space, Tag, Typography } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { projetoPlanejamentoSprintDetalhePath } from '@/features/projetos/sprint-detalhe/sprintDetalhePaths';
import { queryKeys } from '@/lib/cache/queryKeys';

const { Text, Title } = Typography;

const STATUS_PRONTA = new Set(['done', 'concluida', 'concluido']);

type TarefaEntregaRow = {
    id: number;
    titulo: string;
    status?: string;
    chave_tarefa?: string;
};

export type EntregaFichaTarefasPanelProps = {
    entregaId: number;
    projetoId: number | string;
    sprintId?: number | null;
    sprintNome?: string | null;
};

function isTarefaPronta(status?: string): boolean {
    if (!status) return false;
    return STATUS_PRONTA.has(status.toLowerCase());
}

/**
 * Lista tarefas com `entrega_id` e progresso simples (% prontas).
 */
export function EntregaFichaTarefasPanel({
    entregaId,
    projetoId,
    sprintId,
    sprintNome,
}: EntregaFichaTarefasPanelProps) {
    const { data, isLoading } = useQueryCache<{ data: TarefaEntregaRow[] }>({
        queryKey: queryKeys.tarefas.porEntrega(entregaId),
        endpoint: API_ENDPOINTS.desenvolvimento.tarefas.index,
        params: { entrega_id: entregaId, per_page: 100, page: 1 },
        staleTime: 30 * 1000,
    });

    const tarefas = data?.data ?? [];
    const { prontas, total, percent } = useMemo(() => {
        const t = tarefas.length;
        const p = tarefas.filter((row) => isTarefaPronta(row.status)).length;
        return {
            total: t,
            prontas: p,
            percent: t === 0 ? 0 : Math.round((p / t) * 100),
        };
    }, [tarefas]);

    const sprintHref =
        sprintId != null && Number(sprintId) > 0
            ? projetoPlanejamentoSprintDetalhePath(String(projetoId), sprintId)
            : null;

    return (
        <div data-testid="entrega-ficha-tarefas-panel" style={{ marginTop: 8 }}>
            <Title level={5} style={{ marginTop: 0, marginBottom: 8 }}>
                Tarefas da entrega
            </Title>

            {sprintHref ? (
                <Alert
                    type="info"
                    showIcon
                    style={{ marginBottom: 12 }}
                    message={
                        <span>
                            Sprint vinculada:{' '}
                            <Link href={sprintHref}>{sprintNome?.trim() || `Sprint #${sprintId}`}</Link>
                        </span>
                    }
                />
            ) : (
                <Text type="secondary" style={{ display: 'block', marginBottom: 12 }}>
                    Nenhuma sprint principal ligada a esta entrega.
                </Text>
            )}

            <Space direction="vertical" size={8} style={{ width: '100%', marginBottom: 12 }}>
                <Text type="secondary">
                    Progresso: {prontas} de {total} prontas
                </Text>
                <Progress
                    percent={percent}
                    status={percent === 100 && total > 0 ? 'success' : 'active'}
                    size="small"
                />
            </Space>

            {isLoading ? (
                <Text type="secondary">Carregando tarefas…</Text>
            ) : tarefas.length === 0 ? (
                <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="Nenhuma tarefa ligada a esta entrega."
                />
            ) : (
                <List
                    size="small"
                    dataSource={tarefas}
                    renderItem={(item) => (
                        <List.Item>
                            <Space wrap size={8}>
                                <Link href={`/minhas-tarefas/tarefas/${item.id}`}>
                                    {item.chave_tarefa || item.titulo}
                                </Link>
                                {item.chave_tarefa && item.titulo !== item.chave_tarefa ? (
                                    <Text type="secondary">{item.titulo}</Text>
                                ) : null}
                                {item.status ? <Tag>{item.status}</Tag> : null}
                            </Space>
                        </List.Item>
                    )}
                />
            )}
        </div>
    );
}
