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

import { Sheet } from 'konsta/react';
import { BsArrowUpCircleFill } from 'react-icons/bs';
import { GrMicrophone } from 'react-icons/gr';
import { MdClose } from 'react-icons/md';

type Props = {
    onCancel: () => void;
    onSend: (audio: Blob) => void;
};

const RecordingSheet = ({ onCancel, onSend }: Props) => {
    const [seconds, setSeconds] = useState(0);
    //const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
    //const [audioBlob, setAudioBlob] = useState<Blob | null>(null);

    const audioBlob = useRef<Blob | null>(null);
    const mediaRecorder = useRef<MediaRecorder | null>(null);
    const streamRef = useRef<MediaStream | null>(null);
    const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
    const chunks = useRef<Blob[]>([]);

    const [opened, setOpened] = useState(false);

    useEffect(() => {

        setTimeout(() => {
            setOpened(true);
        }, 500);

    }, []);

    const inited = useRef(false);
    useEffect(() => {

        if (inited.current) return;

        inited.current = true;

        const start = async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                streamRef.current = stream;

                const recorder = new MediaRecorder(stream, { mimeType: 'audio/webm' });

                recorder.ondataavailable = (e) => chunks.current.push(e.data);

                recorder.onstop = () => {
                    const blob = new Blob(chunks.current, { type: 'audio/webm' });
                    audioBlob.current = blob;
                    chunks.current = [];
                };

                recorder.start();
                mediaRecorder.current = recorder;

                timerRef.current = setInterval(() => setSeconds((s) => s + 1), 1000);
            } catch (err) {
                console.error('🎙 Не удалось получить доступ к микрофону', err);
                onCancel(); // просто закрываем
            }
        };


        start();

        return () => {
            if (timerRef.current) clearInterval(timerRef.current);
        };
    }, []);

    const handleSend = () => {
        mediaRecorder?.current?.stop();
        streamRef.current?.getTracks().forEach((track) => track.stop());
        if (timerRef.current) clearInterval(timerRef.current);

        setTimeout(() => {
            if (audioBlob.current) {
                onSend(audioBlob.current);
            }
        }, 200); // дожидаемся onstop
    };

    const handleCancel = () => {

        mediaRecorder?.current?.stop();
        streamRef.current?.getTracks().forEach((track) => track.stop());
        if (timerRef.current) clearInterval(timerRef.current);
        onCancel();
    };

    const formatTime = (s: number) =>
        `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, '0')}`;



    return <Sheet
        backdrop={true}
        className="pb-safe "
        onBackdropClick={handleCancel}
        opened={opened}>
        <div className="flex  items-start space-x-4 justify-center py-8 ">

            <div
                onClick={handleCancel}
                className=" bg-gray-600 text-white p-6 rounded-full">
                <MdClose size={36} />

            </div>

            <div className='flex flex-col items-center space-y-2'>
                <div className="animate-pulse bg-red-600 p-6 rounded-full">
                    <GrMicrophone className="text-white" size={36} />
                </div>
                <div className="dark:text-white text-black text-xl">{formatTime(seconds)}</div>

            </div>
            <div className=" bg-green-600 text-white  p-6 rounded-full"
                onClick={handleSend}


            >
                <BsArrowUpCircleFill size={36} />
            </div>
        </div>
    </Sheet>

    return (
        <div className="fixed inset-0 bg-black bg-opacity-60 flex flex-col items-center justify-center z-50">
            <div className="flex  items-start space-x-4 ">

                <div
                    onClick={handleCancel}
                    className=" bg-gray-600 text-white p-6 rounded-full">
                    <MdClose size={36} />

                </div>

                <div className='flex flex-col items-center space-y-2'>
                    <div className="animate-pulse bg-red-600 p-6 rounded-full">
                        <GrMicrophone className="text-white" size={36} />
                    </div>
                    <div className="text-white text-xl">{formatTime(seconds)}</div>

                </div>
                <div className=" bg-green-600 text-white  p-6 rounded-full"
                    onClick={handleSend}


                >
                    <BsArrowUpCircleFill size={36} />
                </div>
            </div>
        </div>
    );
};

export default RecordingSheet;