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

import React, {
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
} 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 { rpc } from '../../../api/request';
import {
  ArgsChannelSendMessageInput,
  FileDocumentFileType,
  ShmChannelMessageType,
} from '../../../api/types';
import sendSound from '../../../send.mp3';
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);


export type RichMessagebarRefProps = {
    setReplyMsg: (msg: ShmChannelMessageType | null) => void;
}

type RichMessagebarProps = {
    onSended: () => void;


    selectChannelID: string;
}

const RichMessagebar = forwardRef<RichMessagebarRefProps, RichMessagebarProps>(({ onSended, selectChannelID }, ref) => {


    const [replayMsg, setReplyMsg] = useState<ShmChannelMessageType | null>(null);

    useImperativeHandle(ref, () => ({
        setReplyMsg: (msg) => {
            setReplyMsg(msg);
        }
    }));




    const onAttachment = () => {

        if (sending) return;

        selectFile().then((file) => {
            if (file) {
                onSelectFile(file);
            }
        });

    }

    const [sending, setSending] = useState(false);



    const onSelectFile = (file: any) => {
        let formData = new FormData();

        formData.append('file', file);

        setSending(true);

        rpc.channelDocumentUpload(formData).then((json) => {
            if (!json) {
                setSending(false);
                return;
            }
            if (!selectChannelID) {
                setSending(false);
                return;
            }

            sendMessage({
                attachments: [json as FileDocumentFileType],
                channel: selectChannelID,
            });

        }).catch(() => {
            setSending(false);
        })

    };



    const [messageText, setMessageText] = useState('');
    const popoverFileTargetRef = useRef<any>(null);

    const textAreaRef = useRef<HTMLTextAreaElement>(null);

    const [recording, setRecording] = useState(false);



    const sendMessage = (params: ArgsChannelSendMessageInput) => {

        if (!selectChannelID) {
            return;
        }

        params.channel = selectChannelID;


        if (replayMsg?._id) {
            params.reply = replayMsg._id;
        }

        setSending(true);
        rpc.channelSendMessage(params).then(() => {
            onSended();

            if (replayMsg) {
                setReplyMsg(null);
            }

            sendAudio.play();
            if (params.text) {
                setMessageText('');

                if (textAreaRef.current) {
                    textAreaRef.current.style.height = 'auto';
                }
            }
        }).finally(() => {
            setSending(false);

        })

    }

    const handleSendClick = () => {

        if (sending) return;

        if (!messageText) {
            setRecording(true);
        } else {

            if (!selectChannelID) {
                return;
            }

            sendMessage({
                channel: selectChannelID,
                text: 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 `}
        >

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

            {replayMsg && <MessageReplayItem
                onClick={() => {

                    if (sending) return;

                    setReplyMsg(null);

                }}

                msg={replayMsg} />}


            <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();
                            }}


                            ref={popoverFileTargetRef}>

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


                <textarea

                    ref={textAreaRef}

                    value={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 (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 = '';
                        }

                        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'>
                        {
                            !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>

        {recording && <RecordingView

            onCancel={() => {
                setRecording(false);
            }}
            onSend={(audioBlob) => {


                let formData = new FormData();
                formData.append('file', audioBlob, 'audio.webm');

                setSending(true);
                rpc.channelVoiceUpload(formData).then((json) => {
                    if (json?._id && selectChannelID) {

                        sendMessage({
                            channel: selectChannelID,
                            voice: {
                                _id: json._id,
                            }
                        })

                    } else {
                        setSending(false);
                    }
                }).catch(() => {
                    setSending(false);
                });

                setRecording(false);
            }}

        />}
    </>



});


export default RichMessagebar;