'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import {
  Plus, Search, Pencil, Trash2, Eye, Building2,
  Filter, ArrowLeft, Loader2, AlertTriangle
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { PropertiesGridSkeleton } from '@/components/ui/skeleton'

const STATUS_MAP: Record<string, { label: string; color: string }> = {
  AVAILABLE: { label: 'متاح',  color: 'bg-green-100 text-green-700' },
  RESERVED:  { label: 'محجوز', color: 'bg-amber-100 text-amber-700' },
  SOLD:      { label: 'مباع',  color: 'bg-red-100 text-red-700'    },
}

type Property = {
  id: string; title: string; city: string; price: number
  status: string; viewCount: number; images: string[]; type: string; area: number
}

export default function DashboardPropertiesPage() {
  const [properties, setProperties] = useState<Property[]>([])
  const [loading, setLoading]       = useState(true)
  const [search, setSearch]         = useState('')
  const [filter, setFilter]         = useState('')
  const [deleting, setDeleting]     = useState<string | null>(null)
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null)

  useEffect(() => {
    fetch('/api/properties?limit=100')
      .then(r => r.json())
      .then(d => setProperties(d.properties ?? []))
      .finally(() => setLoading(false))
  }, [])

  const displayed = properties.filter(p => {
    const matchSearch = !search || p.title.toLowerCase().includes(search.toLowerCase()) || p.city.includes(search)
    const matchFilter = !filter || p.status === filter
    return matchSearch && matchFilter
  })

  const handleDelete = async (id: string) => {
    setDeleting(id)
    try {
      const res = await fetch(`/api/properties/${id}`, { method: 'DELETE' })
      if (res.ok) {
        setProperties(prev => prev.filter(p => p.id !== id))
      }
    } catch (error) {
      console.error('Delete failed:', error)
    } finally {
      setDeleting(null)
      setConfirmDelete(null)
    }
  }

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

        {/* 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">عقاراتي</h1>
              <p className="text-gray-500 text-sm">{properties.length} عقار مسجل</p>
            </div>
          </div>
          <Button asChild>
            <Link href="/properties/new" className="gap-2">
              <Plus className="w-4 h-4" /> إضافة عقار
            </Link>
          </Button>
        </div>

        {/* Filters */}
        <div className="bg-white rounded-2xl border shadow-sm p-4 mb-6 flex flex-wrap gap-3">
          <div className="relative flex-1 min-w-48">
            <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="بحث في عقاراتي..."
              className="w-full pr-10 pl-4 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div className="flex gap-2">
            {['', 'AVAILABLE', 'RESERVED', 'SOLD'].map(s => (
              <button key={s}
                onClick={() => setFilter(s)}
                className={`px-4 py-2 rounded-xl text-sm font-medium transition-colors border ${
                  filter === s ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                }`}
              >
                {!s ? 'الكل' : STATUS_MAP[s]?.label}
              </button>
            ))}
          </div>
        </div>

        {/* Properties Table */}
        {loading ? (
          <div className="bg-white rounded-2xl border p-6">
            <div className="space-y-4">
              {[1,2,3,4,5].map(i => (
                <div key={i} className="flex gap-4 animate-pulse">
                  <div className="w-20 h-16 bg-gray-200 rounded-xl" />
                  <div className="flex-1 space-y-2 py-1">
                    <div className="h-4 bg-gray-200 rounded w-2/3" />
                    <div className="h-3 bg-gray-200 rounded w-1/3" />
                  </div>
                  <div className="w-24 h-8 bg-gray-200 rounded-lg" />
                </div>
              ))}
            </div>
          </div>
        ) : displayed.length === 0 ? (
          <div className="bg-white rounded-2xl border p-16 text-center text-gray-400">
            <Building2 className="w-14 h-14 mx-auto mb-4 opacity-30" />
            <p className="text-lg font-medium mb-2">لا توجد نتائج</p>
            <p className="text-sm mb-4">{search ? 'جرب كلمة بحث مختلفة' : 'لم تقم بإضافة أي عقار بعد'}</p>
            {!search && (
              <Button asChild size="sm">
                <Link href="/properties/new">إضافة أول عقار</Link>
              </Button>
            )}
          </div>
        ) : (
          <div className="bg-white rounded-2xl border shadow-sm overflow-hidden">
            <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-4">العقار</th>
                    <th className="px-5 py-4">المدينة</th>
                    <th className="px-5 py-4">السعر</th>
                    <th className="px-5 py-4">المساحة</th>
                    <th className="px-5 py-4">الحالة</th>
                    <th className="px-5 py-4">المشاهدات</th>
                    <th className="px-5 py-4">إجراءات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                  {displayed.map(p => {
                    const st = STATUS_MAP[p.status] ?? { label: p.status, color: 'bg-gray-100 text-gray-600' }
                    return (
                      <tr key={p.id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-5 py-4">
                          <div className="flex items-center gap-3">
                            <div className="relative w-16 h-12 rounded-lg overflow-hidden bg-gray-100 shrink-0">
                              {p.images?.[0] && (
                                <Image src={p.images[0]} alt={p.title} fill className="object-cover" sizes="64px" />
                              )}
                            </div>
                            <span className="font-medium text-gray-900 line-clamp-1 max-w-[180px]">{p.title}</span>
                          </div>
                        </td>
                        <td className="px-5 py-4 text-gray-500">{p.city}</td>
                        <td className="px-5 py-4 font-medium text-blue-600">
                          {p.price.toLocaleString('ar-MA')}
                        </td>
                        <td className="px-5 py-4 text-gray-500">{p.area} م²</td>
                        <td className="px-5 py-4">
                          <span className={`px-2.5 py-1 rounded-full text-xs font-medium ${st.color}`}>
                            {st.label}
                          </span>
                        </td>
                        <td className="px-5 py-4 text-gray-500 flex items-center gap-1">
                          <Eye className="w-3.5 h-3.5" /> {p.viewCount ?? 0}
                        </td>
                        <td className="px-5 py-4">
                          <div className="flex gap-1">
                            <Link href={`/properties/${p.id}`}>
                              <Button variant="ghost" size="icon" className="h-8 w-8">
                                <Eye className="w-4 h-4 text-gray-500" />
                              </Button>
                            </Link>
                            <Link href={`/dashboard/properties/${p.id}`}>
                              <Button variant="ghost" size="icon" className="h-8 w-8">
                                <Pencil className="w-4 h-4 text-blue-500" />
                              </Button>
                            </Link>
                            <Button variant="ghost" size="icon" className="h-8 w-8"
                              onClick={() => setConfirmDelete(p.id)}>
                              <Trash2 className="w-4 h-4 text-red-400" />
                            </Button>
                          </div>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Delete Confirm Modal */}
        {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={() => handleDelete(confirmDelete)}
                  disabled={!!deleting}
                >
                  {deleting === confirmDelete ? <Loader2 className="w-4 h-4 animate-spin" /> : 'حذف'}
                </Button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
