import React, { useState, useEffect } from 'react';
import { JDmodal, JDbutton, useInput, useSelect, toast, JDicon, JDalign, JDlabel, JDselect } from '@janda-com/front';
import { lang as LANG } from '../../lang/langFn';
import { InputText, autoHypen } from '@janda-com/front';
import { IManager } from '../../types/interface';
import { isEmpty } from '@janda-com/front';
import { IPropForInner } from './declartion';
import MsgTypeViewer from '../../atom/MsgTypeViewer';

interface Iprop extends IPropForInner {
    onSendClick: (msg: string, receivers: string[], senderId: string) => void;
    manager: IManager;
    loading?: boolean
    defualtMsg?: string;
}

const defaultInfo = {
    receivers: undefined,
    targets: [],
    mode: "withNums"
}

const SmsSendModal: React.FC<Iprop> = ({ modalHook, modalConfig, onSendClick, manager, loading, defualtMsg = " " }) => {
    const { templates, senders } = manager;

    const senderOps = senders.filter(s => s.verified).map(s => ({
        label: s.name + " " + autoHypen(s.phoneNumber),
        value: s._id
    }));

    const options = templates.map(t => ({
        label: t.name,
        value: t._id
    }));

    const sendersOps = isEmpty(senderOps) ? [{
        label: LANG("janda_sender"),
        value: ""
    }] : senderOps

    const senderHook = useSelect(sendersOps[0], sendersOps);
    const templateHook = useSelect(null, options)
    const { receivers: defaultSCV } = modalHook.info || defaultInfo;

    const msgHook = useInput(defualtMsg);
    const [receivers, setReceviers] = useState(defaultSCV);
    const newNumberHook = useInput("");

    const selectedTemplateId = templateHook.selectedOption?.value;

    const validate = (): boolean => {
        if (isEmpty(receivers)) {
            toast.warn("non_recivers")
            return false
        }

        return true;
    }

    useEffect(() => {
        const target = templates.find(t => t._id === selectedTemplateId);
        target && msgHook.onChange(target.content)
    }, [selectedTemplateId]);

    const foot = <div>
        <JDbutton thema="primary" mode="flat" label={LANG("send")} onClick={() => {
            if (validate())
                onSendClick(msgHook.value, receivers!, senderHook.selectedOption?.value)
        }} />
    </div>

    return <JDmodal head={{ title: LANG("send_modal_header_id") }} className="smsSendModal" loading={loading} foot={foot} {...modalHook} {...modalConfig}>
        <div>
            <JDselect label={LANG("sender")} {...senderHook} />
        </div>
        <div>
            <InputText label={LANG("receiver_add")} hyphen {...newNumberHook} iconHover iconOnClick={() => {
                const { value } = newNumberHook;
                if (!receivers?.includes(value))
                    setReceviers([value, ...(receivers || [])])
            }} icon="addCircle" />
        </div>
        {isEmpty(receivers) || <JDlabel txt={LANG("receiver")} />}
        {receivers?.map((rcv: any, i) => (
            <JDalign mb="normal" flex={{
                between: true
            }} className="smsSendModal__recivers" key={i + rcv}>
                {autoHypen(rcv)}
                <JDicon hover onClick={() => {
                    setReceviers([...receivers.filter(rc => rc !== rcv)]);
                }} icon="trashCan" />
            </JDalign>
        ))}
        <div className="smsSendModal__msgWrap">
            <InputText label={LANG("msg")} mb="huge" mr="no" {...msgHook} textarea />
            <MsgTypeViewer msg={msgHook.value} className="smsSendModal__typeViewer" />
        </div>
    </JDmodal>;
};


export default SmsSendModal;
