import React from 'react';
import { useApolloClient } from '@apollo/client';
import { Button, DownloadGlyph } from '@orchard/frontend-react-components';
import Segment from 'src/utils/segment';
import {
    SEGMENT_EVENTS,
    REPORT_STATUS_GENERATED,
} from 'src/constants';
import { REPORT_DOWNLOAD_QUERY } from 'src/queries/report-download';

const CLASS_NAME = 'ReportDownloadButton';

type Props = {
    reportId: string;
    reportStatus: string;
    fileName?: string;
    fileFormat?: string;
    trackingCategory: string;
    showDownloadGlyph?: boolean;
    variant?: 'link' | 'glyph' | 'hover';
};

const DownloadReportButton: React.FC<Props> = ({
    reportId,
    reportStatus,
    fileName = '',
    fileFormat = '',
    trackingCategory,
    variant = 'link'
}) => {
    const client = useApolloClient();

    const onClick = async () => {
        Segment.trackEvent(SEGMENT_EVENTS.REPORT_DOWNLOAD_CLICK, trackingCategory);
        const {
            data: {
                collaboratorReportDownload: { url: reportDownloadUrl },
            } = { collaboratorReportDownload: {} },
        } = await client.query({
            query: REPORT_DOWNLOAD_QUERY,
            variables: { reportId },
        });

        if (reportDownloadUrl)
            window.location.assign(reportDownloadUrl);
    };

    if (variant === 'glyph')
        return (
            <Button
                disabled={ reportStatus !== REPORT_STATUS_GENERATED }
                className={ `${CLASS_NAME}-button` }
                size="sm"
                data-testid="download-report"
                onClick={ onClick }
            >
                <DownloadGlyph />
            </Button>
        );

    if (variant === 'hover')
        return (
            <div className={ `${CLASS_NAME}-hover` } data-testid="download-report">
                <span>{ fileName }</span>
                <Button
                    disabled={ reportStatus !== REPORT_STATUS_GENERATED }
                    className={ `${CLASS_NAME}-hover-button` }
                    size="sm"
                    onClick={ onClick }
                >
                    <DownloadGlyph />
                </Button>
            </div>
        );

    return (
        <Button
            disabled={ reportStatus !== REPORT_STATUS_GENERATED }
            className={ `${CLASS_NAME}-link` }
            variant="link"
            data-testid="download-report"
            onClick={ onClick }
        >
            { `${fileName}.${fileFormat}` }
        </Button>
    );
};

export default DownloadReportButton;
