'use client'

import { useState, useEffect } from 'react'
import { ChatWindow } from '@/components/chat/chat-window'
import { Search, MessageSquare, Loader2 } from 'lucide-react'

type Conversation = {
  id: string
  otherUser: { id: string; name: string; image: string | null }
  property: { id: string; title: string; image: string } | null
  lastMessage: string
  lastMessageAt: string
  unread: number
}

export default function MessagesPage() {
  const [conversations, setConversations] = useState<Conversation[]>([])
  const [selected, setSelected] = useState<Conversation | null>(null)
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/messages')
      .then(r => r.json())
      .then(d => { setConversations(d.conversations || []); if (d.conversations?.[0]) setSelected(d.conversations[0]) })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  const filtered = conversations.filter(c =>
    c.otherUser.name?.includes(search) || c.property?.title?.includes(search)
  )

  const timeAgo = (dateStr: string) => {
    const now = Date.now()
    const diff = now - new Date(dateStr).getTime()
    const mins = Math.floor(diff / 60000)
    if (mins < 1) return 'الآن'
    if (mins < 60) return `منذ ${mins} دقيقة`
    const hours = Math.floor(mins / 60)
    if (hours < 24) return `منذ ${hours} ساعة`
    const days = Math.floor(hours / 24)
    if (days < 7) return `منذ ${days} يوم`
    return new Date(dateStr).toLocaleDateString('ar-MA')
  }

  return (
    <div className="min-h-screen bg-gray-50" dir="rtl">
      <div className="container mx-auto px-4 py-6">
        <h1 className="text-2xl font-bold mb-6 flex items-center gap-2">
          <MessageSquare className="w-6 h-6 text-blue-600" />
          الرسائل
        </h1>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 h-[calc(100vh-180px)]">
          <div className="bg-white rounded-2xl shadow-sm border overflow-hidden flex flex-col">
            <div className="p-4 border-b">
              <div className="relative">
                <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                  placeholder="بحث في الرسائل..."
                  className="w-full pr-10 pl-4 py-2 border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50"
                />
              </div>
            </div>
            <div className="overflow-y-auto flex-1">
              {loading ? (
                <div className="flex justify-center py-10"><Loader2 className="w-6 h-6 animate-spin text-blue-600" /></div>
              ) : filtered.length === 0 ? (
                <div className="text-center py-10 text-gray-400 text-sm">لا توجد محادثات</div>
              ) : (
                filtered.map(conv => (
                  <button
                    key={conv.id}
                    onClick={() => setSelected(conv)}
                    className={`w-full p-4 text-right border-b transition-colors hover:bg-gray-50 ${selected?.id === conv.id ? 'bg-blue-50 border-r-2 border-r-blue-500' : ''}`}
                  >
                    <div className="flex items-start gap-3">
                      <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 font-bold shrink-0">
                        {conv.otherUser.name?.[0] || 'م'}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex justify-between items-center mb-0.5">
                          <span className="font-medium text-sm">{conv.otherUser.name || 'مستخدم'}</span>
                          <span className="text-xs text-gray-400">{timeAgo(conv.lastMessageAt)}</span>
                        </div>
                        {conv.property && (
                          <p className="text-xs text-gray-500 truncate">{conv.property.title}</p>
                        )}
                        <p className="text-xs text-gray-600 truncate mt-0.5">{conv.lastMessage}</p>
                      </div>
                      {conv.unread > 0 && (
                        <span className="bg-blue-600 text-white text-xs w-5 h-5 rounded-full flex items-center justify-center shrink-0">
                          {conv.unread}
                        </span>
                      )}
                    </div>
                  </button>
                ))
              )}
            </div>
          </div>

          <div className="lg:col-span-2">
            {selected ? (
              <div>
                {selected.property && (
                  <div className="mb-3 text-sm text-gray-500 bg-white rounded-xl px-4 py-2 border">
                    العقار: <span className="text-blue-600 font-medium">{selected.property.title}</span>
                  </div>
                )}
                <ChatWindow
                  otherUserId={selected.otherUser.id}
                  propertyId={selected.property?.id}
                  otherUserName={selected.otherUser.name || 'مستخدم'}
                  otherUserImage={selected.otherUser.image || ''}
                />
              </div>
            ) : (
              <div className="h-full flex items-center justify-center text-gray-400">
                <div className="text-center">
                  <MessageSquare className="w-12 h-12 mx-auto mb-3 opacity-30" />
                  <p>اختر محادثة للبدء</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
