'use client'

import { useState, useEffect, useRef } from 'react'
import { useSession } from 'next-auth/react'

interface Message {
  id: string
  roomId: string
  senderId: string
  isAdmin: boolean
  text: string
  isRead: boolean
  createdAt: string
}

export default function LiveChat() {
  const { data: session } = useSession()
  const [isOpen, setIsOpen] = useState(false)
  const [room, setRoom] = useState<any>(null)
  const [messages, setMessages] = useState<Message[]>([])
  const [text, setText] = useState('')
  const [unread, setUnread] = useState(0)
  const [isSending, setIsSending] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const esRef = useRef<EventSource | null>(null)

  const isAdmin = session?.user?.role === 'ADMIN'
  const isLoggedIn = !!session?.user?.id

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  const fetchRoom = async () => {
    try {
      const res = await fetch('/api/chat/rooms')
      if (!res.ok) return
      const r = await res.json()
      setRoom(r)
      setUnread(r.unreadUser || 0)
    } catch (e) {}
  }

  const fetchMessages = async (roomId: string) => {
    try {
      const res = await fetch(`/api/chat/messages?roomId=${roomId}`)
      if (!res.ok) return
      setMessages(await res.json())
      setUnread(0)
      setTimeout(scrollToBottom, 100)
    } catch (e) {}
  }

  useEffect(() => {
    if (!isLoggedIn || isAdmin) return
    fetchRoom()
  }, [isLoggedIn, isAdmin])

  useEffect(() => {
    if (!room?.id || isAdmin) return

    fetchMessages(room.id)

    const es = new EventSource(`/api/chat/events/${room.id}`)
    esRef.current = es

    es.addEventListener('new_message', (e) => {
      const msg: Message = JSON.parse(e.data)
      setMessages(prev => prev.find(m => m.id === msg.id) ? prev : [...prev, msg])
      setUnread(prev => isOpen ? 0 : prev + 1)
      setTimeout(scrollToBottom, 100)
    })

    return () => {
      es.close()
      esRef.current = null
    }
  }, [room?.id])

  const handleOpen = () => {
    setIsOpen(true)
    setUnread(0)
    if (room?.id) {
      fetchMessages(room.id)
    } else {
      fetchRoom()
    }
  }

  const sendMessage = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!text.trim() || !room?.id || isSending) return

    setIsSending(true)
    const payload = text.trim()
    setText('')

    try {
      const res = await fetch('/api/chat/messages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ roomId: room.id, text: payload }),
      })
      if (res.ok) {
        const msg = await res.json()
        setMessages(prev => prev.find(m => m.id === msg.id) ? prev : [...prev, msg])
        setTimeout(scrollToBottom, 100)
      }
    } catch (e) {}
    setIsSending(false)
  }

  // ❗ Conditional rendering in return — NOT early return before hooks
  if (!isLoggedIn || isAdmin) return null

  return (
    <>
      {/* Bubble Button */}
      {!isOpen && (
        <button
          onClick={handleOpen}
          id="live-chat-btn"
          aria-label="Buka Live Chat"
          style={{
            position: 'fixed',
            bottom: '24px',
            right: '24px',
            zIndex: 9998,
            width: '56px',
            height: '56px',
            borderRadius: '50%',
            background: 'linear-gradient(135deg, #f59e0b, #d97706)',
            border: 'none',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '22px',
            boxShadow: '0 4px 20px rgba(245, 158, 11, 0.5)',
            transition: 'transform 0.2s',
          }}
          onMouseEnter={e => (e.currentTarget.style.transform = 'scale(1.1)')}
          onMouseLeave={e => (e.currentTarget.style.transform = 'scale(1)')}
        >
          💬
          {unread > 0 && (
            <span style={{
              position: 'absolute',
              top: '-4px',
              right: '-4px',
              background: '#ef4444',
              color: '#fff',
              borderRadius: '50%',
              width: '20px',
              height: '20px',
              fontSize: '11px',
              fontWeight: 700,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              border: '2px solid #0a0a0f',
            }}>
              {unread > 9 ? '9+' : unread}
            </span>
          )}
        </button>
      )}

      {/* Chat Window */}
      {isOpen && (
        <div style={{
          position: 'fixed',
          bottom: '24px',
          right: '24px',
          zIndex: 9998,
          width: '340px',
          height: '480px',
          background: '#111118',
          borderRadius: '16px',
          border: '1px solid rgba(255,255,255,0.08)',
          boxShadow: '0 20px 60px rgba(0,0,0,0.7)',
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden',
          animation: 'slideUpChat 0.3s ease',
        }}>
          {/* Header */}
          <div style={{
            background: 'linear-gradient(135deg, #f59e0b, #d97706)',
            padding: '14px 16px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '14px' }}>
                🎧
              </div>
              <div>
                <div style={{ fontWeight: 700, color: '#fff', fontSize: '14px' }}>Live Chat Support</div>
                <div style={{ fontSize: '11px', color: 'rgba(255,255,255,0.8)' }}>
                  <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#4ade80', marginRight: 4 }} />
                  Admin siap membantu
                </div>
              </div>
            </div>
            <button
              onClick={() => setIsOpen(false)}
              style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.8)', cursor: 'pointer', fontSize: '18px', lineHeight: 1 }}
            >
              ✕
            </button>
          </div>

          {/* Messages */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '16px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
            {messages.length === 0 && (
              <div style={{ textAlign: 'center', color: '#64748b', fontSize: '13px', marginTop: '40px' }}>
                <div style={{ fontSize: '32px', marginBottom: '8px' }}>👋</div>
                <div>Halo! Ada yang bisa kami bantu?</div>
                <div style={{ marginTop: '4px', fontSize: '12px' }}>Kirim pesan dan admin akan segera membalas.</div>
              </div>
            )}
            {messages.map(msg => (
              <div key={msg.id} style={{ display: 'flex', justifyContent: msg.isAdmin ? 'flex-start' : 'flex-end' }}>
                <div style={{
                  maxWidth: '75%',
                  padding: '8px 12px',
                  borderRadius: msg.isAdmin ? '4px 12px 12px 12px' : '12px 4px 12px 12px',
                  background: msg.isAdmin ? '#1e293b' : 'linear-gradient(135deg, #f59e0b, #d97706)',
                  color: '#f1f5f9',
                  fontSize: '13px',
                  lineHeight: 1.5,
                  wordBreak: 'break-word',
                }}>
                  {msg.text}
                  <div style={{ fontSize: '10px', color: 'rgba(255,255,255,0.5)', marginTop: '3px', textAlign: 'right' }}>
                    {new Date(msg.createdAt).toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' })}
                  </div>
                </div>
              </div>
            ))}
            <div ref={messagesEndRef} />
          </div>

          {/* Input */}
          <form onSubmit={sendMessage} style={{
            padding: '12px',
            borderTop: '1px solid rgba(255,255,255,0.06)',
            display: 'flex',
            gap: '8px',
          }}>
            <input
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder="Ketik pesan..."
              style={{
                flex: 1,
                background: '#0a0a0f',
                border: '1px solid rgba(255,255,255,0.1)',
                borderRadius: '8px',
                padding: '8px 12px',
                color: '#f1f5f9',
                fontSize: '13px',
                outline: 'none',
              }}
            />
            <button
              type="submit"
              disabled={!text.trim() || isSending}
              style={{
                background: 'linear-gradient(135deg, #f59e0b, #d97706)',
                border: 'none',
                borderRadius: '8px',
                padding: '8px 14px',
                color: '#fff',
                cursor: (!text.trim() || isSending) ? 'not-allowed' : 'pointer',
                opacity: (!text.trim() || isSending) ? 0.6 : 1,
                fontSize: '14px',
              }}
            >
              ➤
            </button>
          </form>
        </div>
      )}

      <style>{`
        @keyframes slideUpChat {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </>
  )
}
