'use client'

import { useState, useEffect, useRef, useCallback } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useSession } from 'next-auth/react'
import {
  Plus, ArrowLeft, Layout, Eye, Trash2, Edit3, Save, X,
  Loader2, AlertTriangle, Check, MapPin, Users, Shield,
} from 'lucide-react'
import { Button } from '@/components/ui/button'

type Hotspot = {
  id: string; title: string; description: string; price: string; area: string
  x: number; y: number; polygon: string
}

type VisionMapData = {
  id: string; title: string; description: string | null; buildingImage: string
  propertyId: string | null; hotspots: Hotspot[]; isActive: boolean; viewCount: number
  createdAt: string; agentId: string
  property?: { id: string; title: string; city: string; images: string[] } | null
  agent?: { id: string; name: string; email: string; role?: string } | null
}

type AgentStat = { id: string; name: string; email: string; role: string; plan: string; quota: number; used: number }

const PLAN_LABELS: Record<string, string> = {
  FREE: 'مجانية', BRONZE: 'برونزية', GOLD: 'ذهبية', PLATINUM: 'بلاتينيوم',
}
const PLAN_COLORS: Record<string, string> = {
  FREE: 'bg-gray-100 text-gray-600', BRONZE: 'bg-amber-100 text-amber-700',
  GOLD: 'bg-yellow-100 text-yellow-700', PLATINUM: 'bg-purple-100 text-purple-700',
}

function createEmptyHotspot(): Hotspot {
  return { id: `h-${Date.now()}`, title: '', description: '', price: '', area: '', x: 50, y: 50, polygon: '40,40 60,40 60,60 40,60' }
}

export default function VisionDashboardPage() {
  const { data: session } = useSession()
  const isAdmin = (session?.user as any)?.role === 'ADMIN'

  const [maps, setMaps] = useState<VisionMapData[]>([])
  const [agentStats, setAgentStats] = useState<AgentStat[]>([])
  const [loading, setLoading] = useState(true)
  const [plan, setPlan] = useState('FREE')
  const [quota, setQuota] = useState(0)
  const [used, setUsed] = useState(0)

  const [showCreate, setShowCreate] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null)

  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [buildingImage, setBuildingImage] = useState('')
  const [propertyId, setPropertyId] = useState('')
  const [hotspots, setHotspots] = useState<Hotspot[]>([])
  const [activeHotspot, setActiveHotspot] = useState<number | null>(null)
  const [targetAgentId, setTargetAgentId] = useState('')

  const [view, setView] = useState<'maps' | 'agents'>('maps')
  const [agentSearch, setAgentSearch] = useState('')

  const imageRef = useRef<HTMLDivElement>(null)

  const loadMaps = useCallback(async () => {
    try {
      if (isAdmin) {
        const res = await fetch('/api/vision?all=true')
        const data = await res.json()
        setMaps(data.maps ?? [])
        setAgentStats(data.agentStats ?? [])
      } else {
        const res = await fetch('/api/vision')
        const data = await res.json()
        setMaps(data.maps ?? [])
        setPlan(data.plan ?? 'FREE')
        setQuota(data.quota ?? 0)
        setUsed(data.used ?? 0)
      }
    } catch {}
    finally { setLoading(false) }
  }, [isAdmin])

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

  const resetForm = () => {
    setTitle(''); setDescription(''); setBuildingImage(''); setPropertyId('')
    setHotspots([]); setActiveHotspot(null); setEditingId(null); setError(''); setTargetAgentId('')
  }

  const startEdit = (map: VisionMapData) => {
    setEditingId(map.id)
    setTitle(map.title)
    setDescription(map.description ?? '')
    setBuildingImage(map.buildingImage)
    setPropertyId(map.propertyId ?? '')
    setHotspots(Array.isArray(map.hotspots) ? map.hotspots : [])
    setActiveHotspot(null)
    setTargetAgentId(isAdmin ? map.agentId : '')
    setShowCreate(true)
  }

  const handleImageClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!imageRef.current) return
    const rect = imageRef.current.getBoundingClientRect()
    const x = ((e.clientX - rect.left) / rect.width) * 100
    const y = ((e.clientY - rect.top) / rect.height) * 100
    const newHotspot = createEmptyHotspot()
    newHotspot.x = Math.round(x * 10) / 10
    newHotspot.y = Math.round(y * 10) / 10
    newHotspot.polygon = `${x-10},${y-10} ${x+10},${y-10} ${x+10},${y+10} ${x-10},${y+10}`
    setHotspots(prev => [...prev, newHotspot])
    setActiveHotspot(hotspots.length)
  }

  const updateHotspot = (index: number, field: keyof Hotspot, value: string | number) => {
    setHotspots(prev => prev.map((h, i) => i === index ? { ...h, [field]: value } : h))
  }

  const removeHotspot = (index: number) => {
    setHotspots(prev => prev.filter((_, i) => i !== index))
    setActiveHotspot(null)
  }

  const handleSave = async () => {
    if (!title.trim()) return setError('العنوان مطلوب')
    if (!buildingImage.trim()) return setError('رابط صورة المبنى مطلوب')
    setSaving(true)
    setError('')

    try {
      const url = editingId ? `/api/vision/${editingId}` : '/api/vision'
      const method = editingId ? 'PATCH' : 'POST'
      const body: any = { title: title.trim(), description: description.trim() || null, buildingImage: buildingImage.trim(), propertyId: propertyId.trim() || null, hotspots }
      if (isAdmin && targetAgentId) body.agentId = targetAgentId

      const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
      const data = await res.json()
      if (!res.ok) return setError(data.error || 'خطأ في الحفظ')

      setSuccess(editingId ? 'تم التحديث بنجاح' : 'تم الإنشاء بنجاح')
      setTimeout(() => setSuccess(''), 3000)
      resetForm()
      setShowCreate(false)
      loadMaps()
    } catch {
      setError('خطأ في الاتصال')
    } finally { setSaving(false) }
  }

  const handleDelete = async (id: string) => {
    try {
      await fetch(`/api/vision/${id}`, { method: 'DELETE' })
      setMaps(prev => prev.filter(m => m.id !== id))
      if (!isAdmin) setUsed(prev => prev - 1)
      setConfirmDelete(null)
    } catch {}
  }

  const filteredAgents = agentStats.filter(a =>
    !agentSearch || a.name?.toLowerCase().includes(agentSearch.toLowerCase()) || a.email?.toLowerCase().includes(agentSearch.toLowerCase())
  )

  const totalMaps = isAdmin ? maps.length : used
  const displayQuota = isAdmin ? '∞' : quota === Infinity ? '∞' : quota

  return (
    <div className="min-h-screen bg-gray-50 py-8" dir="rtl">
      <div className="container mx-auto px-4 max-w-6xl">

        {/* Header */}
        <div className="flex justify-between items-center 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">
                <Layout className="w-6 h-6 text-blue-600" /> أداة Vision التفاعلية
                {isAdmin && <span className="text-xs bg-red-100 text-red-700 px-2 py-0.5 rounded-full font-medium">مدير</span>}
              </h1>
              <p className="text-gray-500 text-sm">
                {isAdmin ? 'إدارة جميع خرائط Vision لجميع المستخدمين' : 'إنشاء وإدارة خرائط الصور التفاعلية لعقاراتك'}
              </p>
            </div>
          </div>
          <div className="flex gap-3">
            {isAdmin && (
              <div className="flex bg-gray-100 rounded-xl p-1">
                <button onClick={() => setView('maps')}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${view === 'maps' ? 'bg-white shadow-sm text-blue-600' : 'text-gray-500'}`}>
                  <Layout className="w-4 h-4 inline ml-1" />الخرائط
                </button>
                <button onClick={() => setView('agents')}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${view === 'agents' ? 'bg-white shadow-sm text-blue-600' : 'text-gray-500'}`}>
                  <Users className="w-4 h-4 inline ml-1" />الحسابات
                </button>
              </div>
            )}
            <Button onClick={() => { resetForm(); setShowCreate(true) }} className="gap-2">
              <Plus className="w-4 h-4" /> {isAdmin ? 'إنشاء خريطة' : 'إنشاء خريطة جديدة'}
            </Button>
          </div>
        </div>

        {/* Quota / Stats Bar */}
        <div className="bg-white rounded-2xl border shadow-sm p-5 mb-6">
          {isAdmin ? (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="bg-blue-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-blue-600">{agentStats.length}</div>
                <div className="text-xs text-gray-500 mt-1">مستخدم نشط</div>
              </div>
              <div className="bg-green-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-green-600">{maps.length}</div>
                <div className="text-xs text-gray-500 mt-1">إجمالي الخرائط</div>
              </div>
              <div className="bg-purple-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-purple-600">{agentStats.filter(a => a.plan !== 'FREE').length}</div>
                <div className="text-xs text-gray-500 mt-1">حسابات مدفوعة</div>
              </div>
              <div className="bg-amber-50 rounded-xl p-4 text-center">
                <div className="text-2xl font-bold text-amber-600">{agentStats.filter(a => a.quota !== 0 && a.used >= a.quota).length}</div>
                <div className="text-xs text-gray-500 mt-1">وصلوا الحد الأقصى</div>
              </div>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-3">
                  <span className={`text-xs px-3 py-1 rounded-full font-bold ${PLAN_COLORS[plan]}`}>
                    الباقة {PLAN_LABELS[plan]}
                  </span>
                  <span className="text-sm text-gray-500">
                    {used} / {quota === Infinity ? '∞' : quota} خريطة Vision
                  </span>
                </div>
                {plan === 'FREE' && (
                  <Link href="/#pricing" className="text-sm text-blue-600 hover:underline font-medium">ترقية الباقة</Link>
                )}
              </div>
              {quota !== Infinity && (
                <div className="w-full bg-gray-100 rounded-full h-2">
                  <div className={`h-2 rounded-full transition-all ${(used / quota * 100) >= 90 ? 'bg-red-500' : (used / quota * 100) >= 70 ? 'bg-amber-500' : 'bg-blue-600'}`}
                    style={{ width: `${Math.min((used / quota) * 100, 100)}%` }} />
                </div>
              )}
            </>
          )}
        </div>

        {/* Success / Error */}
        {success && (
          <div className="bg-green-50 border border-green-200 text-green-700 text-sm rounded-xl px-4 py-3 mb-4 flex items-center gap-2">
            <Check className="w-4 h-4 shrink-0" />{success}
          </div>
        )}

        {/* Create/Edit Form */}
        {showCreate && (
          <div className="bg-white rounded-2xl border shadow-sm p-6 mb-6">
            <div className="flex justify-between items-center mb-5">
              <h2 className="text-lg font-bold">{editingId ? 'تعديل خريطة Vision' : 'إنشاء خريطة Vision جديدة'}</h2>
              <button onClick={() => { setShowCreate(false); resetForm() }} className="text-gray-400 hover:text-gray-600"><X className="w-5 h-5" /></button>
            </div>

            {error && (
              <div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-xl px-4 py-3 mb-4 flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 shrink-0" />{error}
              </div>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-5">
              {isAdmin && (
                <div>
                  <label className="block text-sm font-medium mb-1.5 text-gray-700">المستخدم (الوكيل)</label>
                  <select value={targetAgentId} onChange={e => setTargetAgentId(e.target.value)}
                    className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">— اختر وكيل —</option>
                    {agentStats.map(a => (
                      <option key={a.id} value={a.id}>{a.name || a.email} ({PLAN_LABELS[a.plan] ?? a.plan})</option>
                    ))}
                  </select>
                </div>
              )}
              <div>
                <label className="block text-sm font-medium mb-1.5 text-gray-700">عنوان الخريطة *</label>
                <input value={title} onChange={e => setTitle(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="مثال: مبنى الواحة السكني - واجهة أمامية" />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1.5 text-gray-700">رابط صورة المبنى *</label>
                <input value={buildingImage} onChange={e => setBuildingImage(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="https://example.com/building.jpg" dir="ltr" />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium mb-1.5 text-gray-700">وصف اختياري</label>
                <textarea value={description} onChange={e => setDescription(e.target.value)}
                  className="w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 h-20 resize-none"
                  placeholder="وصف مختصر للمبنى..." />
              </div>
            </div>

            {buildingImage && (
              <div className="mb-5">
                <label className="block text-sm font-medium mb-2 text-gray-700">انقر على الصورة لإضافة نقاط تفاعلية</label>
                <div ref={imageRef} onClick={handleImageClick}
                  className="relative w-full aspect-[16/10] rounded-xl overflow-hidden bg-gray-100 border-2 border-dashed border-gray-300 cursor-crosshair">
                  <Image src={buildingImage} alt="Building" fill className="object-cover" sizes="800px" />
                  <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 w-full h-full" style={{ zIndex: 10 }}>
                    {hotspots.map((h, i) => {
                      const isActive = activeHotspot === i
                      return (
                        <g key={h.id} className="cursor-pointer" onClick={e => { e.stopPropagation(); setActiveHotspot(i) }}>
                          <polygon points={h.polygon}
                            fill={isActive ? 'rgba(37,99,235,0.35)' : 'rgba(37,99,235,0.08)'}
                            stroke={isActive ? '#2563eb' : 'rgba(37,99,235,0.4)'}
                            strokeWidth={isActive ? '0.8' : '0.4'} className="transition-all" />
                          <circle cx={h.x} cy={h.y} r={isActive ? '3' : '2'} fill="#2563eb" stroke="white" strokeWidth="0.8" />
                          <text x={h.x} y={h.y - 4} textAnchor="middle" fill="#1e40af" fontSize="2.5" fontWeight="bold">{i + 1}</text>
                        </g>
                      )
                    })}
                  </svg>
                </div>
                <p className="text-xs text-gray-400 mt-1">انقر في أي مكان على الصورة لإضافة نقطة تفاعلية</p>
              </div>
            )}

            {hotspots.length > 0 && (
              <div className="mb-5 space-y-3">
                <h3 className="text-sm font-bold text-gray-700">النقاط التفاعلية ({hotspots.length})</h3>
                {hotspots.map((h, i) => (
                  <div key={h.id} className={`border rounded-xl p-4 transition-all ${activeHotspot === i ? 'border-blue-400 bg-blue-50' : 'border-gray-200'}`}>
                    <div className="flex items-center justify-between mb-3">
                      <span className="text-xs font-bold text-blue-600">النقطة {i + 1}</span>
                      <div className="flex gap-2">
                        <button onClick={() => setActiveHotspot(activeHotspot === i ? null : i)}
                          className="text-xs text-gray-500 hover:text-blue-600">{activeHotspot === i ? 'طي' : 'تعديل'}</button>
                        <button onClick={() => removeHotspot(i)} className="text-xs text-red-500 hover:text-red-700">حذف</button>
                      </div>
                    </div>
                    {activeHotspot === i && (
                      <div className="grid grid-cols-2 gap-3">
                        <input value={h.title} onChange={e => updateHotspot(i, 'title', e.target.value)}
                          placeholder="عنوان الوحدة" className="px-3 py-2 border rounded-lg text-sm" />
                        <input value={h.price} onChange={e => updateHotspot(i, 'price', e.target.value)}
                          placeholder="السعر" className="px-3 py-2 border rounded-lg text-sm" />
                        <input value={h.area} onChange={e => updateHotspot(i, 'area', e.target.value)}
                          placeholder="المساحة" className="px-3 py-2 border rounded-lg text-sm" />
                        <input value={h.description} onChange={e => updateHotspot(i, 'description', e.target.value)}
                          placeholder="وصف مختصر" className="px-3 py-2 border rounded-lg text-sm" />
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}

            <div className="flex gap-3">
              <Button onClick={handleSave} disabled={saving} className="gap-2">
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                {editingId ? 'حفظ التعديلات' : 'إنشاء الخريطة'}
              </Button>
              <Button variant="outline" onClick={() => { setShowCreate(false); resetForm() }}>إلغاء</Button>
            </div>
          </div>
        )}

        {/* Admin: Agents View */}
        {isAdmin && view === 'agents' && (
          <div className="bg-white rounded-2xl border shadow-sm overflow-hidden">
            <div className="p-4 border-b flex gap-3">
              <input value={agentSearch} onChange={e => setAgentSearch(e.target.value)}
                placeholder="بحث عن وكيل..." className="flex-1 px-4 py-2 border rounded-xl text-sm" />
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 border-b">
                  <tr className="text-right text-gray-500 text-xs font-medium">
                    <th className="px-5 py-3">الوكيل</th>
                    <th className="px-5 py-3">الباقة</th>
                    <th className="px-5 py-3">الخرائط</th>
                    <th className="px-5 py-3">الحصة</th>
                    <th className="px-5 py-3">الاستخدام</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                  {filteredAgents.map(a => (
                    <tr key={a.id} className="hover:bg-gray-50">
                      <td className="px-5 py-3">
                        <p className="font-medium">{a.name || 'بدون اسم'}</p>
                        <p className="text-xs text-gray-400">{a.email}</p>
                      </td>
                      <td className="px-5 py-3">
                        <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${PLAN_COLORS[a.plan]}`}>
                          {PLAN_LABELS[a.plan]}
                        </span>
                      </td>
                      <td className="px-5 py-3 font-bold">{a.used}</td>
                      <td className="px-5 py-3">{a.quota === Infinity ? '∞' : a.quota}</td>
                      <td className="px-5 py-3">
                        <div className="w-24 bg-gray-100 rounded-full h-2">
                          <div className={`h-2 rounded-full ${a.quota === 0 ? 'bg-gray-300' : (a.used / a.quota * 100) >= 90 ? 'bg-red-500' : 'bg-blue-600'}`}
                            style={{ width: a.quota === 0 ? '100%' : `${Math.min((a.used / a.quota) * 100, 100)}%` }} />
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Maps List */}
        {(isAdmin ? view === 'maps' : true) && (
          loading ? (
            <div className="space-y-4">
              {[1,2,3].map(i => <div key={i} className="bg-white rounded-2xl border p-6 animate-pulse"><div className="h-40 bg-gray-100 rounded-xl" /></div>)}
            </div>
          ) : maps.length === 0 ? (
            <div className="bg-white rounded-2xl border p-16 text-center text-gray-400">
              <Layout className="w-14 h-14 mx-auto mb-4 opacity-30" />
              <p className="text-lg font-medium mb-2">لا توجد خرائط Vision بعد</p>
              <Button size="sm" onClick={() => { resetForm(); setShowCreate(true) }} className="gap-2 mt-4">
                <Plus className="w-4 h-4" /> إنشاء أول خريطة
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              {maps.map(m => (
                <div key={m.id} className="bg-white rounded-2xl border shadow-sm overflow-hidden">
                  <div className="flex flex-col md:flex-row">
                    <div className="relative w-full md:w-64 h-48 md:h-auto bg-gray-100 shrink-0">
                      <Image src={m.buildingImage} alt={m.title} fill className="object-cover" sizes="256px" />
                      <div className="absolute top-2 right-2 bg-black/60 text-white text-xs px-2 py-1 rounded-full">
                        {(Array.isArray(m.hotspots) ? m.hotspots.length : 0)} نقطة
                      </div>
                      {!m.isActive && (
                        <div className="absolute top-2 left-2 bg-red-500 text-white text-xs px-2 py-1 rounded-full">معطل</div>
                      )}
                    </div>
                    <div className="flex-1 p-5">
                      <div className="flex items-start justify-between mb-2">
                        <div>
                          <h3 className="font-bold text-lg">{m.title}</h3>
                          {m.description && <p className="text-sm text-gray-500 mt-1">{m.description}</p>}
                        </div>
                        <div className={`w-3 h-3 rounded-full shrink-0 mt-2 ${m.isActive ? 'bg-green-500' : 'bg-gray-300'}`} />
                      </div>
                      {isAdmin && m.agent && (
                        <p className="text-xs text-gray-500 mb-1">
                          <Shield className="w-3 h-3 inline ml-1" />
                          الوكيل: {m.agent.name || m.agent.email}
                        </p>
                      )}
                      {m.property && (
                        <p className="text-xs text-blue-600 mb-2">
                          <MapPin className="w-3 h-3 inline ml-1" />
                          مرتبط بـ: {m.property.title} — {m.property.city}
                        </p>
                      )}
                      <div className="flex items-center gap-4 text-xs text-gray-400 mt-3">
                        <span><Eye className="w-3.5 h-3.5 inline ml-1" />{m.viewCount} مشاهدة</span>
                        <span>{new Date(m.createdAt).toLocaleDateString('ar-MA')}</span>
                      </div>
                      <div className="flex gap-2 mt-4">
                        <Button size="sm" variant="outline" onClick={() => startEdit(m)} className="gap-1.5">
                          <Edit3 className="w-3.5 h-3.5" /> تعديل
                        </Button>
                        <Button size="sm" variant="ghost" onClick={() => setConfirmDelete(m.id)} className="gap-1.5 text-red-500">
                          <Trash2 className="w-3.5 h-3.5" /> حذف
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )
        )}

        {/* Delete Confirm */}
        {confirmDelete && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-2xl p-6 max-w-sm w-full shadow-2xl">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
                  <AlertTriangle className="w-6 h-6 text-red-500" />
                </div>
                <div>
                  <h3 className="font-bold text-lg">حذف خريطة Vision</h3>
                  <p className="text-gray-500 text-sm">لا يمكن التراجع عن هذا الإجراء</p>
                </div>
              </div>
              <div className="flex gap-3 mt-6">
                <Button variant="outline" className="flex-1" onClick={() => setConfirmDelete(null)}>إلغاء</Button>
                <Button variant="destructive" className="flex-1 bg-red-500 hover:bg-red-600"
                  onClick={() => confirmDelete && handleDelete(confirmDelete)}>حذف</Button>
              </div>
            </div>
          </div>
        )}

      </div>
    </div>
  )
}
