'use client'

import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, AreaChart, Area, LineChart, Line, Legend,
} from 'recharts'

const BLUE_PALETTE  = ['#1d4ed8', '#3b82f6', '#60a5fa', '#93c5fd', '#bfdbe6', '#e0e7ff']
const STATUS_COLORS = { AVAILABLE: '#16a34a', RESERVED: '#d97706', SOLD: '#dc2626' }
const PIE_COLORS    = ['#1d4ed8', '#7c3aed', '#059669', '#d97706', '#dc2626', '#0891b2']

type Analytics = {
  summary: {
    totalProperties: number; recentProperties: number; prevRecentProperties: number
    totalViews: number; totalFavorites: number; totalUsers: number; totalInquiries: number
    recentUsers: number; prevRecentUsers: number
    growth: number; userGrowth: number; propGrowth: number
  }
  byStatus:     { label: string; value: number; status: string }[]
  byType:       { label: string; value: number }[]
  byCity:       { label: string; value: number }[]
  monthlyTrend: { month: string; count: number }[]
  userTrend:    { month: string; count: number }[]
  priceRanges:  { label: string; count: number }[]
  craftsmen:    { total: number; verified: number; byCity: { label: string; value: number }[] }
  inquiries:    { total: number; recent: number }
  topProperties: { id: string; title: string; views: number; city: string; price: number; image: string }[]
}

const CustomTooltip = ({ active, payload, label }: any) => {
  if (!active || !payload?.length) return null
  return (
    <div className="bg-white border border-gray-100 rounded-xl shadow-lg px-4 py-3 text-sm">
      <p className="font-medium text-gray-700 mb-1">{label}</p>
      {payload.map((p: any, i: number) => (
        <p key={i} style={{ color: p.color }} className="font-bold">{p.value.toLocaleString('ar-MA')}</p>
      ))}
    </div>
  )
}

const Section = ({ title, children, className = '' }: { title: string; children: React.ReactNode; className?: string }) => (
  <div className={`bg-white rounded-2xl border shadow-sm p-6 ${className}`}>
    <h2 className="font-bold text-lg mb-5">{title}</h2>
    {children}
  </div>
)

export function AnalyticsCharts({ data }: { data: Analytics }) {
  return (
    <>
      {/* Monthly Trends */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <Section title="📈 إضافات العقارات الشهرية">
          <ResponsiveContainer width="100%" height={240}>
            <AreaChart data={data.monthlyTrend}>
              <defs>
                <linearGradient id="blueGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%"  stopColor="#1d4ed8" stopOpacity={0.15} />
                  <stop offset="95%" stopColor="#1d4ed8" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
              <XAxis dataKey="month" tick={{ fontSize: 11 }} interval={1} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip content={<CustomTooltip />} />
              <Area type="monotone" dataKey="count" stroke="#1d4ed8" strokeWidth={2.5}
                fill="url(#blueGrad)" dot={{ fill: '#1d4ed8', r: 3 }} activeDot={{ r: 5 }} />
            </AreaChart>
          </ResponsiveContainer>
        </Section>

        <Section title="👤 تسجيلات المستخدمين الشهرية">
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={data.userTrend} barSize={16}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f5f5f5" vertical={false} />
              <XAxis dataKey="month" tick={{ fontSize: 11 }} interval={1} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="count" fill="#7c3aed" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </Section>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
        <Section title="🔵 حسب الحالة">
          <ResponsiveContainer width="100%" height={170}>
            <PieChart>
              <Pie data={data.byStatus} cx="50%" cy="50%" innerRadius={50} outerRadius={75}
                dataKey="value" paddingAngle={4}>
                {data.byStatus.map((s, i) => (
                  <Cell key={i} fill={(STATUS_COLORS as any)[s.status] ?? PIE_COLORS[i]} />
                ))}
              </Pie>
              <Tooltip formatter={(v: any) => [`${v} عقار`]} />
            </PieChart>
          </ResponsiveContainer>
          <div className="space-y-2 mt-2">
            {data.byStatus.map((s, i) => (
              <div key={i} className="flex justify-between items-center text-sm">
                <span className="flex items-center gap-2">
                  <span className="w-3 h-3 rounded-full" style={{ background: (STATUS_COLORS as any)[s.status] ?? PIE_COLORS[i] }} />
                  {s.label}
                </span>
                <span className="font-bold">{s.value}</span>
              </div>
            ))}
          </div>
        </Section>

        <Section title="🏠 حسب نوع العقار">
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={data.byType} barSize={36}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f5f5f5" vertical={false} />
              <XAxis dataKey="label" tick={{ fontSize: 12 }} />
              <YAxis tick={{ fontSize: 12 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" radius={[6, 6, 0, 0]}>
                {data.byType.map((_, i) => (
                  <Cell key={i} fill={BLUE_PALETTE[i % BLUE_PALETTE.length]} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </Section>

        <Section title="🔧 الحرفيون حسب المدينة">
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={data.craftsmen.byCity} layout="vertical" barSize={20}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f5f5f5" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11 }} />
              <YAxis type="category" dataKey="label" tick={{ fontSize: 11 }} width={75} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" fill="#059669" radius={[0, 4, 4, 0]} />
            </BarChart>
          </ResponsiveContainer>
          <div className="flex justify-between text-sm mt-3 pt-3 border-t">
            <span className="text-gray-500">الإجمالي: <strong>{data.craftsmen.total}</strong></span>
            <span className="text-green-600">موثق: <strong>{data.craftsmen.verified}</strong></span>
          </div>
        </Section>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <Section title="📍 العقارات حسب المدينة">
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={data.byCity} layout="vertical" barSize={22}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f5f5f5" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11 }} />
              <YAxis type="category" dataKey="label" tick={{ fontSize: 11 }} width={80} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="value" fill="#3b82f6" radius={[0, 6, 6, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </Section>

        <Section title="💰 توزيع الأسعار">
          <ResponsiveContainer width="100%" height={240}>
            <BarChart data={data.priceRanges} barSize={48}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f5f5f5" vertical={false} />
              <XAxis dataKey="label" tick={{ fontSize: 11 }} />
              <YAxis tick={{ fontSize: 11 }} />
              <Tooltip formatter={(v: any) => [`${v} عقار`]} />
              <Bar dataKey="count" fill="#1d4ed8" radius={[6, 6, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </Section>
      </div>

      {/* Top Properties */}
      {data.topProperties?.length > 0 && (
        <Section title="⭐ العقارات الأكثر مشاهدة">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-right">
                  <th className="pb-3 font-medium text-gray-500">العقار</th>
                  <th className="pb-3 font-medium text-gray-500">المدينة</th>
                  <th className="pb-3 font-medium text-gray-500">السعر</th>
                  <th className="pb-3 font-medium text-gray-500">المشاهدات</th>
                </tr>
              </thead>
              <tbody>
                {data.topProperties.map((p, i) => (
                  <tr key={p.id} className="border-b last:border-0">
                    <td className="py-3 flex items-center gap-2">
                      <span className="text-gray-400 text-xs w-5">{i + 1}.</span>
                      <span className="font-medium">{p.title}</span>
                    </td>
                    <td className="py-3 text-gray-500">{p.city}</td>
                    <td className="py-3 text-gray-500">{p.price.toLocaleString('ar-MA')} درهم</td>
                    <td className="py-3">
                      <span className="bg-blue-50 text-blue-700 px-2.5 py-1 rounded-full text-xs font-medium">{p.views.toLocaleString('ar-MA')}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Section>
      )}
    </>
  )
}
