<template>
    <div class="chatContainer">
        <div class="chat-card">
            <ChatHeader @toggle-chat="toggleChat" />
                <ChatBody/>
            <ChatFooter/>
        </div>
    </div>
</template>

<script>

import StatusMessage from "./chat/statusMessage.vue";
import ChatActions from "./chat/actions.vue";
import ResponseSection from "./chat/responseSection.vue";
import ChatForm from "./chat/form.vue";
import ChatHeader from "./chat/structure/header.vue";
import ChatFooter from "./chat/structure/footer.vue";
import ChatBody from "./chat/structure/body.vue";

export default {
    name: "AgentChatComponent",
    components: {ChatBody, ChatFooter, ChatHeader, ChatForm, ResponseSection, ChatActions, StatusMessage},
    props: {
        sendUrl: { type: String, default: "/send-message" },
        voiceUrl: { type: String, default: "/agent/voice" },
        toggleChat: { type: Function, default: null },
    },
    data() {
        return {
            message: "",
            isLoading: false,
            statusMessage: "",
            statusType: "",
            responseContent: "",
            productName: "",
            productData: null,
            mediaRecorder: null,
            chunks: [],
            isRecording: false,
            audioUrl: null,
        };
    },
    computed: {
        csrfToken() {
            const tokenMeta = document.querySelector('meta[name="csrf-token"]');
            return tokenMeta ? tokenMeta.getAttribute('content') : null;
        }
    },
    mounted() {
        window.Echo.channel('public-updates')
            .listen('.new.notification', (data) => {
                this.statusMessage = "Received response";
                this.statusType = "success";
                console.log(data);
                this.responseContent = data.message;
                this.productName = data.productName;
                this.productData = data.item;
                this.isLoading = false;
            });
    },
    methods: {
        async sendMessage(msg) {
            this.message = msg;
            if (!this.message) return;
            this.isLoading = true;
            this.statusMessage = "Thinking...";
            this.statusType = "loading";
            this.responseContent = "";
            this.productData = null;

            const formData = new FormData();
            formData.append("message", this.message);

            try {
                const res = await fetch(this.sendUrl, {
                    method: "POST",
                    headers: {
                        "Accept": "application/json",
                        ...(this.csrfToken ? { "X-CSRF-TOKEN": this.csrfToken } : {})
                    },
                    body: formData,
                    credentials: "same-origin"
                });

                if (!res.ok) {
                    let errText = res.statusText;
                    try {
                        const errJson = await res.json();
                        errText = errJson.message || JSON.stringify(errJson);
                    } catch (e) {
                    }
                    throw new Error(errText);
                }

                const data = await res.json();
                if (data.status !== 'message sent') {
                    throw new Error("Failed to send message.");
                }
                // Now we wait for the Echo listener to receive the response.
                this.statusMessage = "Message sent, waiting for response...";

            } catch (err) {
                this.statusMessage = "Error: " + (err.message || "Request failed");
                this.statusType = "error";
                this.isLoading = false;
            }
        },

        startRecording() {
            console.log("Starting recording...");
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                alert("Your browser does not support audio recording.");
                return;
            }

            navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
                this.mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm" });
                this.mediaRecorder.start();
                this.isRecording = true;
                this.statusMessage = "Recording...";
                this.statusType = "loading";

                this.mediaRecorder.ondataavailable = (e) => {
                    this.chunks.push(e.data);
                };

                this.mediaRecorder.onstop = async () => {
                    const blob = new Blob(this.chunks, { type: "audio/webm" });
                    this.audioUrl = URL.createObjectURL(blob);
                    if(this.$refs.recordedAudio) {
                        this.$refs.recordedAudio.src = this.audioUrl;
                    }

                    const formData = new FormData();
                    const file = new File([blob], "user_audio.webm", { type: "audio/webm" });
                    formData.append("audio_file", file);

                    this.statusMessage = "Transcribing audio...";
                    this.statusType = "loading";

                    try {
                        const response = await fetch(this.voiceUrl, {
                            method: "POST",
                            body: formData,
                            credentials: "same-origin",
                            headers: {
                                "Accept": "application/json",
                                ...(this.csrfToken ? { "X-CSRF-TOKEN": this.csrfToken } : {})
                            },
                        });

                        if (!response.ok) throw new Error("Transcription failed");
                        const data = await response.json();

                        if (data.text) {
                            this.message = data.text;
                            this.statusMessage = "Audio transcribed successfully.";
                            this.statusType = "success";
                        }

                    } catch (error) {
                        this.statusMessage = "Error processing audio";
                        this.statusType = "error";
                    } finally {
                        this.chunks = [];
                        this.isRecording = false;
                    }
                };
            }).catch(err => {
                this.statusMessage = "Microphone access denied";
                this.statusType = "error";
            });
        },

        stopRecording() {
            if (this.mediaRecorder && this.isRecording) {
                this.mediaRecorder.stop();
                this.isRecording = false;
            }
        }
    }
};
</script>

<style scoped>
/* -- CSS Variables for easy theming (mimicking Tailwind colors) -- */
:root {
    --primary-gradient: ;
    --primary-hover: ;
    --bg-gray-50: #f9fafb;
    --bg-gray-100: #f3f4f6;
    --border-gray: #e5e7eb;
    --text-gray-800: #1f2937;
    --text-gray-600: #4b5563;
    --text-gray-400: #9ca3af;

    --color-blue-100: #dbeafe;
    --color-blue-600: #2563eb;
    --color-blue-800: #1e40af;

    --color-cyan-500: #06b6d4;
    --color-cyan-600: #0891b2;

    --color-slate-800: #1e293b;
    --color-slate-900: #0f172a;

    --status-loading-bg: #dbeafe;
    --status-loading-text: #1d4ed8;
    --status-success-bg: #dcfce7;
    --status-success-text: #15803d;
    --status-error-bg: #fee2e2;
    --status-error-text: #b91c1c;
}

/* -- Main Layout -- */
.chatContainer {
    max-width: 48rem; /* 3xl */
    margin: 0 auto;
    font-family: sans-serif;
}

.chat-card {
    background-color: white;
    border-radius: 1rem;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    overflow: hidden;
}


.audio-preview audio {
    height: 2rem;
    width: 12rem;
}

</style>
