import React, { useState } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Button, Help, RefreshGlyph, WarningGlyph, CheckmarkGlyph } from '@orchard/frontend-react-components';
import { formatMessage } from '@orchard/frontend-localization';
import cx from 'classnames';
import BackNav from 'src/components/back-nav/back-nav';
import Currency from 'src/components/currency/currency';
import TableCellLoader from 'src/components/loaders/table-cell-loader';
import { useReportRunsQuery } from 'src/queries/report-runs';
import ReportsPanel from './reports-panel';
import GenerateReportsModal from './generate-reports-modal';
import messages from './i18n';

const CLASS_NAME = 'ManageReportsPage';

const ManageReportsPage: React.FC<RouteComponentProps> = () => {
    const [showGenerateReportsModal, setShowGenerateReportsModal] = useState(false);
    const [showGeneratingBanner, setShowGeneratingBanner] = useState(false);

    const [selectedUuid, setSelectedUuid] = useState<string>();

    const { data, loading } = useReportRunsQuery();

    const reportRuns = data?.collaboratorReportRuns?.reportRuns || [];

    const selectedReportRun = selectedUuid
        ? reportRuns.find(({ reportRunUuid }) => reportRunUuid === selectedUuid)
        : reportRuns[0];

    const handleReportRunSelect = (uuid: string) => {
        setSelectedUuid(uuid);
        setShowGeneratingBanner(false);
    };

    const toggleShowGenerateReportsModal = () => setShowGenerateReportsModal(!showGenerateReportsModal);

    const handleGenerateReportsSuccess = () => {
        toggleShowGenerateReportsModal();
        setShowGeneratingBanner(true);
        setSelectedUuid(undefined);
    };

    const handleDismissGeneratingBanner = () => setShowGeneratingBanner(false);

    const handleAllReportsDeleted = () => setSelectedUuid(undefined);

    const renderListBody = () => {
        if (loading)
            return (
                <div data-testid="report-runs-list-body-loading">
                    { new Array(5).fill(null).map((_, index) => (
                        <div
                            // eslint-disable-next-line react/no-array-index-key
                            key={ index }
                            className={ cx(`${CLASS_NAME}-reports-list-row`, {
                                [`${CLASS_NAME}-reports-list-row-selected`]:
                                    index === 0,
                            }) }
                        >
                            <div className={ `${CLASS_NAME}-reports-list-cell` }><TableCellLoader /></div>
                            <div className={ `${CLASS_NAME}-reports-list-cell` }><TableCellLoader /></div>
                            <div className={ `${CLASS_NAME}-reports-list-cell` }><TableCellLoader /></div>
                        </div>
                    )) }
                </div>
            );

        if (reportRuns.length === 0)
            return (
                <div className={ `${CLASS_NAME}-reports-list-row` }>
                    <div className={ `${CLASS_NAME}-reports-list-cell no-reports` }>
                        { formatMessage(messages.noReportRunsYet) }
                    </div>
                </div>
            );

        return (
            <div>
                { reportRuns.map(({
                    reportRunUuid,
                    reportRunName,
                    periodName,
                    amount,
                    currency,
                    reportsStatusErrorCount,
                    reportsStatusRequestedCount,
                    reportsTotalCount,
                    reportsWithTransactionCount
                }) => (
                    <div
                        key={ reportRunUuid }
                        className={ cx(
                            `${CLASS_NAME}-reports-list-row`,
                            { [`${CLASS_NAME}-reports-list-row-selected`]: reportRunUuid === selectedReportRun?.reportRunUuid }
                        ) }
                        role="button"
                        tabIndex={ 0 }
                        onClick={ () => handleReportRunSelect(reportRunUuid) }
                    >
                        <div className={ `${CLASS_NAME}-reports-list-cell` }>
                            { reportsStatusErrorCount > 0 && (
                                <Help
                                    id={ `${CLASS_NAME}-report-error-tooltip-${reportRunUuid}` }
                                    message={ formatMessage(messages.manageReportsRunReportHasError) }
                                    hideOnHover={ false }
                                >
                                    <WarningGlyph />
                                </Help>
                            ) }
                            { reportsStatusRequestedCount > 0 && (<RefreshGlyph />) }
                            { reportsWithTransactionCount === reportsTotalCount && (
                                <Help
                                    id={ `${CLASS_NAME}-report-added-tooltip-${reportRunUuid}` }
                                    message={ formatMessage(messages.allReportsAddedToRoyalties) }
                                    hideOnHover={ false }
                                >
                                    <CheckmarkGlyph />
                                </Help>
                            ) }
                            { reportRunName }
                        </div>
                        <div className={ `${CLASS_NAME}-reports-list-cell` }>{ periodName }</div>
                        <div className={ `${CLASS_NAME}-reports-list-cell` }>
                            <Currency
                                amount={ amount }
                                code={ currency }
                                renderSpace
                                amountClassName={ `${CLASS_NAME}-reports-list-currency-amount` }
                                codeClassName={ `${CLASS_NAME}-reports-list-currency-code` }
                            />
                        </div>
                    </div>
                )) }
            </div>
        );
    };

    return (
        <div className={ CLASS_NAME }>
            <div className={ `${CLASS_NAME}-runs-panel` }>
                <div className={ `${CLASS_NAME}-runs-panel-content` }>
                    <BackNav />
                    <h1>{ formatMessage(messages.manageReports) }</h1>
                    <div className={ `${CLASS_NAME}-explanation` }>{ formatMessage(messages.manageReportsExplanation) }</div>
                    <Button variant="primary" onClick={ toggleShowGenerateReportsModal }>{ formatMessage(messages.generateReports) }</Button>
                    <div className={ `${CLASS_NAME}-reports-list` } data-testid="report-runs-list">
                        <div className={ `${CLASS_NAME}-reports-list-header` }>
                            <div className={ `${CLASS_NAME}-reports-list-cell` }>{ formatMessage(messages.reportRunName) }</div>
                            <div className={ `${CLASS_NAME}-reports-list-cell` }>{ formatMessage(messages.reportPeriod) }</div>
                            <div className={ `${CLASS_NAME}-reports-list-cell` }>{ formatMessage(messages.totalAmount) }</div>
                        </div>
                        { renderListBody() }
                    </div>
                </div>
            </div>
            <div className={ `${CLASS_NAME}-reports-panel` }>
                <ReportsPanel
                    loading={ loading }
                    reportRun={ selectedReportRun }
                    showGeneratingBanner={ showGeneratingBanner }
                    onDismissGeneratingBanner={ handleDismissGeneratingBanner }
                    onAllReportsDeleted={ handleAllReportsDeleted }
                />
            </div>
            { showGenerateReportsModal
                && (
                    <GenerateReportsModal
                        onCancel={ toggleShowGenerateReportsModal }
                        onSuccess={ handleGenerateReportsSuccess }
                    />
                ) }
        </div>
    );
};

export default ManageReportsPage;
