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

import React, { useRef } from 'react';

import { Preloader } from 'konsta/react';
import { BsArrowUpCircleFill } from 'react-icons/bs';
import { GrMicrophone } from 'react-icons/gr';
import { ImAttachment } from 'react-icons/im';
import { observer } from 'mobx-react';

import { rpc } from '../../../api/request';
import {
  FileDocumentFileType,
} from '../../../api/types';
import sendSound from '../../../send.mp3';
import { channelStore } from '../../../stores/channelStore';
import MessageReplayItem from './MessageReplayItem';
import RecordingView from './RecordingView';

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 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) {
            channelStore.setRecording(true);
        } 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'>
                    <div className='p-2 flex items-center justify-center min-h-11'>

                        <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>

        {channelStore.recording && <RecordingView
            onCancel={() => channelStore.setRecording(false)}
            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));

                channelStore.setRecording(false);
            }}
        />}
    </>
    );
});

export default RichMessagebar;