import React, { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { ArrowLeft, Send, ArrowLeft as Back, Loader2 } from 'lucide-react'
import api from '../../axios'
import Avatar from '../../components/Avatars'

const ease = [0.22, 1, 0.36, 1]
const transition = { duration: 0.4, ease }

export default function AdminSupport() {
    const navigate = useNavigate()
    const [conversations, setConversations] = useState([])
    const [loading, setLoading] = useState(true)
    const [active, setActive] = useState(null) // selected user
    const [messages, setMessages] = useState([])
    const [input, setInput] = useState('')
    const [sending, setSending] = useState(false)
    const scrollRef = useRef(null)
    const pollRef = useRef(null)

    useEffect(() => { fetchInbox() }, [])

    useEffect(() => {
        if (active) {
            fetchConversation(active.user_id)
            pollRef.current = setInterval(() => fetchConversation(active.user_id), 5000)
        } else {
            clearInterval(pollRef.current)
        }
        return () => clearInterval(pollRef.current)
    }, [active])

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

    const fetchInbox = async () => {
        setLoading(true)
        try {
            const res = await api.get('/admin/support/inbox')
            setConversations(res.data.conversations)
        } catch (e) { console.error(e) }
        finally { setLoading(false) }
    }

    const fetchConversation = async (userId) => {
        try {
            const res = await api.get(`/admin/support/conversation/${userId}`)
            setMessages(res.data.messages)
        } catch (e) { console.error(e) }
    }

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

    // Conversation view
    if (active) {
        return (
            <div className="min-h-screen bg-bg max-w-[480px] mx-auto flex flex-col">
                <header className="flex items-center gap-3 px-5 pt-7 pb-4 border-b border-line-soft">
                    <button onClick={() => { setActive(null); fetchInbox() }} className="text-txt-2"><Back size={20} /></button>
                    <div className="w-9 h-9 rounded-full overflow-hidden border" style={{ borderColor: 'var(--accent)' }}>
                        <Avatar id={active.user?.avatar || 'fox'} size={36} />
                    </div>
                    <div>
                        <p className="text-txt text-[14px] font-semibold">{active.user?.name}</p>
                        <p className="text-txt-3 text-[11px]">{active.user?.email}</p>
                    </div>
                </header>

                <div ref={scrollRef} className="flex-1 overflow-y-auto no-scrollbar p-4 space-y-3" style={{ height: 'calc(100vh - 160px)' }}>
                    {messages.map((m, i) => (
                        <div key={m.id || i} className={`flex ${m.sender === 'admin' ? 'justify-end' : 'justify-start'}`}>
                            <div
                                className={`max-w-[75%] px-4 py-2.5 rounded-2xl text-[14px] ${m.sender === 'admin' ? 'text-white rounded-br-sm' : 'bg-raised text-txt rounded-bl-sm'}`}
                                style={m.sender === 'admin' ? { background: 'var(--accent)' } : {}}
                            >
                                {m.message}
                            </div>
                        </div>
                    ))}
                </div>

                <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' && reply()}
                        placeholder="Type your reply…"
                        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={reply}
                        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>
            </div>
        )
    }

    // Inbox list view
    return (
        <div className="min-h-screen bg-bg pb-12 max-w-[480px] mx-auto">
            <motion.header
                initial={{ opacity: 0, y: -12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={transition}
                className="flex items-center gap-3 px-6 pt-7 pb-4"
            >
                <button
                    onClick={() => navigate('/admin')}
                    className="w-10 h-10 rounded-xl bg-surface border border-line card-shadow flex items-center justify-center text-txt-2"
                >
                    <ArrowLeft size={18} />
                </button>
                <h1 className="text-txt text-[18px] font-semibold">Support Inbox</h1>
            </motion.header>

            <div className="px-6">
                {loading ? (
                    <div className="space-y-3">{[1,2,3].map(i => <div key={i} className="shimmer h-20 rounded-2xl" />)}</div>
                ) : conversations.length === 0 ? (
                    <div className="bg-surface border border-line rounded-2xl py-12 text-center card-shadow">
                        <p className="text-txt-3 text-[14px]">No messages yet</p>
                    </div>
                ) : conversations.map((c, i) => (
                    <motion.button
                        key={c.user_id}
                        initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ ...transition, delay: i * 0.04 }}
                        onClick={() => setActive(c)}
                        className="w-full bg-surface border border-line rounded-2xl p-4 mb-3 flex items-center gap-3 card-shadow"
                    >
                        <div className="w-11 h-11 rounded-full overflow-hidden border flex-shrink-0" style={{ borderColor: 'var(--accent)' }}>
                            <Avatar id={c.user?.avatar || 'fox'} size={44} />
                        </div>
                        <div className="flex-1 text-left">
                            <p className="text-txt text-[14px] font-medium">{c.user?.name || 'User'}</p>
                            <p className="text-txt-3 text-[12px]">{c.user?.email}</p>
                        </div>
                        {c.unread > 0 && (
                            <span className="w-6 h-6 rounded-full bg-bad text-white text-[11px] font-bold flex items-center justify-center">
                                {c.unread}
                            </span>
                        )}
                    </motion.button>
                ))}
            </div>
        </div>
    )
}