'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import {
  Building2, Eye, MessageSquare,
  Plus, ArrowLeft, ChevronUp,
  ChevronDown, BarChart3,
  Sparkles, Wrench
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { PropertiesGridSkeleton } from '@/components/ui/skeleton'
import { NotificationBell } from '@/components/notifications/notification-bell'
import { useSafeSession } from '@/hooks/use-safe-session'

type Stat = { label: string; value: string | number; change: number; icon: React.ReactNode; color: string }
type Property = { id: string; title: string; city: string; price: number; status: string; viewCount: number; images: string[]; createdAt: string }

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'    },
}

export default function DashboardPage() {
  const [properties, setProperties] = useState<Property[]>([])
  const [loading, setLoading]       = useState(true)
  const [craftsmenCount, setCraftsmenCount] = useState(0)
  const [unverifiedCount, setUnverifiedCount] = useState(0)
  const [greeting, setGreeting]     = useState('')
  const { data: session } = useSafeSession()

  useEffect(() => {
    const h = new Date().getHours()
    setGreeting(h < 12 ? 'صباح الخير' : h < 18 ? 'مساء الخير' : 'مساء النور')

    fetch('/api/properties?limit=6')
      .then(r => r.json())
      .then(d => setProperties(d.properties ?? []))
      .catch(() => {})
    fetch('/api/craftsmen?limit=1')
      .then(r => r.json())
      .then(d => { setCraftsmenCount(d.total ?? 0); setUnverifiedCount(d.unverified ?? 0) })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  const stats: Stat[] = [
    { label: 'إجمالي العقارات',  value: properties.length, change: +12, icon: <Building2 className="w-6 h-6" />,    color: 'bg-blue-50 text-blue-600'   },
    { label: 'الحرفيون',         value: craftsmenCount,    change: +3,  icon: <Wrench className="w-6 h-6" />,        color: 'bg-emerald-50 text-emerald-600'},
    { label: 'قيد المراجعة',     value: unverifiedCount,   change: 0,   icon: <Sparkles className="w-6 h-6" />,     color: 'bg-amber-50 text-amber-600'  },
    { label: 'المشاهدات الشهر',  value: '4,821',           change: +23, icon: <Eye className="w-6 h-6" />,          color: 'bg-purple-50 text-purple-600'},
  ]

  return (
    <div className="p-6">
        {/* Header */}
        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{greeting}، وكيل الديمو 👋</h1>
            <p className="text-gray-500 text-sm mt-1">
              {new Date().toLocaleDateString('ar-MA', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
            </p>
          </div>
          <div className="flex gap-3">
            <NotificationBell userId={session?.user?.id} />
            <Button asChild>
              <Link href="/properties/new" className="gap-2">
                <Plus className="w-4 h-4" />
                إضافة عقار
              </Link>
            </Button>
          </div>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
          {stats.map((stat, i) => (
            <div key={i} className="bg-white rounded-2xl p-5 shadow-sm border">
              <div className="flex justify-between items-start mb-4">
                <div className={`p-2.5 rounded-xl ${stat.color}`}>{stat.icon}</div>
                <div className={`flex items-center gap-1 text-xs font-medium ${stat.change >= 0 ? 'text-green-600' : 'text-red-500'}`}>
                  {stat.change >= 0 ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                  {Math.abs(stat.change)}%
                </div>
              </div>
              <div className="text-2xl font-bold text-gray-900 mb-1">{stat.value}</div>
              <div className="text-sm text-gray-500">{stat.label}</div>
            </div>
          ))}
        </div>

        {/* Recent Properties */}
        <div className="bg-white rounded-2xl shadow-sm border p-6 mb-6">
          <div className="flex justify-between items-center mb-5">
            <h2 className="text-lg font-bold">آخر العقارات المضافة</h2>
            <Link href="/dashboard/properties" className="text-sm text-blue-600 hover:underline flex items-center gap-1">
              عرض الكل <ArrowLeft className="w-4 h-4" />
            </Link>
          </div>

          {loading ? (
            <div className="space-y-3">
              {[1,2,3].map(i => (
                <div key={i} className="flex gap-4 animate-pulse">
                  <div className="w-20 h-16 bg-gray-200 rounded-xl shrink-0" />
                  <div className="flex-1 space-y-2 py-1">
                    <div className="h-4 bg-gray-200 rounded w-3/4" />
                    <div className="h-3 bg-gray-200 rounded w-1/2" />
                    <div className="h-3 bg-gray-200 rounded w-1/4" />
                  </div>
                </div>
              ))}
            </div>
          ) : properties.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <Building2 className="w-12 h-12 mx-auto mb-3 opacity-30" />
              <p className="mb-4">لا توجد عقارات بعد</p>
              <Button asChild size="sm">
                <Link href="/properties/new">إضافة أول عقار</Link>
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              {properties.slice(0, 5).map(p => {
                const st = STATUS_MAP[p.status] ?? { label: p.status, color: 'bg-gray-100 text-gray-600' }
                return (
                  <div key={p.id} className="flex items-center gap-4 p-3 hover:bg-gray-50 rounded-xl transition-colors">
                    <div className="relative w-20 h-16 rounded-xl overflow-hidden shrink-0 bg-gray-100">
                      {p.images?.[0] && (
                        <Image src={p.images[0]} alt={p.title} fill className="object-cover" sizes="80px" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <h3 className="font-medium text-sm truncate">{p.title}</h3>
                      <p className="text-xs text-gray-500 mt-0.5">{p.city}</p>
                    </div>
                    <div className="text-left shrink-0 space-y-1">
                      <p className="text-blue-600 font-bold text-sm">{p.price.toLocaleString('ar-MA')} درهم</p>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${st.color}`}>{st.label}</span>
                    </div>
                    <div className="text-xs text-gray-400 flex items-center gap-1 shrink-0">
                      <Eye className="w-3.5 h-3.5" />{p.viewCount ?? 0}
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>

        {/* Quick Actions */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { href: '/properties/new',      icon: <Plus className="w-6 h-6" />,           label: 'إضافة عقار جديد', color: 'bg-blue-600 text-white'       },
            { href: '/dashboard/craftsmen', icon: <Wrench className="w-6 h-6" />,         label: 'إدارة الحرفيين',  color: 'bg-emerald-600 text-white'    },
            { href: '/dashboard/analytics', icon: <BarChart3 className="w-6 h-6" />,      label: 'عرض التحليلات',   color: 'bg-purple-600 text-white'     },
            { href: '/messages',            icon: <MessageSquare className="w-6 h-6" />,  label: 'الرسائل',         color: 'bg-amber-500 text-white'      },
          ].map(action => (
            <Link key={action.href} href={action.href}
              className={`${action.color} rounded-2xl p-5 flex flex-col items-center gap-3 text-center hover:opacity-90 transition-opacity shadow-sm`}>
              {action.icon}
              <span className="text-sm font-medium">{action.label}</span>
            </Link>
          ))}
        </div>
    </div>
  )
}
