'use client'

import { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
import { Plus, ArrowLeft, Wrench, Trash2, Edit3, Loader2, Check, X, Search, MapPin, Star } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'

export default function CraftsmanDashboard() {
  const [craftsmen, setCraftsmen] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')

  const load = useCallback(async () => {
    try {
      const res = await fetch('/api/craftsmen?limit=100')
      const data = await res.json()
      setCraftsmen(data.craftsmen ?? [])
    } catch {}
    finally { setLoading(false) }
  }, [])

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

  const toggleVerify = async (id: string, verified: boolean) => {
    await fetch(`/api/craftsmen/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ isVerified: !verified }),
    })
    load()
  }

  const deleteCraftsman = async (id: string) => {
    if (!confirm('تأكيد حذف هذا الحرفي؟')) return
    await fetch(`/api/craftsmen/${id}`, { method: 'DELETE' })
    load()
  }

  const filtered = craftsmen.filter(c =>
    !search || c.name.includes(search) || c.profession.includes(search) || c.city.includes(search)
  )

  return (
    <div className="min-h-screen bg-gray-50 py-8" dir="rtl">
      <div className="container mx-auto px-4 max-w-6xl">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <Link href="/dashboard" className="text-gray-400 hover:text-gray-600"><ArrowLeft className="w-5 h-5 rotate-180" /></Link>
            <div>
              <h1 className="text-2xl font-bold flex items-center gap-2"><Wrench className="w-6 h-6 text-blue-600" />إدارة الحرفيين</h1>
              <p className="text-gray-500 text-sm">{craftsmen.length} حرفي مسجل</p>
            </div>
          </div>
          <Button asChild size="sm" className="gap-2">
            <Link href="/dashboard/craftsmen/new"><Plus className="w-4 h-4" />إضافة حرفي</Link>
          </Button>
        </div>

        <div className="bg-white rounded-2xl border shadow-sm overflow-hidden">
          <div className="p-4 border-b">
            <div className="relative max-w-xs">
              <Search className="absolute right-3 top-2.5 w-4 h-4 text-gray-400" />
              <input value={search} onChange={e => setSearch(e.target.value)}
                placeholder="بحث عن حرفي..."
                className="w-full pr-9 pl-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
            </div>
          </div>

          {loading ? (
            <div className="p-12 text-center"><Loader2 className="w-8 h-8 animate-spin mx-auto text-blue-400" /></div>
          ) : filtered.length === 0 ? (
            <div className="p-12 text-center text-gray-400">
              <Wrench className="w-12 h-12 mx-auto mb-3 opacity-20" />
              <p>لا يوجد حرفيون</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 text-gray-600">
                  <tr>
                    <th className="text-right p-4 font-medium">الاسم</th>
                    <th className="text-right p-4 font-medium">التخصص</th>
                    <th className="text-right p-4 font-medium">المدينة</th>
                    <th className="text-center p-4 font-medium">التقييم</th>
                    <th className="text-center p-4 font-medium">الحالة</th>
                    <th className="text-center p-4 font-medium">إجراءات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {filtered.map(c => (
                    <tr key={c.id} className="hover:bg-gray-50">
                      <td className="p-4 font-medium">{c.name}</td>
                      <td className="p-4 text-gray-600">{c.profession}</td>
                      <td className="p-4 text-gray-500">{c.city}</td>
                      <td className="p-4 text-center">
                        <span className="inline-flex items-center gap-1 text-amber-600 text-xs font-medium">
                          <Star className="w-3.5 h-3.5 fill-amber-400" />{c.rating.toFixed(1)}
                        </span>
                      </td>
                      <td className="p-4 text-center">
                        <Badge className={c.isVerified ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}>
                          {c.isVerified ? 'موثق' : 'قيد المراجعة'}
                        </Badge>
                      </td>
                      <td className="p-4">
                        <div className="flex items-center justify-center gap-2">
                          <button onClick={() => toggleVerify(c.id, c.isVerified)}
                            className={`p-1.5 rounded-lg transition-colors ${c.isVerified ? 'text-yellow-600 hover:bg-yellow-50' : 'text-green-600 hover:bg-green-50'}`}
                            title={c.isVerified ? 'إلغاء التوثيق' : 'توثيق'}>
                            {c.isVerified ? <X className="w-4 h-4" /> : <Check className="w-4 h-4" />}
                          </button>
                          <Link href={`/dashboard/craftsmen/${c.id}`}
                            className="p-1.5 rounded-lg text-blue-600 hover:bg-blue-50 transition-colors" title="تعديل">
                            <Edit3 className="w-4 h-4" />
                          </Link>
                          <button onClick={() => deleteCraftsman(c.id)}
                            className="p-1.5 rounded-lg text-red-500 hover:bg-red-50 transition-colors" title="حذف">
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}