import React, { useState, useEffect } from 'react';
import {
    Button,
    SkeletonLoader,
    UploadArea,
} from '@theorchard/suite-components';
import { isArray, has } from 'lodash-es';
import { useParams } from 'react-router-dom';
import { useUploadExchangeRates } from 'src/apollo/mutations/exchange-rate';
import { ActionStatusIcon } from 'src/components/shared/action-status-icon';
import { FX_RATE_FILE_EXTENSIONS } from 'src/constants';
import { validateFile } from 'src/utils/file-validation';
import { ABACUS_ACTION_STATUSES } from '@theorchard/accounting-apps-shared';

export interface UploadExchangeRatesProps {
    exchangeRatesUploaded: boolean;
    setError: any;
}
export const UploadExchangeRates: React.FC<UploadExchangeRatesProps> = ({
    exchangeRatesUploaded,
    setError,
}) => {
    const { statementPeriodId } = useParams<{ statementPeriodId: string }>();
    const [hasFxRates, setHasFxRates] = useState(exchangeRatesUploaded);
    const [isUploading, setIsUploading] = useState(false);
    const uploadExchangeRates = useUploadExchangeRates(statementPeriodId);

    const uploadCSV = (file: any) => {
        setIsUploading(true);
        const isValid: any = validateFile(file, FX_RATE_FILE_EXTENSIONS);

        if (isValid.error) {
            setError(isValid.error);
            setIsUploading(false);
            return false;
        }

        const fileInfo = file[0];
        const reader: any = new FileReader();
        reader.readAsBinaryString(fileInfo);
        reader.onload = () => {
            const variables = {
                statementPeriodId,
                exchangeRates: btoa(reader.result),
            };

            uploadExchangeRates({ variables })
                .then(() => {
                    setError();
                    setHasFxRates(true);
                    setIsUploading(false);
                })
                .catch(error => {
                    if (isArray(error))
                        if (has(error[0], 'errors')) setError(error[0].errors);
                        else setError(error[0]);
                    else setError(error);

                    setIsUploading(false);
                });
        };
    };

    useEffect(() => {
        setHasFxRates(exchangeRatesUploaded);
    }, [exchangeRatesUploaded]);

    return (
        <div className={`UploadExchangeRates ${hasFxRates ? 'disabled' : ''}`}>
            {!isUploading &&
                (hasFxRates ? (
                    <Button
                        disabled={true}
                        onClick={() => false}
                        variant="quartenary"
                    >
                        <ActionStatusIcon
                            actionStatus={ABACUS_ACTION_STATUSES.COMPLETE}
                        />{' '}
                        Exchange Rates
                    </Button>
                ) : (
                    <UploadArea
                        accept=".csv, .tsv, .txt"
                        className="UploadExchangeRates-uploadcsv"
                        inputId="browser-upload"
                        onUpload={acceptedFiles => uploadCSV(acceptedFiles)}
                    >
                        <label htmlFor="browser-upload">
                            UPLOAD EXCHANGE RATES
                        </label>
                    </UploadArea>
                ))}
            {!hasFxRates && isUploading && (
                <SkeletonLoader numberOfItems={1} vertical />
            )}
        </div>
    );
};
