import type { FC } from 'react';
import React, { useState } from 'react';
import { ENV_PROD } from '@theorchard/constants';
import { Button } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-i18n';
import type { SuiteError } from '../../types';

interface Props {
    environment: string;
    error: SuiteError;
}

const getAuth0Id = (error: SuiteError) => {
    const { message } = error;
    const parts = message.split(/auth0\|/i);
    return parts[1];
};

export const VerifyEmailButton: FC<Props> = ({ environment, error }) => {
    const [emailSent, setEmailSent] = useState(false);
    const [emailFired, setEmailFired] = useState(false);

    const auth0Id = getAuth0Id(error);

    if (!auth0Id) return null;

    const verify = async () => {
        setEmailFired(true);
        const params = btoa(JSON.stringify({ type: 'verify', auth0_id: auth0Id }));
        const host = environment === ENV_PROD ? 'theorchard.com' : 'qaorch.com';
        // After the auth0 resend request is sent, the fetch will redirect until it errors out.
        try {
            await fetch(`https://workstation.${host}/login/resend-email?request=${params}`, {
                mode: 'no-cors',
            });
        } finally {
            setEmailSent(true);
        }
    };

    return (
        <Button onClick={verify} disabled={emailFired} variant="primary">
            {formatMessage(emailSent ? 'error_emailSent' : 'error_resendVerifyEmail')}
        </Button>
    );
};
