// import { ref } from 'vue'; // Auto-imported by Nuxt

// Global state (Singleton pattern)
const ws = ref<WebSocket | null>(null);
const status = ref<'disconnected' | 'connecting' | 'connected'>('disconnected');
const messages = ref<any[]>([]);
const error = ref<string | null>(null);
const retryCount = ref(0);
const maxRetries = 5;
const currentHandshake = ref<{ operador_id: string, cliente_phone: string, cliente_id?: string } | null>(null);
const isSendingTemplate = ref(false);

export const useWhatsappChat = () => {

    // Configuration
    const config = useRuntimeConfig();
    const WS_URL = config.public.wsBase || "ws://localhost:6789";
    const API_URL = config.public.apiBase || "http://localhost:8081";

    const getWsUrl = () => {
        return WS_URL;
    };

    const getApiUrl = () => {
        return API_URL;
    };

    const connect = (operador_id: string, cliente_phone: string, cliente_id: string = '') => {
        if (ws.value) {
            ws.value.close();
        }

        currentHandshake.value = { operador_id, cliente_phone, cliente_id };
        status.value = 'connecting';
        error.value = null;

        try {
            const url = getWsUrl();
            // //console.log(`[WhatsApp] Connecting to ${url}...`);
            ws.value = new WebSocket(url);

            ws.value.onopen = () => {
                // //console.log("[WhatsApp] WebSocket Connected");
                status.value = 'connected';
                retryCount.value = 0;

                // Send handshake
                if (ws.value && currentHandshake.value) {
                    ws.value.send(JSON.stringify(currentHandshake.value));
                }
            };

            ws.value.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data);

                    const msg = {
                        id: data.id || Date.now() + Math.random(),
                        body: data.body || data.message || '',
                        from: data.from || 'unknown',
                        direction: data.direction || (data.operador_id ? 'out' : 'in'),
                        timestamp: data.timestamp || new Date(),
                        type: data.type || 'text',
                        media: data.media || null
                    };

                    messages.value.push(msg);

                } catch (e) {
                    // //console.warn("[WhatsApp] Received non-JSON message:", event.data);
                    messages.value.push({
                        id: Date.now(),
                        body: event.data,
                        from: 'server',
                        direction: 'in',
                        timestamp: new Date(),
                        type: 'text'
                    });
                }
            };

            ws.value.onclose = () => {
                //console.log("[WhatsApp] WebSocket Closed");
                status.value = 'disconnected';
                ws.value = null;

                // Auto reconnect
                if (retryCount.value < maxRetries) {
                    retryCount.value++;
                    const timeout = Math.min(1000 * Math.pow(2, retryCount.value), 30000);
                    //console.log(`[WhatsApp] Reconnecting in ${timeout}ms...`);
                    setTimeout(() => {
                        if (currentHandshake.value) {
                            connect(currentHandshake.value.operador_id, currentHandshake.value.cliente_phone, currentHandshake.value.cliente_id || '');
                        }
                    }, timeout);
                }
            };

            ws.value.onerror = (e) => {
                //console.error("[WhatsApp] WebSocket Error:", e);
                error.value = "Connection error";
            };

        } catch (e: any) {
            //console.error("[WhatsApp] Connection failed:", e);
            error.value = e.message;
            status.value = 'disconnected';
        }
    };

    const disconnect = () => {
        // Prevent auto-reconnect
        retryCount.value = maxRetries + 1;
        if (ws.value) {
            ws.value.close();
            ws.value = null;
        }
        status.value = 'disconnected';
        currentHandshake.value = null;
    };

    const sendMessage = (text: string) => {
        if (!ws.value || status.value !== 'connected') {
            //console.error("[WhatsApp] Not connected");
            return false;
        }

        try {
            const payload = {
                body: text,
                timestamp: Math.floor(Date.now() / 1000)
            };
            ws.value.send(JSON.stringify(payload));

            // Optimistic update
            messages.value.push({
                id: Date.now(),
                body: text,
                from: 'me',
                direction: 'out', // Outgoing
                timestamp: new Date(),
                type: 'text'
            });
            return true;
        } catch (e) {
            //console.error("[WhatsApp] Send failed:", e);
            return false;
        }
    };

    const clearMessages = () => {
        messages.value = [];
    };

    const startConversation = async (phone: string, template: string = 'hello_world') => {
        isSendingTemplate.value = true;
        try {
            const url = `${getApiUrl()}/send-template`;
            //console.log(`[WhatsApp] Sending template to ${url}...`);

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    to: phone,
                    template: template,
                    language: 'en_US'
                })
            });

            const data = await response.json();

            if (response.ok && data.success) {
                return true;
            } else {
                console.error("[WhatsApp] Failed to send template:", data);
                error.value = data.error || "Error al enviar plantilla";
                return false;
            }
        } catch (e: any) {
            console.error("[WhatsApp] Error starting conversation:", e);
            error.value = e.message;
            return false;
        } finally {
            isSendingTemplate.value = false;
        }
    };

    // State for conversations history
    const conversations = ref<any[]>([]);
    const loadingHistory = ref(false);

    const loadConversations = async () => {
        const config = useRuntimeConfig();
        const baseUrl = config.public.apiBase;

        try {
            const response = await fetch(`${baseUrl}/chat/conversaciones/`);
            if (response.ok) {
                const data = await response.json();
                conversations.value = data.map((c: any) => ({
                    ...c,
                    // Parse necessary fields for UI
                    name: c.cliente_phone, // TODO: Enhance with Client Name if available
                    phone: c.cliente_phone,
                    lastMessage: c.last_message ? c.last_message.content : '',
                    timestamp: c.ultima_actividad
                }));
            }
        } catch (e) {
            console.error("Error loading conversations", e);
        }
    };

    const loadMessages = async (conversacionId: number) => {
        const config = useRuntimeConfig();
        const baseUrl = config.public.apiBase;

        loadingHistory.value = true;
        try {
            const response = await fetch(`${baseUrl}/chat/mensajes/?conversacion_id=${conversacionId}`);
            if (response.ok) {
                const data = await response.json();
                // Merge or replace messages
                const history = data.map((m: any) => ({
                    id: m.id,
                    body: m.content || '',
                    from: m.sender_type === 'operator' ? 'me' : 'client',
                    direction: m.sender_type === 'operator' ? 'out' : 'in',
                    timestamp: m.timestamp, // Assuming text parser in backend sends format
                    type: m.message_type || 'text',
                    media: m.media_url
                }));

                // Prepend history to current messages (or replace if clean load)
                messages.value = history;
            }
        } catch (e) {
            console.error("Error loading messages", e);
        } finally {
            loadingHistory.value = false;
        }
    };

    return {
        ws,
        status,
        messages,
        conversations,
        error,
        connect,
        disconnect,
        sendMessage,
        clearMessages,
        startConversation,
        isSendingTemplate,
        loadConversations,
        loadMessages
    };
};
