'use client'

import { useState, useEffect } from 'react'
import { MessageSquare, Trash2, Loader2, Mail, Phone, Clock, Check, X, ChevronDown, ChevronUp } from 'lucide-react'

type Inquiry = {
  id: string; name: string; email: string; subject: string; message: string
  read: boolean; createdAt: string
}

export default function ContactInquiriesPage() {
  const [inquiries, setInquiries] = useState<Inquiry[]>([])
  const [loading, setLoading] = useState(true)
  const [expanded, setExpanded] = useState<string | null>(null)
  const [updating, setUpdating] = useState<string | null>(null)

  const load = async () => {
    try {
      const res = await fetch('/api/contact')
      if (res.ok) setInquiries(await res.json())
    } catch {} finally { setLoading(false) }
  }

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

  const toggleRead = async (id: string, read: boolean) => {
    setUpdating(id)
    await fetch(`/api/contact/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ read: !read }) })
    setUpdating(null)
    load()
  }

  const deleteInquiry = async (id: string) => {
    if (!confirm('حذف هذه الرسالة؟')) return
    setUpdating(id)
    await fetch(`/api/contact/${id}`, { method: 'DELETE' })
    setUpdating(null)
    load()
  }

  const unread = inquiries.filter(i => !i.read).length

  return (
    <div className="min-h-screen bg-gray-50" dir="rtl">
      <div className="pr-0 lg:pr-64">
        <div className="p-6 sm:p-8">
          <div className="flex items-center gap-3 mb-8">
            <div className="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
              <MessageSquare className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h1 className="text-2xl font-bold">رسائل الاتصال</h1>
              <p className="text-gray-500 text-sm">{inquiries.length} رسالة{unread > 0 && ` (${unread} غير مقروءة)`}</p>
            </div>
          </div>

          {loading ? (
            <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-blue-600" /></div>
          ) : inquiries.length === 0 ? (
            <div className="bg-white rounded-2xl border border-gray-100 p-16 text-center">
              <MessageSquare className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-gray-500">لا توجد رسائل</p>
            </div>
          ) : (
            <div className="space-y-3">
              {inquiries.map(inq => (
                <div key={inq.id} className={`bg-white rounded-2xl border shadow-sm transition-colors ${!inq.read ? 'border-blue-200 bg-blue-50/30' : 'border-gray-100'}`}>
                  <button onClick={() => setExpanded(expanded === inq.id ? null : inq.id)} className="w-full text-right p-5 flex items-start gap-4">
                    <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${inq.read ? 'bg-gray-100' : 'bg-blue-100'}`}>
                      <MessageSquare className={`w-5 h-5 ${inq.read ? 'text-gray-400' : 'text-blue-600'}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-semibold text-gray-900">{inq.name}</span>
                        {!inq.read && <span className="w-2 h-2 bg-blue-500 rounded-full" />}
                      </div>
                      <p className="text-sm text-gray-500 truncate">{inq.subject}</p>
                      <p className="text-xs text-gray-400 mt-1 flex items-center gap-1">
                        <Clock className="w-3 h-3" />{new Date(inq.createdAt).toLocaleString('ar-MA')}
                      </p>
                    </div>
                    <div className="flex items-center gap-1">
                      <span onClick={e => { e.stopPropagation(); toggleRead(inq.id, inq.read) }}
                        className={`p-2 rounded-lg text-xs transition-colors ${inq.read ? 'text-gray-400 hover:text-blue-600 hover:bg-blue-50' : 'text-blue-600 bg-blue-100 hover:bg-blue-200'}`}
                      >
                        {updating === inq.id ? <Loader2 className="w-4 h-4 animate-spin" /> : inq.read ? <X className="w-4 h-4" /> : <Check className="w-4 h-4" />}
                      </span>
                      <span onClick={e => { e.stopPropagation(); deleteInquiry(inq.id) }} className="p-2 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 transition-colors">
                        <Trash2 className="w-4 h-4" />
                      </span>
                      {expanded === inq.id ? <ChevronUp className="w-4 h-4 text-gray-400" /> : <ChevronDown className="w-4 h-4 text-gray-400" />}
                    </div>
                  </button>
                  {expanded === inq.id && (
                    <div className="px-5 pb-5 pt-0 border-t border-gray-100">
                      <div className="flex items-center gap-4 text-sm text-gray-500 mb-4 pt-4">
                        <span className="flex items-center gap-1"><Mail className="w-3.5 h-3.5" />{inq.email}</span>
                      </div>
                      <div className="bg-gray-50 rounded-xl p-4">
                        <p className="font-semibold text-gray-800 text-sm mb-2">{inq.subject}</p>
                        <p className="text-gray-600 text-sm leading-relaxed whitespace-pre-wrap">{inq.message}</p>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
