'use client';

/**
 * Card "Release actual" no dashboard (TASK-PPS-039).
 * Loading: Skeleton; erro/timeout: retry + link (não loading eterno).
 */

import { Rocket } from 'lucide-react';
import Link from 'next/link';
import React, { useEffect, useMemo, useState } from 'react';
import { Button, Empty, Skeleton, Space, Tag, Tooltip, Typography } from 'antd';
import ContentCard from '@/components/layouts/ContentCard';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';
import {
    RELEASE_STATUS_COLOR,
    RELEASE_STATUS_LABEL,
    type ProdutoReleaseResumo,
} from '@/features/projetos/projeto-produto-releases/types';
import { projetoProdutoReleasesQueryKey } from '@/features/projetos/projeto-produto-releases/utils/produtoQueryKeys';
import { selectReleaseActual } from '@/features/projetos/projeto-produto-releases/utils/selectReleaseActual';

const { Text, Title } = Typography;

/** Se a query ficar pendente sem erro, deixa de mascarar falha com "A carregar…". */
const RELEASE_ACTUAL_LOAD_TIMEOUT_MS = 12_000;

type ReleasesApiResponse = {
    data: ProdutoReleaseResumo[];
    meta: { total: number };
};

type Props = {
    projetoId: string;
};

export function ReleaseActualCard({ projetoId }: Props) {
    const { canEditar, tooltipSemPermissao } = useProjetoWriteGates();
    const [timedOut, setTimedOut] = useState(false);

    const { data, isPending, isFetching, isError, refetch } = useQueryCache<ReleasesApiResponse>({
        queryKey: projetoProdutoReleasesQueryKey(projetoId),
        endpoint: API_ENDPOINTS.projetos.releases.index(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 60 * 1000,
        retry: 1,
    });

    const waitingForData = (isPending || isFetching) && data === undefined;

    useEffect(() => {
        if (!waitingForData || isError) {
            setTimedOut(false);
            return;
        }
        const timer = window.setTimeout(() => setTimedOut(true), RELEASE_ACTUAL_LOAD_TIMEOUT_MS);
        return () => window.clearTimeout(timer);
    }, [waitingForData, isError, projetoId]);

    const actual = useMemo(
        () => selectReleaseActual(data?.data ?? []),
        [data?.data],
    );

    const handleRetry = () => {
        setTimedOut(false);
        void refetch();
    };

    const criarCta = canEditar ? (
        <Link href={`/projetos/${projetoId}/produto/releases`}>
            <Button type="primary" size="small" data-testid="release-actual-criar">
                Criar release
            </Button>
        </Link>
    ) : (
        <Tooltip title={tooltipSemPermissao('criar releases')}>
            <span>
                <Button type="primary" size="small" disabled data-testid="release-actual-criar-disabled">
                    Criar release
                </Button>
            </span>
        </Tooltip>
    );

    const showLoading = waitingForData && !timedOut && !isError;
    const showError = isError || timedOut;

    return (
        <ContentCard
            title="Release actual"
            icon={<Rocket size={18} aria-hidden />}
            style={{ height: '100%' }}
            data-testid="release-actual-card"
        >
            {showLoading ? (
                <Skeleton
                    active
                    title={false}
                    paragraph={{ rows: 3, width: ['90%', '60%', '40%'] }}
                    data-testid="release-actual-skeleton"
                />
            ) : showError ? (
                <Space direction="vertical" size={8} style={{ width: '100%' }} data-testid="release-actual-error">
                    <Text type="danger">
                        Não foi possível carregar as releases.
                        {timedOut && !isError ? ' A espera excedeu o tempo limite.' : null}
                    </Text>
                    <Space wrap>
                        <Button size="small" type="primary" onClick={handleRetry} data-testid="release-actual-retry">
                            Tentar novamente
                        </Button>
                        <Link href={`/projetos/${projetoId}/produto/releases`}>
                            <Button size="small" data-testid="release-actual-ver-releases">
                                Ver releases
                            </Button>
                        </Link>
                    </Space>
                </Space>
            ) : !actual ? (
                <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="Nenhuma release no programa"
                    data-testid="release-actual-empty"
                >
                    <Space wrap>
                        {criarCta}
                        <Link href={`/projetos/${projetoId}/produto/releases`}>
                            <Button size="small">Ver releases</Button>
                        </Link>
                    </Space>
                </Empty>
            ) : (
                <Space direction="vertical" size={8} style={{ width: '100%' }} data-testid="release-actual-content">
                    <Title level={5} style={{ margin: 0 }}>
                        <Link href={`/projetos/${projetoId}/produto/releases/${actual.id}`}>
                            {actual.nome}
                        </Link>
                    </Title>
                    <Space wrap size={[8, 4]}>
                        <Tag>{actual.codigo}</Tag>
                        <Tag color={RELEASE_STATUS_COLOR[actual.status]}>
                            {RELEASE_STATUS_LABEL[actual.status]}
                        </Tag>
                    </Space>
                    <Text type="secondary">
                        Data alvo: {actual.data_alvo ?? '—'}
                    </Text>
                    <Link href={`/projetos/${projetoId}/produto/releases/${actual.id}`}>
                        <Button type="link" size="small" style={{ paddingInline: 0 }}>
                            Abrir detalhe
                        </Button>
                    </Link>
                </Space>
            )}
        </ContentCard>
    );
}
