import './bootstrap';

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(document).ready(function () {

    $('.content-chat-message-user').hide();

    var userInfo = document.getElementById('user-info');
    var userName = userInfo.getAttribute('data-name');
    var userProfile = userInfo.getAttribute('data-profile');

    var usersUrl = window.usersUrl;
    var fetchedUrl = window.fetchedUrl;
    var submitUrl = window.submitUrl;

    console.log(usersUrl, fetchedUrl, submitUrl);
    var receiverId;
    $(document).on('click', '#userClck', function (e) {
        e.preventDefault();
        var userId = $(this).data('id');
        console.log(userId);
        $('.content-chat-message-user').show();
        $('.userClck').removeClass('active');
        $(this).addClass('active');
        receiverId = userId;
        $('#recieverid').val(userId);
        $.ajax({
            url: usersUrl,
            method: "POST",
            data: {
                user_id: userId
            },
            dataType: "json",
            success: function (data) {
                $('#user-profile-image').attr('src', data.profile_image);
                $('#user-profile-name').text(data.name);
                $('#user-status').text(data.status);
            }
        });
        fetchMessages(userId);
    });

    // fetch messages
    function fetchMessages(userId) {
        $.ajax({
            url: fetchedUrl,
            method: "POST",
            data: {
                user_id: userId
            },
            dataType: "json",
            success: function (messages) {
                var messageContainer = $('.body-chat-message-user');
                messageContainer.empty();
                console.log(messages);

                messages.messages.forEach(function (message) {
                    var messageHtml = '';
                    var isCurrentUser = message.sender_id === authId;
                    var userProfile = message.sender_id == messages.users[0].id ? messages.users[0].profile_url : messages.users[1].profile_url;
                    var userName = message.sender_id == messages.users[0].id ? messages.users[0].name : messages.users[1].name;
                    console.log(userProfile, userName);

                    if (message.msg_file && !message.message) {
                        // Display audio
                        var msgFile = window.assetBaseUrl + 'uploads/files/' + message.msg_file;
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right' : 'message-user-left'}">`;
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right-img' : 'message-user-left-img'}">`;
                        messageHtml += `<p class="mt-0 mb-0"><strong>${userName}</strong></p>`;
                        messageHtml += `<img src="${userProfile}" alt="">`;
                        messageHtml += `</div>`;
                        messageHtml += `<div class="">`;
                        messageHtml += `<audio controls>`;
                        messageHtml += `<source src="${msgFile}" type="audio/wav">`;
                        messageHtml += `Your browser does not support the audio element.`;
                        messageHtml += `</audio>`;
                        messageHtml += `</div>`;
                        messageHtml += `</div>`;
                    } else if (message.msg_files && !message.msg_file && !message.message) {
                        // Display images or videos
                        const fileUrls = JSON.parse(message.msg_files);
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right' : 'message-user-left'}">`;
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right-img' : 'message-user-left-img'}">`;
                        messageHtml += `<p class="mt-0 mb-0"><strong>${userName}</strong></p>`;
                        messageHtml += `<img src="${userProfile}" alt="">`;
                        messageHtml += `</div>`;
                        fileUrls.forEach((fileUrl) => {
                            const isImage = /\.(jpeg|jpg|gif|png)$/i.test(fileUrl);
                            const isVideo = /\.(mp4|webm|ogg)$/i.test(fileUrl);
                            if (isImage) {
                                messageHtml += `<div class="${isCurrentUser ? 'message-user-right-text' : 'message-user-left-text'}" style="width: 250px; height: 250px;">`;
                                messageHtml += `<img src="${window.assetBaseUrl + 'uploads/files/' + fileUrl}" alt="Image" style="width: 100%; height: 250px;">`;
                                messageHtml += `</div>`;
                            } else if (isVideo) {
                                messageHtml += `<div class="${isCurrentUser ? 'message-user-right-text' : 'message-user-left-text'}" style="width: 300px; height: 250px; display: flex; align-items: center;">`;
                                messageHtml += `<video controls style="width: 300px; height: 250px;">`;
                                messageHtml += `<source src="${window.assetBaseUrl + 'uploads/files/' + fileUrl}" type="video/mp4" style="width: 100%; height: 250px;">`;
                                messageHtml += `Your browser does not support the video element.`;
                                messageHtml += `</video>`;
                                messageHtml += `</div>`;
                            }
                        });
                        messageHtml += `</div>`;
                    } else {
                        // Display regular message
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right' : 'message-user-left'}">`;
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right-img' : 'message-user-left-img'}">`;
                        messageHtml += `<p class="mt-0 mb-0"><strong>${userName}</strong></p>`;
                        messageHtml += `<img src="${userProfile}" alt="">`;
                        messageHtml += `</div>`;
                        messageHtml += `<div class="${isCurrentUser ? 'message-user-right-text' : 'message-user-left-text'}">`;
                        messageHtml += `<strong>${message.message}</strong>`;
                        messageHtml += `</div>`;
                        messageHtml += `</div>`;
                    }

                    messageContainer.append(messageHtml);
                });

            },
            error: function (xhr, status, error) {
                console.error("Error fetching messages: " + error);
            }
        });
    }

    $(document).on('click', '#sendMessageButton', function (e) {
        e.preventDefault();
        var message = $('#messageInput').val();
        console.log(message);
        sendMessage(message);
        if (message == '') {
            alert('Please enter message')
            return false;
        }

        function sendMessage(message) {
            $.ajax({
                url: submitUrl,
                method: "POST",
                data: {
                    _token: $('meta[name="csrf-token"]').attr('content'),
                    sender_id: authId,
                    receiver_id: receiverId,
                    message: message
                },
                success: function (response) {
                    if (response.success) {
                        console.log(response.data);
                        $('#messageInput').val('');
                        // var sentMessageHtml = `<div class="message-user-right">`;
                        // sentMessageHtml += `<div class="message-user-right-img">`;
                        // sentMessageHtml += `<p class="mt-0 mb-0"><strong>${userName}</strong></p>`;
                        // sentMessageHtml += `<img src="${userProfile}" alt="">`;
                        // sentMessageHtml += `</div>`;
                        // sentMessageHtml += `<div class="message-user-right-text">`;
                        // sentMessageHtml += `<strong>${message}</strong>`;
                        // sentMessageHtml += `</div>`;
                        // sentMessageHtml += `</div>`;
                        // $('.body-chat-message-user').append(sentMessageHtml);
                        // var container = $('.body-chat-message-user');
                        // container.scrollTop(container.prop("scrollHeight"));
                    } else {
                        console.log(response.error);
                    }
                },
                error: function (error) {
                    console.error(error);
                }
            });
        }

    });

    // send audio file
    var recordButton = document.getElementById('recordButton');
    var fileInput = document.getElementById('fileInput');
    let isRecording = false;
    let audioChunks = [];
    let mediaRecorder;

    // Event listener for the record button
    recordButton.addEventListener('click', () => {
        if (!isRecording) {
            console.log('Recording start');
            startRecording();
            recordButton.innerHTML = '<i class="fa-solid fa-stop"></i>';
        } else {
            console.log('Recording stop');
            stopRecording();
            recordButton.innerHTML = '<i class="fa-solid fa-microphone"></i>';
        }
    });

    // Event listener for file input
    fileInput.addEventListener('change', function (event) {
        const selectedFiles = event.target.files;
        if (selectedFiles.length > 0) {
            saveToLaravel(selectedFiles, authId, receiverId);
        }
    });

    // Function to start recording or upload files
    function startRecording() {
        // Check if there are files selected
        const selectedFiles = fileInput.files;
        if (selectedFiles.length > 0) {
            // Files from the file input
            saveToLaravel(selectedFiles, authId, receiverId);
        } else {
            // No files selected, proceed with audio recording
            isRecording = true;
            audioChunks = [];
            navigator.mediaDevices.getUserMedia({
                    audio: true
                })
                .then((stream) => {
                    mediaRecorder = new MediaRecorder(stream);
                    // Event listener for data available
                    mediaRecorder.ondataavailable = (event) => {
                        if (event.data.size > 0) {
                            audioChunks.push(event.data);
                        }
                    };
                    // Event listener for stopping recording
                    mediaRecorder.onstop = () => {
                        isRecording = false;
                        const audioBlob = new Blob(audioChunks, {
                            type: 'audio/wav'
                        });
                        // Send the audio data to Laravel backend
                        saveToLaravel(audioBlob, authId, receiverId);
                    };
                    // Start recording
                    mediaRecorder.start();
                })
                .catch((error) => console.error('Error accessing microphone:', error));
        }
    }

    // Function to stop recording
    function stopRecording() {
        if (mediaRecorder) {
            mediaRecorder.stop();
        }
    }

    // Function to send audio data or files to Laravel backend
    function saveToLaravel(data, authId, receiverId) {
        const formData = new FormData();

        if (data instanceof Blob) {
            // Audio data
            formData.append('audio', data);
            formData.append('sender_id', authId);
            formData.append('receiver_id', receiverId);
            axios.post('/send-message', formData)
                .then((response) => console.log('Audio saved successfully:', response.data))
                .catch((error) => console.error('Error saving audio:', error));
        } else if (data instanceof FileList && data.length > 0) {
            // Files from the file input
            for (let i = 0; i < data.length; i++) {
                const file = data[i];
                formData.append('sender_id', authId);
                formData.append('receiver_id', receiverId);
                formData.append('files[]', file);
            }
            axios.post('/send-message', formData)
                .then((response) => console.log('Files saved successfully:', response.data))
                .catch((error) => console.error('Error saving files:', error));
        }
    }



});


window.Echo.channel('chat').listen('.message', (data) => {
    console.log('Data received from socket:', data);
    const messageData = data.message || {};
    const users = data.users || [];
    var messageContainer = $('.body-chat-message-user');
    var messageHtml = '';
    var isCurrentUser = messageData.sender_id === authId;
    var userProfile = messageData.sender_id == data.users[0].id ? data.users[0].profile : data.users[1].profile;
    var userName = messageData.sender_id == data.users[0].id ? data.users[0].name : data.users[1].name;
    console.log(userProfile, userName);
    var userProfilePath = window.assetBaseUrl + 'uploads/users/' + userProfile;

    if (isCurrentUser) {
        messageHtml += `<div class="message-user-right">`;
        messageHtml +=
            `<div class="message-user-right-img">`;
        messageHtml +=
            `<p class="mt-0 mb-0"><strong>${userName}</strong></p>`;
        messageHtml +=
            `<img src="${userProfilePath}" alt="">`;
        messageHtml += `</div>`;
        if (messageData.msg_file && !messageData.message) {
            messageHtml += `<audio controls>`;
            messageHtml += `<source src="${messageData.path}" type="audio/wav">`;
            messageHtml += `Your browser does not support the audio element.`;
            messageHtml += `</audio>`;
        } else if (messageData.msg_files && !messageData.msg_file && !messageData.message) {
            // Display images or videos
            const fileUrls = JSON.parse(messageData.msg_files);
            fileUrls.forEach((fileUrl) => {
                const isImage = /\.(jpeg|jpg|gif|png)$/i.test(fileUrl);
                const isVideo = /\.(mp4|webm|ogg)$/i.test(fileUrl);
                if (isImage) {
                    messageHtml += `<div class="" style="width: 250px; height: 250px;">`;
                    messageHtml += `<img src="${window.assetBaseUrl + 'uploads/files/' + fileUrl}" alt="Image" style="width: 100%; height: 250px;">`;
                    messageHtml += `</div>`;
                } else if (isVideo) {
                    messageHtml += `<div class="" style="width: 300px; height: 250px;">`;
                    messageHtml += `<video controls>`;
                    messageHtml += `<source src="${window.assetBaseUrl + 'uploads/files/' + fileUrl}" type="video/mp4" style="width: 100%; height: 250px;">`;
                    messageHtml += `Your browser does not support the video element.`;
                    messageHtml += `</video>`;
                    messageHtml += `</div>`;
                }
            });
        } else {
            messageHtml +=
                `<div class="message-user-right-text">`;
            messageHtml += `<strong>${messageData.message}</strong>`;
        }
        messageHtml += `</div>`;
        messageHtml += `</div>`;
    } else {
        messageHtml += `<div class="message-user-left">`;
        messageHtml += `<div class="message-user-left-img">`;
        messageHtml += `<img src="${userProfilePath}" alt="">`;
        messageHtml +=
            `<p class="mt-0 mb-0"><strong>${userName}</strong></p>`;
        messageHtml += `</div>`;
        if (messageData.msg_file && !messageData.message) {
            messageHtml += `<div class="message-user-left-img">`;
            messageHtml += `<audio controls>`;
            messageHtml += `<source src="${window.assetBaseUrl + messageData.msg_file}" type="audio/wav">`;
            messageHtml += `Your browser does not support the audio element.`;
            messageHtml += `</audio>`;
            messageHtml += `</div>`;
        } else if (messageData.msg_files && !messageData.msg_file && !messageData.message) {
            // Display images or videos
            const fileUrls = JSON.parse(messageData.msg_files);
            fileUrls.forEach((fileUrl) => {
                const isImage = /\.(jpeg|jpg|gif|png)$/i.test(fileUrl);
                const isVideo = /\.(mp4|webm|ogg)$/i.test(fileUrl);
                if (isImage) {
                    messageHtml += `<div class="" style="width: 250px; height: 250px;">`;
                    messageHtml += `<img src="${window.assetBaseUrl + 'uploads/files/' + fileUrl}" alt="Image" style="width: 100%; height: 250px;">`;
                    messageHtml += `</div>`;
                } else if (isVideo) {
                    messageHtml += `<div class="" style="width: 300px; height: 250px;">`;
                    messageHtml += `<video controls>`;
                    messageHtml += `<source src="${window.assetBaseUrl + 'uploads/files/' + fileUrl}" type="video/mp4" style="width: 100%; height: 250px;">`;
                    messageHtml += `Your browser does not support the video element.`;
                    messageHtml += `</video>`;
                    messageHtml += `</div>`;
                }
            });
        } else {
            messageHtml += `<div class="message-user-left-text">`;
            messageHtml += `<strong>${messageData.message}</strong>`;
        }
        messageHtml += `</div>`;
        messageHtml += `</div>`;
    }

    messageContainer.append(messageHtml);
    messageContainer.scrollTop(messageContainer.prop("scrollHeight"));
});
