import React, { useEffect, useState } from 'react';
import ProductCreationCompleteCard from 'src/components/productCreationCompleteCard';
import ProductCreationSubmitFailedCard from 'src/components/productCreationSubmitFailedCard';
import { useGetIngestionReportQuery } from 'src/data/queries/getIngestionReport';

interface ProductCreationCardProps {
    ingestionId: string | null;
    createdAt: string;
    fileName: string;
}

const ProductCreationCard = ({
    ingestionId,
    createdAt,
    fileName,
}: ProductCreationCardProps) => {
    const [downloadLink, setDownloadLink] = useState<string>('');
    const [isLoading, setIsLoading] = useState<boolean>(true);
    const getIngestionReport = useGetIngestionReportQuery();

    useEffect(() => {
        if (ingestionId) {
            getIngestionReport(ingestionId)
                .then(link => {
                    setDownloadLink(link);
                    setIsLoading(false);
                })
                .catch(() => setIsLoading(false));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [ingestionId]);

    if (isLoading) {
        return null;
    }

    if (downloadLink) {
        return (
            <ProductCreationSubmitFailedCard
                createdAt={createdAt}
                fileName={fileName}
                downloadLink={downloadLink}
            />
        );
    }

    return (
        <ProductCreationCompleteCard
            key={ingestionId}
            createdAt={createdAt}
            fileName={fileName}
        />
    );
};

export default ProductCreationCard;
