import React, { useState, useEffect, useRef } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { MessageCircle, X, Send, ArrowLeft, Loader2 } from 'lucide-react'
import api from '../axios'

const ease = [0.22, 1, 0.36, 1]
const WHATSAPP_NUMBER = '2348029921409' // ← CHANGE to your WhatsApp number

export default function ChatBubble() {
    const [open, setOpen] = useState(false)
    const [view, setView] = useState('menu') // menu | chat
    const [messages, setMessages] = useState([])
    const [input, setInput] = useState('')
    const [loading, setLoading] = useState(false)
    const [sending, setSending] = useState(false)
    const [unread, setUnread] = useState(0)
    const scrollRef = useRef(null)
    const pollRef = useRef(null)

    // Poll unread count while closed
    useEffect(() => {
        const checkUnread = () => {
            api.get('/support/unread').then(r => setUnread(r.data.unread)).catch(() => {})
        }
        checkUnread()
        const t = setInterval(checkUnread, 8000)
        return () => clearInterval(t)
    }, [])

    // Poll messages while chat open
    useEffect(() => {
        if (open && view === 'chat') {
            fetchMessages()
            pollRef.current = setInterval(fetchMessages, 5000)
        } else {
            clearInterval(pollRef.current)
        }
        return () => clearInterval(pollRef.current)
    }, [open, view])

    useEffect(() => {
        if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    }, [messages])

    const fetchMessages = async () => {
        try {
            const res = await api.get('/support/messages')
            setMessages(res.data.messages)
            setUnread(0)
        } catch (e) { console.error(e) }
    }

    const openChat = async () => {
        setView('chat')
        setLoading(true)
        await fetchMessages()
        setLoading(false)
    }

    const send = async () => {
        if (!input.trim() || sending) return
        const text = input.trim()
        setInput('')
        setSending(true)
        // Optimistic
        setMessages(m => [...m, { id: 'temp', message: text, sender: 'user', created_at: new Date().toISOString() }])
        try {
            await api.post('/support/send', { message: text })
            await fetchMessages()
        } catch (e) {
            console.error(e)
        } finally {
            setSending(false)
        }
    }

    const openWhatsApp = () => {
        window.open(`https://wa.me/${WHATSAPP_NUMBER}?text=Hi%20Fargo%20Topup%2C%20I%20need%20help`, '_blank')
    }

    return (
        <>
            {/* Floating bubble */}
            <motion.button
                drag
                dragMomentum={false}
                dragConstraints={{ left: -300, right: 0, top: -500, bottom: 0 }}
                whileTap={{ scale: 0.9 }}
                onClick={() => { setOpen(true); setView('menu') }}
                className="fixed bottom-24 right-5 w-14 h-14 rounded-full flex items-center justify-center z-50 card-shadow-lg cursor-grab active:cursor-grabbing"
                style={{ background: 'var(--accent)' }}
            >
                <MessageCircle size={24} className="text-white" />
                {unread > 0 && (
                    <span className="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-bad text-white text-[10px] font-bold flex items-center justify-center">
                        {unread}
                    </span>
                )}
            </motion.button>

            <AnimatePresence>
                {open && (
                    <motion.div
                        initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
                        onClick={() => setOpen(false)}
                        className="fixed inset-0 bg-black/40 flex items-end sm:items-center justify-center z-[55] p-4"
                    >
                        <motion.div
                            initial={{ y: 40, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 40, opacity: 0 }}
                            transition={{ duration: 0.4, ease }}
                            onClick={e => e.stopPropagation()}
                            className="bg-surface border border-line rounded-3xl w-full max-w-[400px] overflow-hidden card-shadow-lg flex flex-col"
                            style={{ height: view === 'chat' ? '70vh' : 'auto', maxHeight: '600px' }}
                        >
                            {view === 'menu' ? (
                                <div className="p-6">
                                    <div className="flex items-center justify-between mb-1">
                                        <h3 className="text-txt text-[18px] font-semibold">Need help?</h3>
                                        <button onClick={() => setOpen(false)} className="text-txt-3"><X size={20} /></button>
                                    </div>
                                    <p className="text-txt-3 text-[13px] mb-6">We usually reply within minutes</p>

                                    <motion.button
                                        whileTap={{ scale: 0.98 }}
                                        onClick={openChat}
                                        className="w-full bg-accent-soft border border-accent rounded-2xl p-4 flex items-center gap-3 mb-3"
                                    >
                                        <div className="w-11 h-11 rounded-xl flex items-center justify-center" style={{ background: 'var(--accent)' }}>
                                            <MessageCircle size={20} className="text-white" />
                                        </div>
                                        <div className="text-left">
                                            <p className="text-txt text-[14px] font-semibold">Chat with us</p>
                                            <p className="text-txt-3 text-[12px]">In-app live support</p>
                                        </div>
                                    </motion.button>

                                    <motion.button
                                        whileTap={{ scale: 0.98 }}
                                        onClick={openWhatsApp}
                                        className="w-full bg-surface border border-line rounded-2xl p-4 flex items-center gap-3 card-shadow"
                                    >
                                        <div className="w-11 h-11 rounded-xl flex items-center justify-center bg-[#25D366]">
                                            <svg width="22" height="22" viewBox="0 0 24 24" fill="white">
                                                <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.1-.2.3-.7.9-.8 1-.2.2-.3.2-.6.1-.3-.1-1.2-.5-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6l.4-.5c.1-.2.2-.3.2-.5.1-.2 0-.3 0-.5 0-.1-.6-1.5-.9-2-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.4s1 2.8 1.2 3c.1.2 2 3.1 4.9 4.3.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.6-.3zM12 2a10 10 0 00-8.5 15.3L2 22l4.8-1.5A10 10 0 1012 2z"/>
                                            </svg>
                                        </div>
                                        <div className="text-left">
                                            <p className="text-txt text-[14px] font-semibold">WhatsApp</p>
                                            <p className="text-txt-3 text-[12px]">Chat on WhatsApp instead</p>
                                        </div>
                                    </motion.button>
                                </div>
                            ) : (
                                <>
                                    {/* Chat header */}
                                    <div className="flex items-center gap-3 p-4 border-b border-line-soft">
                                        <button onClick={() => setView('menu')} className="text-txt-2"><ArrowLeft size={18} /></button>
                                        <div className="flex-1">
                                            <p className="text-txt text-[14px] font-semibold">Fargo Support</p>
                                            <p className="text-ok text-[11px]">● Online</p>
                                        </div>
                                        <button onClick={() => setOpen(false)} className="text-txt-3"><X size={20} /></button>
                                    </div>

                                    {/* Messages */}
                                    <div ref={scrollRef} className="flex-1 overflow-y-auto no-scrollbar p-4 space-y-3">
                                        {loading ? (
                                            <div className="flex justify-center py-8"><Loader2 size={20} className="animate-spin text-accent" /></div>
                                        ) : messages.length === 0 ? (
                                            <div className="text-center py-8">
                                                <p className="text-txt-3 text-[13px]">Send us a message and we'll reply shortly</p>
                                            </div>
                                        ) : messages.map((m, i) => (
                                            <div key={m.id || i} className={`flex ${m.sender === 'user' ? 'justify-end' : 'justify-start'}`}>
                                                <div
                                                    className={`max-w-[75%] px-4 py-2.5 rounded-2xl text-[14px] ${m.sender === 'user' ? 'text-white rounded-br-sm' : 'bg-raised text-txt rounded-bl-sm'}`}
                                                    style={m.sender === 'user' ? { background: 'var(--accent)' } : {}}
                                                >
                                                    {m.message}
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    {/* Input */}
                                    <div className="p-3 border-t border-line-soft flex items-center gap-2">
                                        <input
                                            value={input}
                                            onChange={e => setInput(e.target.value)}
                                            onKeyDown={e => e.key === 'Enter' && send()}
                                            placeholder="Type a message…"
                                            className="glow-focus flex-1 bg-raised text-txt text-[14px] rounded-xl px-4 py-3 border border-line outline-none"
                                        />
                                        <motion.button
                                            whileTap={{ scale: 0.9 }}
                                            onClick={send}
                                            disabled={!input.trim() || sending}
                                            className="w-11 h-11 rounded-xl flex items-center justify-center text-white disabled:opacity-40"
                                            style={{ background: 'var(--accent)' }}
                                        >
                                            <Send size={18} />
                                        </motion.button>
                                    </div>
                                </>
                            )}
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>
        </>
    )
}