'use client'

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

type Scene = {
  id: string; name: string; panoramaUrl: string; thumbnailUrl: string; hotspots: any[]; infoTags: any[]
}

type TourData = {
  id: string; scenes: Scene[]; createdAt: string; updatedAt: string
  property?: { id: string; title: string; city: string; images: string[] } | null
  creator?: { id: string; name: string; email: string } | null
}

type Property = { id: string; title: string; city: string; images: string[] }

type CreatorStat = { 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 createEmptyScene(): Scene {
  return { id: `s-${Date.now()}`, name: '', panoramaUrl: '', thumbnailUrl: '', hotspots: [], infoTags: [] }
}

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

  const [tours, setTours] = useState<TourData[]>([])
  const [creatorStats, setCreatorStats] = useState<CreatorStat[]>([])
  const [properties, setProperties] = useState<Property[]>([])
  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 [selectedPropertyId, setSelectedPropertyId] = useState('')
  const [scenes, setScenes] = useState<Scene[]>([])
  const [expandedScene, setExpandedScene] = useState<number | null>(0)
  const [targetUserId, setTargetUserId] = useState('')

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

  const loadTours = useCallback(async () => {
    try {
      if (isAdmin) {
        const [toursRes, propsRes] = await Promise.all([
          fetch('/api/virtual-tours?all=true'),
          fetch('/api/properties?limit=500'),
        ])
        const toursData = await toursRes.json()
        const propsData = await propsRes.json()
        setTours(toursData.tours ?? [])
        setCreatorStats(toursData.creatorStats ?? [])
        setProperties(propsData.properties ?? [])
      } else {
        const [toursRes, propsRes] = await Promise.all([
          fetch('/api/virtual-tours'),
          fetch('/api/properties?limit=500'),
        ])
        const toursData = await toursRes.json()
        const propsData = await propsRes.json()
        setTours(toursData.tours ?? [])
        setPlan(toursData.plan ?? 'FREE')
        setQuota(toursData.quota ?? 0)
        setUsed(toursData.used ?? 0)
        setProperties(propsData.properties ?? [])
      }
    } catch {}
    finally { setLoading(false) }
  }, [isAdmin])

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

  const resetForm = () => {
    setSelectedPropertyId(''); setScenes([]); setExpandedScene(0)
    setEditingId(null); setError(''); setTargetUserId('')
  }

  const startEdit = (tour: TourData) => {
    setEditingId(tour.id)
    setSelectedPropertyId(tour.property?.id ?? '')
    setScenes(Array.isArray(tour.scenes) ? tour.scenes : [])
    setExpandedScene(0)
    setTargetUserId(isAdmin ? tour.creator?.id ?? '' : '')
    setShowCreate(true)
  }

  const addScene = () => {
    setScenes(prev => [...prev, createEmptyScene()])
    setExpandedScene(scenes.length)
  }

  const updateScene = (index: number, field: keyof Scene, value: any) => {
    setScenes(prev => prev.map((s, i) => i === index ? { ...s, [field]: value } : s))
  }

  const removeScene = (index: number) => {
    setScenes(prev => prev.filter((_, i) => i !== index))
    setExpandedScene(null)
  }

  const addHotspot = (sceneIndex: number) => {
    const newHotspot = { id: `h-${Date.now()}`, pitch: 0, yaw: 0, text: '', url: '' }
    setScenes(prev => prev.map((s, i) => i === sceneIndex ? { ...s, hotspots: [...s.hotspots, newHotspot] } : s))
  }

  const updateHotspot = (sceneIndex: number, hIndex: number, field: string, value: any) => {
    setScenes(prev => prev.map((s, i) => {
      if (i !== sceneIndex) return s
      return { ...s, hotspots: s.hotspots.map((h, j) => j === hIndex ? { ...h, [field]: value } : h) }
    }))
  }

  const removeHotspot = (sceneIndex: number, hIndex: number) => {
    setScenes(prev => prev.map((s, i) => {
      if (i !== sceneIndex) return s
      return { ...s, hotspots: s.hotspots.filter((_, j) => j !== hIndex) }
    }))
  }

  const handleSave = async () => {
    if (!selectedPropertyId) return setError('اختر العقار')
    if (scenes.length === 0) return setError('أضف مشهداً واحداً على الأقل')
    const hasEmpty = scenes.some(s => !s.name.trim() || !s.panoramaUrl.trim())
    if (hasEmpty) return setError('كل مشهد يجب أن يكون له اسم ورابط صورة بانورامية')
    setSaving(true)
    setError('')

    try {
      const url = editingId ? `/api/virtual-tours/${editingId}` : '/api/virtual-tours'
      const method = editingId ? 'PATCH' : 'POST'
      const body: any = { propertyId: selectedPropertyId, scenes }
      if (isAdmin && targetUserId) body.createdBy = targetUserId

      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)
      loadTours()
    } catch {
      setError('خطأ في الاتصال')
    } finally { setSaving(false) }
  }

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

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

  const totalTours = isAdmin ? tours.length : used
  const displayQuota = isAdmin ? '∞' : quota === Infinity ? '∞' : quota

  const usedPropertyIds = tours.map(t => t.property?.id).filter(Boolean)

  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">
                <Globe className="w-6 h-6 text-blue-600" /> جولات 360° الافتراضية
                {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 ? 'إدارة جميع الجولات الافتراضية لجميع المستخدمين' : 'إنشاء وإدارة جولات افتراضية 360° لعقاراتك'}
              </p>
            </div>
          </div>
          <div className="flex gap-3">
            {isAdmin && (
              <div className="flex bg-gray-100 rounded-xl p-1">
                <button onClick={() => setView('tours')}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${view === 'tours' ? 'bg-white shadow-sm text-blue-600' : 'text-gray-500'}`}>
                  <Globe 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" /> إنشاء جولة جديدة
            </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">{creatorStats.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">{tours.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">{creatorStats.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">{tours.reduce((acc, t) => acc + (Array.isArray(t.scenes) ? t.scenes.length : 0), 0)}</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} جولة افتراضية
                  </span>
                </div>
                {plan === 'FREE' && (
                  <Link href="/#pricing" className="text-sm text-blue-600 hover:underline font-medium">ترقية الباقة</Link>
                )}
              </div>
              {quota !== Infinity && quota > 0 && (
                <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>
              )}
              {quota === 0 && (
                <p className="text-sm text-amber-600 mt-2">جولات 360° غير متاحة في باقتك الحالية. قم بالترقية.</p>
              )}
            </>
          )}
        </div>

        {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 ? 'تعديل الجولة' : 'إنشاء جولة افتراضية جديدة'}</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={targetUserId} onChange={e => setTargetUserId(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>
                    {creatorStats.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>
                <select value={selectedPropertyId} onChange={e => setSelectedPropertyId(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>
                  {properties.map(p => (
                    <option key={p.id} value={p.id} disabled={usedPropertyIds.includes(p.id) && p.id !== selectedPropertyId}>
                      {p.title} — {p.city}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Scenes */}
            <div className="mb-5">
              <div className="flex justify-between items-center mb-3">
                <h3 className="text-sm font-bold text-gray-700">المشاهد ({scenes.length})</h3>
                <Button size="sm" variant="outline" onClick={addScene} className="gap-1.5">
                  <Plus className="w-3.5 h-3.5" /> إضافة مشهد
                </Button>
              </div>

              {scenes.length === 0 && (
                <div className="border-2 border-dashed border-gray-200 rounded-xl p-8 text-center text-gray-400">
                  <Camera className="w-10 h-10 mx-auto mb-3 opacity-30" />
                  <p className="text-sm">أضف مشهداً بانورامياً 360°</p>
                </div>
              )}

              <div className="space-y-3">
                {scenes.map((scene, si) => (
                  <div key={scene.id} className="border rounded-xl overflow-hidden">
                    <button onClick={() => setExpandedScene(expandedScene === si ? null : si)}
                      className="w-full flex items-center justify-between p-4 hover:bg-gray-50 transition-colors text-right">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center text-blue-600 text-sm font-bold">{si + 1}</div>
                        <div>
                          <p className="font-medium text-sm">{scene.name || `مشهد ${si + 1}`}</p>
                          <p className="text-xs text-gray-400 truncate max-w-xs">{scene.panoramaUrl || 'بدون رابط'}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-gray-400">{scene.hotspots.length} نقطة</span>
                        {expandedScene === si ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                      </div>
                    </button>

                    {expandedScene === si && (
                      <div className="p-4 border-t bg-gray-50 space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                          <div>
                            <label className="block text-xs font-medium mb-1 text-gray-600">اسم المشهد *</label>
                            <input value={scene.name} onChange={e => updateScene(si, 'name', e.target.value)}
                              className="w-full px-3 py-2 border rounded-lg text-sm" placeholder="مثال: الصالون الرئيسي" />
                          </div>
                          <div className="flex items-end gap-2">
                            <div className="flex-1">
                              <label className="block text-xs font-medium mb-1 text-gray-600">رابط الصورة البانورامية *</label>
                              <input value={scene.panoramaUrl} onChange={e => updateScene(si, 'panoramaUrl', e.target.value)}
                                className="w-full px-3 py-2 border rounded-lg text-sm" placeholder="https://..." dir="ltr" />
                            </div>
                            <Button size="sm" variant="ghost" onClick={() => removeScene(si)} className="text-red-500 shrink-0">حذف</Button>
                          </div>
                          <div>
                            <label className="block text-xs font-medium mb-1 text-gray-600">رابط الصورة المصغرة</label>
                            <input value={scene.thumbnailUrl} onChange={e => updateScene(si, 'thumbnailUrl', e.target.value)}
                              className="w-full px-3 py-2 border rounded-lg text-sm" placeholder="https://..." dir="ltr" />
                          </div>
                        </div>

                        {/* Panorama Preview */}
                        {scene.panoramaUrl && (
                          <div className="relative w-full h-40 rounded-lg overflow-hidden bg-gray-200">
                            <Image src={scene.panoramaUrl} alt={scene.name} fill className="object-cover" sizes="800px" />
                            <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                              <span className="bg-white/90 text-xs px-3 py-1.5 rounded-full font-medium">معاينة بانوراما</span>
                            </div>
                          </div>
                        )}

                        {/* Hotspots */}
                        <div>
                          <div className="flex justify-between items-center mb-2">
                            <span className="text-xs font-medium text-gray-600">النقاط التفاعلية ({scene.hotspots.length})</span>
                            <Button size="sm" variant="ghost" onClick={() => addHotspot(si)} className="gap-1 text-xs h-7">
                              <Plus className="w-3 h-3" /> إضافة نقطة
                            </Button>
                          </div>
                          {scene.hotspots.map((h, hi) => (
                            <div key={h.id} className="flex gap-2 mb-2 items-center">
                              <input value={h.text} onChange={e => updateHotspot(si, hi, 'text', e.target.value)}
                                placeholder="نص النقطة" className="flex-1 px-3 py-1.5 border rounded-lg text-xs" />
                              <input type="number" value={h.pitch} onChange={e => updateHotspot(si, hi, 'pitch', parseFloat(e.target.value) || 0)}
                                placeholder="pitch" className="w-20 px-2 py-1.5 border rounded-lg text-xs" dir="ltr" />
                              <input type="number" value={h.yaw} onChange={e => updateHotspot(si, hi, 'yaw', parseFloat(e.target.value) || 0)}
                                placeholder="yaw" className="w-20 px-2 py-1.5 border rounded-lg text-xs" dir="ltr" />
                              <button onClick={() => removeHotspot(si, hi)} className="text-red-400 hover:text-red-600 text-xs">✕</button>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </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>
        )}

        {/* Tours List */}
        {(isAdmin ? view === 'tours' : 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-32 bg-gray-100 rounded-xl" /></div>)}
            </div>
          ) : tours.length === 0 ? (
            <div className="bg-white rounded-2xl border p-16 text-center text-gray-400">
              <Globe className="w-14 h-14 mx-auto mb-4 opacity-30" />
              <p className="text-lg font-medium mb-2">لا توجد جولات افتراضية بعد</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">
              {tours.map(tour => {
                const sceneCount = Array.isArray(tour.scenes) ? tour.scenes.length : 0
                return (
                  <div key={tour.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">
                        {tour.property?.images?.[0] ? (
                          <Image src={tour.property.images[0]} alt={tour.property.title} fill className="object-cover" sizes="256px" />
                        ) : (
                          <div className="flex items-center justify-center h-full"><Globe className="w-12 h-12 text-gray-300" /></div>
                        )}
                        <div className="absolute top-2 right-2 bg-black/60 text-white text-xs px-2 py-1 rounded-full">
                          {sceneCount} مشهد
                        </div>
                      </div>
                      <div className="flex-1 p-5">
                        <div className="flex items-start justify-between mb-2">
                          <div>
                            <h3 className="font-bold text-lg">{tour.property?.title ?? 'عقار غير معروف'}</h3>
                            <p className="text-sm text-gray-500">{tour.property?.city}</p>
                          </div>
                        </div>
                        {isAdmin && tour.creator && (
                          <p className="text-xs text-gray-500 mb-1">
                            <Shield className="w-3 h-3 inline ml-1" />
                            أنشأها: {tour.creator.name || tour.creator.email}
                          </p>
                        )}
                        <div className="flex flex-wrap gap-2 mt-2">
                          {Array.isArray(tour.scenes) && tour.scenes.map((s, i) => (
                            <span key={s.id || i} className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-full">
                              {s.name || `مشهد ${i + 1}`}
                            </span>
                          ))}
                        </div>
                        <div className="flex items-center gap-4 text-xs text-gray-400 mt-3">
                          <span>{new Date(tour.createdAt).toLocaleDateString('ar-MA')}</span>
                        </div>
                        <div className="flex gap-2 mt-4">
                          <Button size="sm" variant="outline" onClick={() => startEdit(tour)} className="gap-1.5">
                            <Edit3 className="w-3.5 h-3.5" /> تعديل
                          </Button>
                          <Button size="sm" variant="ghost" onClick={() => setConfirmDelete(tour.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">حذف الجولة</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>
  )
}
