'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useSession } from 'next-auth/react'
import {
  User, Bell, Shield, Download, ArrowLeft, Check,
  Loader2, Eye, EyeOff, Smartphone, Globe, Lock, Mail, Phone, Camera, AlertTriangle, Save,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { passwordStrength } from '@/lib/validations'

type Tab = 'profile' | 'notifications' | 'security' | 'export'

const TABS: { id: Tab; icon: React.ReactNode; label: string }[] = [
  { id: 'profile',       icon: <User      className="w-5 h-5" />, label: 'الملف الشخصي'   },
  { id: 'notifications', icon: <Bell      className="w-5 h-5" />, label: 'الإشعارات'       },
  { id: 'security',      icon: <Shield   className="w-5 h-5" />, label: 'الأمان'          },
  { id: 'export',       icon: <Download  className="w-5 h-5"/>, label: 'تصدير البيانات'   },
]

export default function SettingsPage() {
  const { data: session, update: updateSession } = useSession()
  const [tab, setTab]       = useState<Tab>('profile')
  const [saving, setSaving] = useState(false)
  const [saved, setSaved]   = useState(false)
  const [error, setError]   = useState('')

  const [profile, setProfile] = useState({
    name: '', email: '', phone: '', bio: '', city: 'الدار البيضاء',
  })
  const [loadingProfile, setLoadingProfile] = useState(true)

  const [notifPrefs, setNotifPrefs] = useState({
    emailMessages: true, emailNewProperty: true, emailMarketing: false,
    pushMessages: true, pushNewProperty: false, pushReviews: true, soundEnabled: true,
  })

  const [pwForm, setPwForm]   = useState({ current: '', newPw: '', confirm: '' })
  const [showPw, setShowPw]   = useState({ current: false, newPw: false })
  const [pwError, setPwError] = useState('')
  const [pwSuccess, setPwSuccess] = useState(false)
  const [exporting, setExporting] = useState<string | null>(null)

  const strength = passwordStrength(pwForm.newPw)

  useEffect(() => {
    fetch('/api/user/profile')
      .then(r => r.json())
      .then(data => {
        if (data && !data.error) {
          setProfile({
            name: data.name || '',
            email: data.email || '',
            phone: data.phone || '',
            bio: '',
            city: 'الدار البيضاء',
          })
        }
      })
      .catch(() => {})
      .finally(() => setLoadingProfile(false))
  }, [])

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      const res = await fetch('/api/user/profile', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: profile.name, email: profile.email, phone: profile.phone }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error || 'خطأ في الحفظ')
      } else {
        setSaved(true)
        setTimeout(() => setSaved(false), 2500)
        if (data.name || data.email) {
          await updateSession({ user: { name: data.name, email: data.email } })
        }
      }
    } catch {
      setError('خطأ في الاتصال بالخادم')
    } finally {
      setSaving(false)
    }
  }

  const handlePasswordChange = async () => {
    setPwError('')
    setPwSuccess(false)
    if (!pwForm.current)                              return setPwError('كلمة المرور الحالية مطلوبة')
    if (pwForm.newPw.length < 8)                      return setPwError('كلمة المرور الجديدة 8 أحرف على الأقل')
    if (pwForm.newPw !== pwForm.confirm)              return setPwError('كلمتا المرور غير متطابقتين')
    setSaving(true)
    try {
      const res = await fetch('/api/user/password', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ currentPassword: pwForm.current, newPassword: pwForm.newPw }),
      })
      const data = await res.json()
      if (!res.ok) {
        setPwError(data.error || 'خطأ في تغيير كلمة المرور')
      } else {
        setPwSuccess(true)
        setPwForm({ current: '', newPw: '', confirm: '' })
        setTimeout(() => setPwSuccess(false), 3000)
      }
    } catch {
      setPwError('خطأ في الاتصال بالخادم')
    } finally {
      setSaving(false)
    }
  }

  const handleExport = async (format: 'csv' | 'json') => {
    setExporting(format)
    try {
      const res = await fetch(`/api/export?format=${format}`)
      const blob = await res.blob()
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url; a.download = `aqar-export-${new Date().toISOString().slice(0,10)}.${format}`; a.click()
      URL.revokeObjectURL(url)
    } catch (e) { console.error(e) }
    finally { setExporting(null) }
  }

  const Toggle = ({ checked, onChange, label, sub }: any) => (
    <div className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0">
      <div><p className="text-sm font-medium text-gray-800">{label}</p>{sub && <p className="text-xs text-gray-500 mt-0.5">{sub}</p>}</div>
      <button onClick={() => onChange(!checked)}
        className={`relative w-11 h-6 rounded-full transition-colors duration-200 ${checked ? 'bg-blue-600' : 'bg-gray-300'}`}
        role="switch" aria-checked={checked}>
        <span className={`absolute top-0.5 w-5 h-5 bg-white rounded-full shadow transition-all duration-200 ${checked ? 'right-0.5' : 'left-0.5'}`} />
      </button>
    </div>
  )

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

  const userName = profile.name || (session?.user as any)?.name || 'مستخدم'

  return (
    <div className="py-8" dir="rtl">
      <div className="container mx-auto px-4 max-w-4xl">
        <div className="flex items-center gap-3 mb-8">
          <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">إدارة حسابك وتفضيلاتك</p>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <div className="md:col-span-1">
            <div className="bg-white rounded-2xl border shadow-sm overflow-hidden">
              {TABS.map(t => (
                <button key={t.id} onClick={() => setTab(t.id)}
                  className={`w-full flex items-center gap-3 px-4 py-3.5 text-sm font-medium transition-colors border-b border-gray-50 last:border-0 ${
                    tab === t.id ? 'bg-blue-50 text-blue-700 border-r-2 border-r-blue-600' : 'text-gray-600 hover:bg-gray-50'
                  }`}>
                  {t.icon} {t.label}
                </button>
              ))}
            </div>
          </div>

          <div className="md:col-span-3">

            {tab === 'profile' && (
              <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-5">
                <h2 className="text-lg font-bold mb-2">الملف الشخصي</h2>

                {error && (
                  <div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-xl px-4 py-3">{error}</div>
                )}

                <div className="flex items-center gap-4 pb-4 border-b">
                  <div className="relative">
                    <div className="w-20 h-20 rounded-2xl bg-blue-100 flex items-center justify-center text-3xl font-bold text-blue-600">
                      {userName[0]}
                    </div>
                    <button className="absolute -bottom-1 -left-1 bg-blue-600 text-white rounded-full p-1.5 shadow"><Camera className="w-3.5 h-3.5" /></button>
                  </div>
                  <div>
                    <p className="font-bold">{userName}</p>
                    <p className="text-sm text-gray-500">{(session?.user as any)?.role === 'ADMIN' ? 'مدير' : 'وكيل عقاري'}</p>
                  </div>
                </div>

                {loadingProfile ? (
                  <div className="space-y-4">
                    {[1,2,3,4].map(i => <div key={i} className="h-12 bg-gray-100 rounded-xl animate-pulse" />)}
                  </div>
                ) : (
                  <>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium mb-1.5 text-gray-700">الاسم الكامل</label>
                        <div className="relative">
                          <User className="absolute right-3 top-3.5 w-4 h-4 text-gray-400" />
                          <input className={`${inputCls} pr-10`} value={profile.name} onChange={e => setProfile({ ...profile, name: e.target.value })} />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium mb-1.5 text-gray-700">البريد الإلكتروني</label>
                        <div className="relative">
                          <Mail className="absolute right-3 top-3.5 w-4 h-4 text-gray-400" />
                          <input className={`${inputCls} pr-10`} type="email" value={profile.email} dir="ltr" onChange={e => setProfile({ ...profile, email: e.target.value })} />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium mb-1.5 text-gray-700">رقم الهاتف</label>
                        <div className="relative">
                          <Phone className="absolute right-3 top-3.5 w-4 h-4 text-gray-400" />
                          <input className={`${inputCls} pr-10`} value={profile.phone} dir="ltr" placeholder="+212 6XX-XXXXXX"
                            onChange={e => setProfile({ ...profile, phone: e.target.value })} />
                        </div>
                      </div>
                    </div>
                    <Button onClick={handleSave} disabled={saving} className="w-full gap-2">
                      {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : saved ? <Check className="w-4 h-4" /> : <Save className="w-4 h-4" />}
                      {saved ? 'تم الحفظ!' : 'حفظ التغييرات'}
                    </Button>
                  </>
                )}
              </div>
            )}

            {tab === 'notifications' && (
              <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-2">
                <h2 className="text-lg font-bold mb-4">تفضيلات الإشعارات</h2>
                <div className="mb-4">
                  <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-1">البريد الإلكتروني</h3>
                  <div className="bg-gray-50 rounded-xl px-4">
                    <Toggle label="رسائل جديدة"     sub="إشعار عند وصول رسالة من عميل"     checked={notifPrefs.emailMessages}    onChange={(v: boolean) => setNotifPrefs({...notifPrefs, emailMessages: v})} />
                    <Toggle label="عقارات جديدة"    sub="عند إضافة عقار يطابق بحثك"        checked={notifPrefs.emailNewProperty} onChange={(v: boolean) => setNotifPrefs({...notifPrefs, emailNewProperty: v})} />
                    <Toggle label="النشرة الإخبارية" sub="تحديثات وعروض عقار ديزاين"        checked={notifPrefs.emailMarketing}   onChange={(v: boolean) => setNotifPrefs({...notifPrefs, emailMarketing: v})} />
                  </div>
                </div>
                <div className="mb-4">
                  <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-1">إشعارات التطبيق (Push)</h3>
                  <div className="bg-gray-50 rounded-xl px-4">
                    <Toggle label="رسائل جديدة"   sub="إشعار فوري عند وصول رسالة"   checked={notifPrefs.pushMessages}    onChange={(v: boolean) => setNotifPrefs({...notifPrefs, pushMessages: v})} />
                    <Toggle label="عقارات مميزة"  sub="إشعار بالعقارات الجديدة"    checked={notifPrefs.pushNewProperty} onChange={(v: boolean) => setNotifPrefs({...notifPrefs, pushNewProperty: v})} />
                    <Toggle label="تقييمات جديدة" sub="عند حصول عقارك على تقييم"   checked={notifPrefs.pushReviews}     onChange={(v: boolean) => setNotifPrefs({...notifPrefs, pushReviews: v})} />
                    <Toggle label="الصوت"         sub="تشغيل صوت مع الإشعارات"     checked={notifPrefs.soundEnabled}    onChange={(v: boolean) => setNotifPrefs({...notifPrefs, soundEnabled: v})} />
                  </div>
                </div>
                <div className="bg-blue-50 rounded-xl p-3 text-xs text-blue-600">
                  تفضيلات الإشعارات محفوظة تلقائياً locally في المتصفح.
                </div>
              </div>
            )}

            {tab === 'security' && (
              <div className="space-y-4">
                <div className="bg-white rounded-2xl border shadow-sm p-6">
                  <h2 className="text-lg font-bold mb-5 flex items-center gap-2"><Lock className="w-5 h-5 text-blue-600" /> تغيير كلمة المرور</h2>
                  {pwError && (
                    <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" />{pwError}
                    </div>
                  )}
                  {pwSuccess && (
                    <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" />تم تغيير كلمة المرور بنجاح
                    </div>
                  )}
                  <div className="space-y-4">
                    {(['current', 'newPw'] as const).map(field => (
                      <div key={field}>
                        <label className="block text-sm font-medium mb-1.5 text-gray-700">
                          {field === 'current' ? 'كلمة المرور الحالية' : 'كلمة المرور الجديدة'}
                        </label>
                        <div className="relative">
                          <input type={showPw[field] ? 'text' : 'password'} className={`${inputCls} pl-10`} value={pwForm[field]} dir="ltr"
                            onChange={e => setPwForm({ ...pwForm, [field]: e.target.value })} />
                          <button type="button" onClick={() => setShowPw(s => ({ ...s, [field]: !s[field] }))} className="absolute left-3 top-3.5 text-gray-400">
                            {showPw[field] ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                          </button>
                        </div>
                        {field === 'newPw' && pwForm.newPw && (
                          <div className="mt-2">
                            <div className="flex gap-1 mb-1">
                              {[1,2,3,4].map(i => (
                                <div key={i} className={`h-1.5 flex-1 rounded-full transition-colors ${i <= strength.score ? strength.color : 'bg-gray-200'}`} />
                              ))}
                            </div>
                            <p className="text-xs text-gray-500">قوة كلمة المرور: <span className="font-medium">{strength.label}</span></p>
                          </div>
                        )}
                      </div>
                    ))}
                    <div>
                      <label className="block text-sm font-medium mb-1.5 text-gray-700">تأكيد كلمة المرور الجديدة</label>
                      <input type="password" className={inputCls} value={pwForm.confirm} dir="ltr" onChange={e => setPwForm({ ...pwForm, confirm: e.target.value })} />
                      {pwForm.confirm && pwForm.newPw !== pwForm.confirm && <p className="text-red-500 text-xs mt-1">كلمتا المرور غير متطابقتين</p>}
                    </div>
                  </div>
                  <Button onClick={handlePasswordChange} disabled={saving} className="w-full mt-5 gap-2">
                    {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Shield className="w-4 h-4" />}
                    تحديث كلمة المرور
                  </Button>
                </div>
              </div>
            )}

            {tab === 'export' && (
              <div className="bg-white rounded-2xl border shadow-sm p-6 space-y-6">
                <h2 className="text-lg font-bold">تصدير البيانات</h2>
                {[
                  { format: 'csv' as const, icon: '📊', title: 'تصدير Excel / CSV', desc: 'تحميل جميع عقاراتك في ملف CSV متوافق مع Excel مع دعم العربية الكامل.', badge: 'موصى به', badgeColor: 'bg-green-100 text-green-700' },
                  { format: 'json' as const, icon: '🔧', title: 'تصدير JSON', desc: 'تحميل البيانات الكاملة بصيغة JSON للمطورين وعمليات النسخ الاحتياطي.', badge: 'للمطورين', badgeColor: 'bg-purple-100 text-purple-700' },
                ].map(item => (
                  <div key={item.format} className="border border-gray-200 rounded-2xl p-5 flex gap-4 items-center hover:border-blue-300 transition-colors">
                    <div className="text-4xl shrink-0">{item.icon}</div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <h3 className="font-bold">{item.title}</h3>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${item.badgeColor}`}>{item.badge}</span>
                      </div>
                      <p className="text-sm text-gray-500">{item.desc}</p>
                    </div>
                    <Button variant="outline" onClick={() => handleExport(item.format)} disabled={exporting === item.format} className="shrink-0 gap-2">
                      {exporting === item.format ? <Loader2 className="w-4 h-4 animate-spin" /> : <Download className="w-4 h-4" />}تحميل
                    </Button>
                  </div>
                ))}
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  )
}
