'use client'

import { useState, useRef, useEffect, useCallback } from 'react'
import { Send, Phone, MoreVertical } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useSafeSession } from '@/hooks/use-safe-session'

interface ChatMsg {
  id: string
  content: string
  sender: { id: string; name: string }
  createdAt: string
}

interface ChatWindowProps {
  conversationId?: string
  otherUserId?: string
  propertyId?: string
  otherUserName?: string
  otherUserImage?: string
}

export function ChatWindow({ otherUserId, propertyId, otherUserName = 'الوكيل العقاري', otherUserImage }: ChatWindowProps) {
  const { data: session } = useSafeSession()
  const [messages, setMessages] = useState<ChatMsg[]>([])
  const [input, setInput] = useState('')
  const [loading, setLoading] = useState(false)
  const [sending, setSending] = useState(false)
  const messagesEndRef = useRef<HTMLDivElement>(null)

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

  const fetchMessages = useCallback(async () => {
    if (!otherUserId) return
    setLoading(true)
    try {
      const res = await fetch(`/api/messages/conversation?with=${otherUserId}${propertyId ? `&property=${propertyId}` : ''}`)
      if (res.ok) { const data = await res.json(); setMessages(data.messages) }
    } catch {} finally { setLoading(false) }
  }, [otherUserId, propertyId])

  useEffect(() => { fetchMessages() }, [fetchMessages])
  useEffect(() => { scrollToBottom() }, [messages])

  const sendMessage = async () => {
    if (!input.trim() || !otherUserId) return
    setSending(true)
    try {
      const res = await fetch('/api/messages', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: input, receiverId: otherUserId, propertyId }),
      })
      if (res.ok) {
        const msg = await res.json()
        setMessages(prev => [...prev, msg])
        setInput('')
      }
    } catch {} finally { setSending(false) }
  }

  const userId = session?.user?.id

  return (
    <div className="bg-white rounded-2xl shadow-xl overflow-hidden flex flex-col h-[500px]">
      <div className="p-4 border-b bg-blue-50 flex justify-between items-center">
        <div className="flex items-center gap-3">
          <Avatar>
            <AvatarImage src={otherUserImage} />
            <AvatarFallback>{otherUserName[0]}</AvatarFallback>
          </Avatar>
          <div>
            <h3 className="font-bold">{otherUserName}</h3>
            <p className="text-xs text-green-600 flex items-center gap-1">
              <span className="w-2 h-2 bg-green-500 rounded-full" /> متصل الآن
            </p>
          </div>
        </div>
        <div className="flex gap-1">
          <Button variant="ghost" size="icon"><Phone className="w-5 h-5" /></Button>
          <Button variant="ghost" size="icon"><MoreVertical className="w-5 h-5" /></Button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {loading ? (
          <div className="flex justify-center py-10"><div className="w-6 h-6 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" /></div>
        ) : messages.length === 0 ? (
          <div className="text-center text-gray-400 py-10 text-sm">لا توجد رسائل بعد. ابدأ المحادثة!</div>
        ) : (
          messages.map((msg) => {
            const isMe = msg.sender.id === userId
            return (
              <div key={msg.id} className={`flex ${isMe ? 'justify-end' : 'justify-start'}`}>
                <div className={`max-w-[70%] p-3 rounded-2xl ${isMe ? 'bg-blue-600 text-white rounded-br-none' : 'bg-gray-100 text-gray-800 rounded-bl-none'}`}>
                  <p>{msg.content}</p>
                  <span className="text-xs opacity-70 mt-1 block">
                    {new Date(msg.createdAt).toLocaleTimeString('ar-MA', { hour: '2-digit', minute: '2-digit' })}
                  </span>
                </div>
              </div>
            )
          })
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="p-4 border-t">
        <div className="flex gap-2">
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && !sending && sendMessage()}
            placeholder="اكتب رسالتك..."
            className="flex-1 px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none"
          />
          <Button onClick={sendMessage} disabled={sending || !input.trim()} size="icon">
            <Send className="w-5 h-5" />
          </Button>
        </div>
      </div>
    </div>
  )
}
