import React from "react";
import { useQuery, useMutation } from "@apollo/client";
import { myManager, send, sendVariables } from "../../types/api";
import { GET_SMS_MANAGER, SENDE } from "../../apollo/queries";
import { queryDataFormater, onCompletedMessage } from "@janda-com/front";
import client from "../../apollo/apolloClient";
import { lang as LANG } from "../../lang/langFn";
import { ISmsConfig } from "../../app";
import SmsSendModalWithId from "./SmsSendModalWithID";
import { IPropForInner } from "./declartion";
import SmsSendModal from "./SmsSendModal";


interface IProps extends IPropForInner {
    config: ISmsConfig;
}

// 만약에이게 HOC 이 되어야한다면 component를 받으면 그 컴포넌트로 전달하고 
// 아니면 그냥 SMSSendModal을 반환하자.
const SmsSenderModalWrap: React.FC<IProps> = ({
    modalHook,
    callBackWithIds,
    modalConfig,
    ...props
}) => {

    const { info } = modalHook;
    const withIDs = info?.mode === "withIds"

    const { data, loading } = useQuery<myManager>(GET_SMS_MANAGER, {
        client
    })
    const [sendMu, { loading: sendLoading }] = useMutation<send, sendVariables>(SENDE, {
        client,
        onCompleted: ({ Send }) => {
            onCompletedMessage(Send, LANG("sended"), LANG("unSended"))

        }
    })

    const manager = queryDataFormater(data, 'MyManager', 'data', false) || false;


    const totalLoading = sendLoading || loading;

    if (!manager)
        return <div />

    const sendFn = (message: string, receivers: string[], senderId: string) => {
        sendMu({
            variables: {
                input: {
                    sendTargets: receivers.map((r: string) => ({
                        receiver: r
                    })),
                    message,
                    senderId
                }
            }
        })
    }

    const sharedProp = {
        manager: manager,
        modalHook: modalHook,
        loading: totalLoading,
        modalConfig,
        ...props
    }

    return withIDs ? <SmsSendModalWithId onSendClick={callBackWithIds!} {...sharedProp} /> : <SmsSendModal onSendClick={sendFn} {...sharedProp} />
}

export default SmsSenderModalWrap;