'use client'

import { useState, useEffect } from 'react'
import { Users, Trash2, Search, Loader2 } from 'lucide-react'

const ROLE_LABELS: Record<string, string> = {
  USER: 'مستخدم', AGENT: 'وكيل', DEVELOPER: 'مطور', ADMIN: 'مدير', CRAFTSMAN: 'حرفي',
}
const ROLE_COLORS: Record<string, string> = {
  USER: 'bg-gray-100 text-gray-700', AGENT: 'bg-blue-100 text-blue-700',
  DEVELOPER: 'bg-purple-100 text-purple-700', ADMIN: 'bg-amber-100 text-amber-700',
  CRAFTSMAN: 'bg-emerald-100 text-emerald-700',
}

type User = {
  id: string; name: string | null; email: string | null; phone: string | null
  role: string; verified: boolean; createdAt: string
  _count: { properties: number; craftsmen: number }
}

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [saving, setSaving] = useState<string | null>(null)
  const [deleting, setDeleting] = useState<string | null>(null)

  const fetchUsers = async () => {
    try {
      const res = await fetch('/api/users')
      if (!res.ok) return
      setUsers(await res.json())
    } catch {} finally {
      setLoading(false)
    }
  }

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

  const updateRole = async (id: string, role: string) => {
    setSaving(id)
    await fetch('/api/users', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, role }) })
    setSaving(null)
    fetchUsers()
  }

  const deleteUser = async (id: string) => {
    if (!confirm('هل أنت متأكد من حذف هذا المستخدم؟')) return
    setDeleting(id)
    await fetch('/api/users', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) })
    setDeleting(null)
    fetchUsers()
  }

  const filtered = users.filter(u =>
    !search || (u.name && u.name.includes(search)) || (u.email && u.email.includes(search)) || (u.phone && u.phone.includes(search))
  )

  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">
              <Users className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h1 className="text-2xl font-bold">إدارة المستخدمين</h1>
              <p className="text-gray-500 text-sm">{users.length} مستخدم</p>
            </div>
          </div>

          <div className="relative mb-6">
            <Search className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              className="w-full border border-gray-200 rounded-xl pr-12 pl-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="بحث عن مستخدم..."
              value={search} onChange={e => setSearch(e.target.value)}
            />
          </div>

          {loading ? (
            <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-blue-600" /></div>
          ) : filtered.length === 0 ? (
            <div className="text-center py-20">
              <Users className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <p className="text-gray-500">{search ? 'لا توجد نتائج' : 'لا يوجد مستخدمين'}</p>
            </div>
          ) : (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-100 bg-gray-50">
                      <th className="text-right px-4 py-3 font-semibold text-gray-700">الاسم</th>
                      <th className="text-right px-4 py-3 font-semibold text-gray-700">البريد</th>
                      <th className="text-right px-4 py-3 font-semibold text-gray-700">الهاتف</th>
                      <th className="text-right px-4 py-3 font-semibold text-gray-700">الدور</th>
                      <th className="text-center px-4 py-3 font-semibold text-gray-700">عقارات</th>
                      <th className="text-center px-4 py-3 font-semibold text-gray-700">حرفيون</th>
                      <th className="text-center px-4 py-3 font-semibold text-gray-700">تاريخ</th>
                      <th className="text-center px-4 py-3 font-semibold text-gray-700"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.map(u => (
                      <tr key={u.id} className="border-b border-gray-50 hover:bg-gray-50 transition-colors">
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 font-bold text-xs">
                              {(u.name || 'م')[0]}
                            </div>
                            <span className="font-medium">{u.name || 'مستخدم'}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-gray-500">{u.email || '—'}</td>
                        <td className="px-4 py-3 text-gray-500">{u.phone || '—'}</td>
                        <td className="px-4 py-3">
                          <div className="relative">
                            <select
                              className={`appearance-none border-0 rounded-lg px-3 py-1.5 text-xs font-medium cursor-pointer focus:outline-none focus:ring-2 focus:ring-blue-500 ${ROLE_COLORS[u.role] || 'bg-gray-100 text-gray-700'}`}
                              value={u.role}
                              onChange={e => updateRole(u.id, e.target.value)}
                              disabled={saving === u.id}
                            >
                              {Object.entries(ROLE_LABELS).map(([val, label]) => (
                                <option key={val} value={val}>{label}</option>
                              ))}
                            </select>
                            {saving === u.id && <Loader2 className="w-3 h-3 animate-spin absolute -left-5 top-1/2 -translate-y-1/2 text-blue-600" />}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">{u._count.properties}</td>
                        <td className="px-4 py-3 text-center">{u._count.craftsmen}</td>
                        <td className="px-4 py-3 text-center text-gray-400 text-xs">
                          {new Date(u.createdAt).toLocaleDateString('ar-MA')}
                        </td>
                        <td className="px-4 py-3 text-center">
                          <button
                            onClick={() => deleteUser(u.id)}
                            disabled={deleting === u.id}
                            className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
                          >
                            {deleting === u.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
