'use client';
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { Truck, Tag, Users, FolderOpen, Eye, TrendingUp, Star, Clock } from 'lucide-react';
import Link from 'next/link';
import { useLanguage } from '@/lib/i18n/language-context';

export default function DashboardPage() {
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const { t } = useLanguage();

  useEffect(() => {
    fetch('/api/stats')
      .then((r: any) => r?.json?.())
      .then((d: any) => setStats(d ?? {}))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin w-8 h-8 border-4 border-red-600 border-t-transparent rounded-full" />
      </div>
    );
  }

  const statCards = [
    { icon: Truck, label: t.admin.dashboard.totalVehicles, value: stats?.totalVehicles ?? 0, color: 'bg-blue-50 text-blue-600' },
    { icon: Tag, label: t.admin.dashboard.available, value: stats?.availableVehicles ?? 0, color: 'bg-green-50 text-green-600' },
    { icon: TrendingUp, label: t.admin.dashboard.sold, value: stats?.soldVehicles ?? 0, color: 'bg-red-50 text-red-600' },
    { icon: Star, label: t.admin.dashboard.featured, value: stats?.featuredVehicles ?? 0, color: 'bg-yellow-50 text-yellow-600' },
    { icon: Users, label: t.admin.dashboard.totalLeads, value: stats?.totalLeads ?? 0, color: 'bg-purple-50 text-purple-600' },
    { icon: Clock, label: t.admin.dashboard.newLeads, value: stats?.newLeads ?? 0, color: 'bg-orange-50 text-orange-600' },
    { icon: FolderOpen, label: t.admin.dashboard.categories, value: stats?.totalCategories ?? 0, color: 'bg-indigo-50 text-indigo-600' },
    { icon: Eye, label: t.admin.dashboard.contacted, value: stats?.contactedLeads ?? 0, color: 'bg-teal-50 text-teal-600' },
  ];

  return (
    <div>
      <h1 className="font-display text-2xl font-bold tracking-tight mb-6">{t.admin.dashboard.title}</h1>

      {/* Stat cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        {(statCards ?? [])?.map((card: any, i: number) => (
          <motion.div key={i} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }} className="bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${card?.color ?? ''} mb-3`}>
              <card.icon className="w-5 h-5" />
            </div>
            <p className="text-2xl font-bold text-gray-900">{card?.value ?? 0}</p>
            <p className="text-xs text-gray-500 mt-1">{card?.label ?? ''}</p>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top viewed */}
        <div className="bg-white rounded-xl p-6 shadow-sm">
          <h2 className="font-semibold text-lg mb-4 flex items-center gap-2"><Eye className="w-5 h-5 text-red-500" /> {t.admin.dashboard.topViewed}</h2>
          {(stats?.topViewed?.length ?? 0) > 0 ? (
            <div className="space-y-3">
              {(stats?.topViewed ?? [])?.map((v: any, i: number) => (
                <div key={v?.id ?? i} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                  <div>
                    <p className="text-sm font-medium text-gray-900">{v?.title ?? t.common.noTitle}</p>
                    <span className={`text-xs px-2 py-0.5 rounded-full ${v?.status === 'SOLD' ? 'bg-gray-100 text-gray-600' : 'bg-green-50 text-green-600'}`}>
                      {v?.status === 'SOLD' ? t.admin.dashboard.soldLabel : t.admin.dashboard.availableLabel}
                    </span>
                  </div>
                  <span className="text-sm font-mono text-gray-500 flex items-center gap-1"><Eye className="w-3 h-3" /> {v?.viewCount ?? 0}</span>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-gray-400">{t.admin.dashboard.noData}</p>
          )}
        </div>

        {/* Recent leads */}
        <div className="bg-white rounded-xl p-6 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-lg flex items-center gap-2"><Users className="w-5 h-5 text-red-500" /> {t.admin.dashboard.recentLeads}</h2>
            <Link href="/admin/leads" className="text-xs text-red-600 hover:text-red-700">{t.admin.dashboard.viewAll} &rarr;</Link>
          </div>
          {(stats?.recentLeads?.length ?? 0) > 0 ? (
            <div className="space-y-3">
              {(stats?.recentLeads ?? [])?.map((lead: any, i: number) => (
                <div key={lead?.id ?? i} className="py-2 border-b border-gray-50 last:border-0">
                  <div className="flex items-center justify-between">
                    <p className="text-sm font-medium text-gray-900">{lead?.name ?? ''}</p>
                    <span className={`text-xs px-2 py-0.5 rounded-full ${lead?.status === 'NEW' ? 'bg-orange-50 text-orange-600' : lead?.status === 'CONTACTED' ? 'bg-blue-50 text-blue-600' : 'bg-gray-100 text-gray-600'}`}>
                      {lead?.status ?? 'NEW'}
                    </span>
                  </div>
                  <p className="text-xs text-gray-400 truncate mt-1">{lead?.message ?? ''}</p>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-gray-400">{t.admin.dashboard.noLeads}</p>
          )}
        </div>
      </div>
    </div>
  );
}
