import React, { type ReactNode } from 'react';
import { Alert } from '@theorchard/suite-components';
import { usePayoneerServiceStatus } from 'src/apollo/queries/payoneer-service-status';
import {
    PAYONEER_OUTAGE_TYPES,
    PAYONEER_STATUS_CODE,
    PAYONEER_OUTAGE_MESSAGE_TITLE,
    PAYONEER_OUTAGE_MESSAGE_CONTENT,
} from 'src/constants';

// Helper function to create alert component
const createAlert = (title: string, message: ReactNode) => {
    return <Alert variant="warn" title={title} text={message} />;
};

export function usePayoneerOutageStatus({ skip = false } = {}) {
    const {
        data: payoneerServiceStatusData,
        error: payoneerServiceStatusError,
        loading: isPayoneerServiceStatusLoading,
    } = usePayoneerServiceStatus({ skip });

    if (skip || isPayoneerServiceStatusLoading) {
        return {
            alert: null,
            isPayoneerOutage: false,
            isLoading: isPayoneerServiceStatusLoading,
            error: payoneerServiceStatusError,
        };
    }

    const statusCode =
        payoneerServiceStatusData?.payoneerServiceStatus?.statusCode;
    const isPayoneerOutage = statusCode === PAYONEER_STATUS_CODE.OUTAGE;
    let alert = null;

    // show unknown alert for unknown status, error, or status available
    if (
        statusCode === PAYONEER_STATUS_CODE.UNKNOWN ||
        !statusCode ||
        payoneerServiceStatusError
    ) {
        alert = createAlert(
            PAYONEER_OUTAGE_MESSAGE_TITLE[PAYONEER_OUTAGE_TYPES.UNKNOWN],
            PAYONEER_OUTAGE_MESSAGE_CONTENT[PAYONEER_OUTAGE_TYPES.UNKNOWN]
        );
    }
    if (statusCode === PAYONEER_STATUS_CODE.OUTAGE) {
        alert = createAlert(
            PAYONEER_OUTAGE_MESSAGE_TITLE[PAYONEER_OUTAGE_TYPES.OUTAGE],
            PAYONEER_OUTAGE_MESSAGE_CONTENT[PAYONEER_OUTAGE_TYPES.OUTAGE]
        );
    }

    return {
        alert,
        isPayoneerOutage,
        isLoading: isPayoneerServiceStatusLoading,
        error: payoneerServiceStatusError,
    };
}
