import 'dayjs/locale/ru'; // load on demand

import React, {
    useRef,
    useState,
} from 'react';

import {
    Link,
    List,
    ListItem,
    Popover,
    Preloader,
} from 'konsta/react';
import { observer } from 'mobx-react';
import { BsArrowUpCircleFill } from 'react-icons/bs';
import { GrMicrophone } from 'react-icons/gr';
import { ImAttachment } from 'react-icons/im';
import { LiaEdit } from 'react-icons/lia';
import {
    LuMessageSquareCode,
    LuPlus,
} from 'react-icons/lu';

import { rpc } from '../../../api/request';
import { FileDocumentFileType } from '../../../api/types';
import {
    fastAnswerPopupRootRef,
} from '../../../components/FastAnswerPopupRoot';
import { recordingSheetRef } from '../../../components/RecordingSheetRoot';
import sendSound from '../../../send.mp3';
import { channelStore } from '../../../stores/channelStore';
import store from '../../../stores/store';
import MessageReplayItem from './MessageReplayItem';

async function selectFile(): Promise<File | null> {
    return new Promise((resolve) => {
        const input = document.createElement('input');
        input.type = 'file';
        input.style.display = 'none';

        input.addEventListener('change', () => {
            const file = input.files?.[0] ?? null;

            input.remove(); // удаляем input

            if (file) {
                const maxSizeMB = 5;
                const maxSizeBytes = maxSizeMB * 1024 * 1024;

                if (file.size > maxSizeBytes) {
                    alert(`❌ Файл слишком большой. Максимальный размер — ${maxSizeMB}MB.`);
                    resolve(null);
                    return;
                }
            }

            resolve(file);
        });

        document.body.appendChild(input);
        input.click();
    });
}

const sendAudio = new Audio(sendSound);

const RichMessagebar = observer(() => {
    const selectChannelID = channelStore.channel?._id ?? '';
    const textAreaRef = useRef<HTMLTextAreaElement>(null);

    const [fastAnswersPopoverOpened, setFastAnswersPopoverOpened] = useState(false);
    const fastAnswersPopoverTargetRef = useRef<HTMLDivElement>(null);

    const onAttachment = () => {
        if (channelStore.sending) return;
        selectFile().then((file) => {
            if (file) onSelectFile(file);
        });
    };

    const onSelectFile = (file: File) => {
        const formData = new FormData();
        formData.append('file', file);
        channelStore.setSending(true);

        rpc.channelDocumentUpload(formData)
            .then((json: any) => {
                if (!json || !selectChannelID) {
                    channelStore.setSending(false);
                    return;
                }
                channelStore.sendMessage({
                    attachments: [json as FileDocumentFileType],
                    channel: selectChannelID,
                });
            })
            .catch(() => channelStore.setSending(false));
    };

    const handleSend = (params: { text?: string; voice?: { _id: string } }) => {
        if (!selectChannelID) return;
        channelStore.sendMessage({ ...params, channel: selectChannelID }).then(() => {
            sendAudio.play();
            if (params.text && textAreaRef.current) {
                textAreaRef.current.style.height = 'auto';
            }
        });
    };

    const handleSendClick = () => {
        if (channelStore.sending) return;
        if (!channelStore.messageText) {
            recordingSheetRef.current?.open({
                onClose: () => { },
                onSend: (audioBlob) => {
                    const formData = new FormData();
                    formData.append('file', audioBlob, 'audio.webm');
                    channelStore.setSending(true);

                    rpc.channelVoiceUpload(formData)
                        .then((json) => {
                            if (json?._id && selectChannelID) {
                                handleSend({ voice: { _id: json._id } });
                            } else {
                                channelStore.setSending(false);
                            }
                        })
                        .catch(() => channelStore.setSending(false));
                },
            });
        } else {
            handleSend({ text: channelStore.messageText });
        }
    };







    return (
        <>
            <div


                style={{
                    height: 'auto',
                }}
                className={`left-0 z-10 bottom-0 absolute  w-full  p-2 bg-ios-light-surface-2 dark:bg-ios-dark-surface-2 `}
            >

                {channelStore.sending && <div className='flex items-center justify-center w-full  mb-2'>

                    <Preloader
                        className='w-4 h-4 text-gray-800 dark:text-white'
                    />

                </div>}

                {channelStore.replyMsg && <MessageReplayItem
                    onClick={() => {
                        if (channelStore.sending) return;
                        channelStore.setReplyMsg(null);
                    }}
                    msg={channelStore.replyMsg} />}


                <div className='w-full  flex'>

                    <div className='flex items-end'>

                        {store.mode == "full" && <div

                            onClick={() => {
                                setFastAnswersPopoverOpened(true);
                            }}
                            ref={fastAnswersPopoverTargetRef}
                            className='p-2 flex items-center justify-center min-h-11 cursor-pointer active:opacity-50'>
                            <LuMessageSquareCode size={20} className='text-gray-500' />
                        </div>}
                        <div className='p-2 flex items-center justify-center min-h-11 cursor-pointer active:opacity-50'>

                            <div

                                onClick={() => {
                                    onAttachment();
                                }}


                            >

                                <ImAttachment className='text-gray-500' size={20} />
                            </div>
                        </div>
                    </div>


                    <textarea

                        ref={textAreaRef}

                        value={channelStore.messageText}


                        className=" p-2 w-full outline-none border-none text-base resize-none overflow-hidden bg-white  rounded-md dark:bg-gray-800"
                        rows={1}
                        onChange={(e) => {

                            if (channelStore.sending) return;

                            const target = e.currentTarget;
                            target.style.height = 'auto';
                            target.style.height = `${target.scrollHeight}px`;

                            let value = e.target?.value;


                            if (value.trim() === '') {
                                value = '';
                            }

                            channelStore.setMessageText(value);

                        }}
                        placeholder="Введите сообщение..."
                    />

                    <div className='flex items-end w-10 '>
                        <div

                            onClick={() => {
                                handleSendClick();
                            }}
                            className='p-2 flex items-center justify-center min-h-11 relative'>
                            {
                                !channelStore.messageText ? (

                                    <GrMicrophone
                                        size={28}
                                        className="w-6"
                                    />

                                ) : (<>
                                    <input

                                        onFocus={() => {
                                            textAreaRef.current?.focus();
                                        }}

                                        className='absolute opacity-0  right-0 left-0 top-0 bottom-0  cursor-pointer'
                                    />
                                    <BsArrowUpCircleFill size={28} className="w-6" />
                                </>
                                )
                            }
                        </div>
                    </div>
                </div>
            </div>

            <Popover
                className='w-[300px]'
                opened={fastAnswersPopoverOpened}
                target={fastAnswersPopoverTargetRef.current}
                onBackdropClick={() => setFastAnswersPopoverOpened(false)}
            >
                <List nested outline dividers>

                    {store.fastAnswers.map((fastAnswer) => (
                        <ListItem
                            title={fastAnswer.name}
                            link
                            chevron={false}
                            onClick={() => {


                                if (fastAnswer.text) {
                                    channelStore.setMessageText(fastAnswer.text);
                                }
                                setFastAnswersPopoverOpened(false);
                            }}
                            after={<Link onClick={(e) => {
                                e.stopPropagation();
                                setFastAnswersPopoverOpened(false);
                                fastAnswerPopupRootRef.current?.open(fastAnswer);
                            }}>
                                <LiaEdit size={24} />
                            </Link>}
                        />
                    ))}


                    <ListItem

                        media={<LuPlus size={20} />}
                        title="Добавить быстрый ответ"
                        link

                        chevron={false}
                        onClick={() => {
                            fastAnswerPopupRootRef.current?.open();
                            setFastAnswersPopoverOpened(false);
                        }}
                    />
                </List>
            </Popover>
        </>
    );
});

export default RichMessagebar;