'use client'

import { useState, useEffect, useRef } from 'react'
import { formatDistanceToNow } from 'date-fns'
import { id as idLocale } from 'date-fns/locale'

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

interface Room {
  id: string
  userId: string
  unreadAdmin: number
  lastMessage: string | null
  updatedAt: string
  user: { id: string; name: string; email: string; image?: string }
  messages: Message[]
}

export default function AdminChatPage() {
  const [rooms, setRooms] = useState<Room[]>([])
  const [selectedRoom, setSelectedRoom] = useState<Room | null>(null)
  const [messages, setMessages] = useState<Message[]>([])
  const [text, setText] = useState('')
  const [isSending, setIsSending] = useState(false)
  const [totalUnread, setTotalUnread] = useState(0)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const esRef = useRef<EventSource | null>(null)

  const fetchRooms = async () => {
    const res = await fetch('/api/chat/rooms')
    if (!res.ok) return
    const data: Room[] = await res.json()
    setRooms(data)
    setTotalUnread(data.reduce((acc, r) => acc + r.unreadAdmin, 0))
  }

  useEffect(() => {
    fetchRooms()
    const interval = setInterval(fetchRooms, 10000)
    return () => clearInterval(interval)
  }, [])

  const fetchMessages = async (roomId: string) => {
    const res = await fetch(`/api/chat/messages?roomId=${roomId}`)
    if (!res.ok) return
    const msgs: Message[] = await res.json()
    setMessages(msgs)
    setTimeout(() => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100)
    // Refresh rooms to reset unread
    fetchRooms()
  }

  const openRoom = (room: Room) => {
    setSelectedRoom(room)
    fetchMessages(room.id)

    // Close previous SSE
    if (esRef.current) esRef.current.close()

    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])
      setTimeout(() => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100)
      fetchRooms()
    })
  }

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

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

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

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h1 style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '4px' }}>
            💬 Live Chat Support
            {totalUnread > 0 && (
              <span style={{ marginLeft: '10px', background: '#ef4444', color: '#fff', borderRadius: '100px', padding: '2px 10px', fontSize: '14px', fontWeight: 700 }}>
                {totalUnread}
              </span>
            )}
          </h1>
          <p style={{ color: '#94a3b8' }}>Balas pesan dari pengguna secara realtime</p>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: '20px', height: 'calc(100vh - 240px)', minHeight: '500px' }}>
        {/* Rooms List */}
        <div className="card" style={{ padding: 0, overflowY: 'auto' }}>
          {rooms.length === 0 && (
            <div style={{ padding: '32px', textAlign: 'center', color: '#64748b' }}>
              <div style={{ fontSize: '32px', marginBottom: '8px' }}>💬</div>
              <div>Belum ada chat masuk</div>
            </div>
          )}
          {rooms.map(room => (
            <div
              key={room.id}
              onClick={() => openRoom(room)}
              style={{
                padding: '14px 16px',
                borderBottom: '1px solid rgba(255,255,255,0.04)',
                cursor: 'pointer',
                background: selectedRoom?.id === room.id ? 'rgba(245,158,11,0.08)' : 'transparent',
                borderLeft: selectedRoom?.id === room.id ? '3px solid #f59e0b' : '3px solid transparent',
                transition: 'all 0.15s',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
                <div style={{ fontWeight: 600, color: '#f1f5f9', fontSize: '14px' }}>{room.user.name}</div>
                {room.unreadAdmin > 0 && (
                  <span style={{ background: '#ef4444', color: '#fff', borderRadius: '100px', padding: '1px 7px', fontSize: '11px', fontWeight: 700 }}>
                    {room.unreadAdmin}
                  </span>
                )}
              </div>
              <div style={{ fontSize: '12px', color: '#64748b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {room.lastMessage || 'Belum ada pesan'}
              </div>
              <div style={{ fontSize: '10px', color: '#475569', marginTop: '3px' }}>
                {formatDistanceToNow(new Date(room.updatedAt), { addSuffix: true, locale: idLocale })}
              </div>
            </div>
          ))}
        </div>

        {/* Chat Window */}
        <div className="card" style={{ padding: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {!selectedRoom ? (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#64748b' }}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '48px', marginBottom: '12px' }}>👈</div>
                <div>Pilih percakapan untuk memulai</div>
              </div>
            </div>
          ) : (
            <>
              {/* Chat Header */}
              <div style={{ padding: '14px 20px', borderBottom: '1px solid rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', gap: '12px' }}>
                <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: 'linear-gradient(135deg, #f59e0b, #d97706)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, color: '#fff', fontSize: '14px' }}>
                  {selectedRoom.user.name[0]}
                </div>
                <div>
                  <div style={{ fontWeight: 600, color: '#f1f5f9' }}>{selectedRoom.user.name}</div>
                  <div style={{ fontSize: '12px', color: '#64748b' }}>{selectedRoom.user.email}</div>
                </div>
              </div>

              {/* Messages */}
              <div style={{ flex: 1, overflowY: 'auto', padding: '20px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
                {messages.map(msg => (
                  <div key={msg.id} style={{ display: 'flex', justifyContent: msg.isAdmin ? 'flex-end' : 'flex-start' }}>
                    <div style={{
                      maxWidth: '60%',
                      padding: '8px 14px',
                      borderRadius: msg.isAdmin ? '12px 4px 12px 12px' : '4px 12px 12px 12px',
                      background: msg.isAdmin ? 'linear-gradient(135deg, #f59e0b, #d97706)' : '#1e293b',
                      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' })}
                        {msg.isAdmin && <span style={{ marginLeft: 4 }}>{msg.isRead ? '✓✓' : '✓'}</span>}
                      </div>
                    </div>
                  </div>
                ))}
                <div ref={messagesEndRef} />
              </div>

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