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

interface Iprop extends IPropForInner {
    onSendClick: ICallBackWithIds;
    manager: IManager;
    loading?: boolean
    defualtMsg?: string;
    config: ISmsConfig;
}

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

    const { smsReplaceKeys, msgToTemplate } = config;


    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
    }));
    options.unshift({
        value: "",
        label: LANG("custom_msg")
    });

    const templateHook = useSelect(options[0], options)
    const { targets } = modalHook.info!;
    const msgHook = useInput(defualtMsg);

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


    const handleTemplateBtnClick = (op: IselectedOption) => {
        msgHook.onChange(`${msgHook.value} [${op.label}]`)
    }

    const senderHook = useSelect(sendersOps[0], sendersOps);


    if (!targets) throw Error("Target Must be supplied")

    const selectedTemplateId = templateHook.selectedOption?.value;

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



    return <JDmodal head={{
        title: LANG("send_modal_header_num")
    }} loading={loading} foot={
        <div>
            <JDbutton thema="primary" mode="flat" label={LANG("send")} onClick={() => {
                onSendClick(targets.map(t => t.id), msgToTemplate(msgHook.value), senderHook.selectedOption?.value || undefined)
            }} />
        </div>
    } {...modalHook} {...modalConfig}>
        {isEmpty(targets) || <div>
            <JDselect label={LANG("sender")} {...senderHook} />
        </div>}
        <JDlabel txt={LANG("receiver") + " " + targets.length + "명"} />
        <JDalign flex>
            {targets.map((t, i) => (
                <JDalign mr="tiny" flex={{
                    vCenter: true
                }} mb="normal" className="smsSendModal__recivers" key={t.id + i}>
                    <JDtypho mr="tiny">{t.label}</JDtypho>
                    <JDtypho size="tiny">{t.info}</JDtypho>
                </JDalign>
            ))}
        </JDalign>
        <div>
            <JDselect label={LANG("template_choice")} {...templateHook} />
        </div>
        <JDalign mb="large" className="smsSendModal__msgWrap">
            <InputText mb="huge" mr="no" label={LANG("msg")} {...msgHook} textarea />
            <MsgTypeViewer msg={msgHook.value} className="smsSendModal__typeViewer" />
        </JDalign>
        <div>
            {smsReplaceKeys?.map((op: IselectedOption) => {
                const { label, value } = op;
                return (
                    <JDbutton
                        onClick={() => {
                            handleTemplateBtnClick(op);
                        }}
                        size="small"
                        mode="border"
                        key={`templateBtn${op.value}${value}`}
                        label={label}
                    />
                );
            })}
        </div>
    </JDmodal>;
};

export default SmsSendModalWithId;
