'use client'

import { useState, useEffect } from 'react'
import { useRouter, useParams } from 'next/navigation'
import Link from 'next/link'
import {
  ArrowLeft, Building2, Loader2, CheckCircle, AlertCircle, Save, Trash2
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { VALID_PROPERTY_TYPES, PROPERTY_TYPE_LABELS, MOROCCAN_CITIES } from '@/lib/validations'

const FEATURES_LIST = ['مسبح', 'حديقة', 'موقف سيارات', 'مصعد', 'أمن 24/7', 'تكييف مركزي', 'غرفة خادمة', 'مستودع', 'شرفة', 'إطلالة بحرية', 'قرب المدارس', 'قرب المستشفى']

const STATUS_OPTIONS = [
  { value: 'AVAILABLE', label: 'متاح' },
  { value: 'RESERVED',  label: 'محجوز' },
  { value: 'SOLD',      label: 'مباع' },
  { value: 'RENTED',    label: 'مؤجَّر' },
]

const LABELS: Record<string, string> = {
  APARTMENT: 'شقة', VILLA: 'فيلا', COMMERCIAL: 'محل تجاري', LAND: 'أرض', RIAD: 'رياض', OFFICE: 'مكتب', WAREHOUSE: 'مستودع',
}

export default function EditPropertyPage() {
  const router = useRouter()
  const params = useParams()
  const id = params.id as string

  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [form, setForm] = useState<any>(null)

  const inputCls = 'w-full px-4 py-3 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white'

  useEffect(() => {
    fetch(`/api/properties/${id}`)
      .then(r => r.json())
      .then(d => { setForm(d); setLoading(false) })
      .catch(() => { setError('فشل تحميل العقار'); setLoading(false) })
  }, [id])

  const update = (f: string, v: any) => setForm((p: any) => ({ ...p, [f]: v }))

  const toggleFeature = (feat: string) => {
    setForm((p: any) => ({
      ...p,
      features: p.features.includes(feat) ? p.features.filter((f: string) => f !== feat) : [...p.features, feat],
    }))
  }

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    setError('')
    const { agent, createdAt, updatedAt, viewCount, virtualTourViews, ...data } = form
    try {
      const res = await fetch(`/api/properties/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      if (!res.ok) { const d = await res.json(); setError(d.error || 'حدث خطأ'); return }
      router.push('/dashboard/properties')
    } catch { setError('خطأ في الاتصال') }
    finally { setSaving(false) }
  }

  const handleDelete = async () => {
    if (!confirm('تأكيد حذف هذا العقار؟')) return
    setSaving(true)
    await fetch(`/api/properties/${id}`, { method: 'DELETE' })
    router.push('/dashboard/properties')
  }

  if (loading) return <div className="flex justify-center py-20 bg-gray-50"><Loader2 className="w-8 h-8 animate-spin text-blue-600" /></div>
  if (error && !form) return (
    <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center gap-4" dir="rtl">
      <AlertCircle className="w-12 h-12 text-red-400" /><p className="text-gray-600">{error}</p>
      <Button asChild><Link href="/dashboard/properties">العودة</Link></Button>
    </div>
  )

  return (
    <div className="min-h-screen bg-gray-50 py-8" dir="rtl">
      <div className="container mx-auto px-4 max-w-3xl">
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <Link href="/dashboard/properties" className="text-gray-400 hover:text-gray-600"><ArrowLeft className="w-5 h-5 rotate-180" /></Link>
            <h1 className="text-2xl font-bold flex items-center gap-2"><Building2 className="w-6 h-6 text-blue-600" />تعديل العقار</h1>
          </div>
          <Button variant="outline" size="sm" onClick={handleDelete} className="text-red-500 hover:bg-red-50 gap-1">
            <Trash2 className="w-4 h-4" />حذف
          </Button>
        </div>

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

        <form onSubmit={submit} className="space-y-4">
          <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-4">
            <h2 className="font-bold text-gray-800">المعلومات الأساسية</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2"><input value={form.title} onChange={e => update('title', e.target.value)} required placeholder="عنوان العقار" className={inputCls} /></div>
              <select value={form.type} onChange={e => update('type', e.target.value)} className={inputCls}>
                {VALID_PROPERTY_TYPES.map(t => <option key={t} value={t}>{LABELS[t] || t}</option>)}
              </select>
              <select value={form.status} onChange={e => update('status', e.target.value)} className={inputCls}>
                {STATUS_OPTIONS.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
              </select>
            </div>
            <textarea value={form.description} onChange={e => update('description', e.target.value)} required rows={4} placeholder="وصف العقار" className={`${inputCls} resize-none`} />
          </div>

          <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-4">
            <h2 className="font-bold text-gray-800">السعر والمواصفات</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <input value={form.price} onChange={e => update('price', e.target.value)} type="number" placeholder="السعر (DH)" className={inputCls} />
              <input value={form.area} onChange={e => update('area', e.target.value)} type="number" placeholder="المساحة (م²)" className={inputCls} />
              <input value={form.bedrooms ?? ''} onChange={e => update('bedrooms', e.target.value)} type="number" placeholder="غرف النوم" className={inputCls} />
              <input value={form.bathrooms ?? ''} onChange={e => update('bathrooms', e.target.value)} type="number" placeholder="الحمامات" className={inputCls} />
              <input value={form.floor ?? ''} onChange={e => update('floor', e.target.value)} type="number" placeholder="الطابق" className={inputCls} />
              <input value={form.totalFloors ?? ''} onChange={e => update('totalFloors', e.target.value)} type="number" placeholder="إجمالي الطوابق" className={inputCls} />
              <input value={form.yearBuilt ?? ''} onChange={e => update('yearBuilt', e.target.value)} type="number" placeholder="سنة البناء" className={inputCls} />
            </div>
          </div>

          <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-4">
            <h2 className="font-bold text-gray-800">الموقع</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <select value={form.city} onChange={e => update('city', e.target.value)} className={inputCls}>
                {MOROCCAN_CITIES.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
              <input value={form.neighborhood} onChange={e => update('neighborhood', e.target.value)} placeholder="الحي" className={inputCls} />
              <input value={form.address ?? ''} onChange={e => update('address', e.target.value)} placeholder="العنوان" className={inputCls} />
              <div className="flex gap-2">
                <input value={form.latitude} onChange={e => update('latitude', e.target.value)} type="number" step="any" placeholder="خط العرض" className={inputCls} />
                <input value={form.longitude} onChange={e => update('longitude', e.target.value)} type="number" step="any" placeholder="خط الطول" className={inputCls} />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-4">
            <h2 className="font-bold text-gray-800">المميزات</h2>
            <div className="flex flex-wrap gap-2">
              {FEATURES_LIST.map(f => (
                <button key={f} type="button" onClick={() => toggleFeature(f)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${form.features?.includes(f) ? 'bg-blue-600 text-white border-blue-600' : 'bg-white text-gray-600 border-gray-200 hover:border-blue-300'}`}
                >{f}</button>
              ))}
            </div>
          </div>

          <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-4">
            <h2 className="font-bold text-gray-800">روابط الصور</h2>
            <div className="flex flex-wrap gap-3">
              {[0,1,2,3,4].map(i => (
                <div key={i} className="flex flex-col items-center gap-1">
                  {(form.images?.[i]) ? (
                    <div className="relative">
                      <img src={form.images[i]} alt="" className="w-24 h-24 object-cover rounded-xl border" />
                      <button type="button" onClick={() => update('images', form.images.filter((_: any, j: number) => j !== i))}
                        className="absolute -top-2 -left-2 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center text-xs">×</button>
                    </div>
                  ) : (
                    <div className="w-24 h-24 bg-gray-100 rounded-xl border-2 border-dashed border-gray-200 flex items-center justify-center text-gray-400 text-xs">صورة {i+1}</div>
                  )}
                  <input value={form.images?.[i] || ''} onChange={e => { const imgs = [...(form.images || [])]; imgs[i] = e.target.value; update('images', imgs) }}
                    placeholder="رابط الصورة" className="w-24 text-xs px-2 py-1 border border-gray-200 rounded-lg text-center" />
                </div>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-3">
            <label className="flex items-center gap-2 text-sm font-medium text-gray-700 cursor-pointer">
              <input type="checkbox" checked={form.isFeatured || false} onChange={e => update('isFeatured', e.target.checked)}
                className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" />
              عقار مميز
            </label>
          </div>

          <Button type="submit" disabled={saving} className="w-full py-3 gap-2">
            {saving ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />} حفظ التعديلات
          </Button>
        </form>
      </div>
    </div>
  )
}
