'use client';
import { useState, useEffect } from 'react';
import { useLanguage } from '@/lib/i18n/language-context';
import { motion } from 'framer-motion';
import {
  BarChart3, TrendingUp, Users, Eye, MousePointerClick,
  Globe, ExternalLink, Target, Phone, Mail, MessageSquare,
  Calendar, Activity, PieChart
} from 'lucide-react';

export default function AnalyticsPage() {
  const { locale } = useLanguage();
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const gaId = process.env.NEXT_PUBLIC_GA_ID;
  const hasGA = gaId && gaId !== 'G-XXXXXXXXXX';

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

  const es = locale === 'es';

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-red-600" />
      </div>
    );
  }

  const totalLeads = stats?.totalLeads ?? 0;
  const newLeads = stats?.newLeads ?? 0;
  const contactedLeads = stats?.contactedLeads ?? 0;
  const conversionRate = totalLeads > 0 ? Math.round((contactedLeads / totalLeads) * 100) : 0;
  const leadsByMonth = stats?.leadsByMonth ?? [];
  const leadsBySource = stats?.leadsBySource ?? [];
  const topViewed = stats?.topViewedVehicles ?? [];
  const recentLeads = stats?.recentLeads ?? [];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <BarChart3 className="w-6 h-6 text-red-600" />
            {es ? 'Analíticas y Estadísticas' : 'Analytics & Statistics'}
          </h1>
          <p className="text-gray-500 text-sm mt-1">
            {es ? 'Resumen del rendimiento del sitio y captura de leads' : 'Site performance and lead capture overview'}
          </p>
        </div>
        {hasGA && (
          <a
            href="https://analytics.google.com/analytics/web/"
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition"
          >
            <Globe className="w-4 h-4" />
            Google Analytics
            <ExternalLink className="w-3 h-3" />
          </a>
        )}
      </div>

      {/* GA Status Banner */}
      {!hasGA ? (
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <Activity className="w-5 h-5 text-amber-600 mt-0.5 shrink-0" />
            <div>
              <h3 className="font-semibold text-amber-800 text-sm">
                {es ? 'Google Analytics no está configurado' : 'Google Analytics is not configured'}
              </h3>
              <p className="text-amber-700 text-xs mt-1">
                {es
                  ? 'Para ver estadísticas de tráfico en tiempo real (visitantes, páginas vistas, fuentes de tráfico), necesitas configurar Google Analytics.'
                  : 'To see real-time traffic stats (visitors, page views, traffic sources), you need to configure Google Analytics.'}
              </p>
              <div className="mt-3 bg-white rounded-lg p-3 border border-amber-100">
                <p className="text-xs font-medium text-gray-700 mb-2">{es ? 'Pasos para configurar:' : 'Setup steps:'}</p>
                <ol className="text-xs text-gray-600 space-y-1 list-decimal list-inside">
                  <li>{es ? 'Ve a ' : 'Go to '}<a href="https://analytics.google.com" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">analytics.google.com</a></li>
                  <li>{es ? 'Crea una propiedad para tu sitio web' : 'Create a property for your website'}</li>
                  <li>{es ? 'Copia el Measurement ID (empieza con G-)' : 'Copy the Measurement ID (starts with G-)'}</li>
                  <li>{es ? 'Compártelo conmigo y lo configuro automáticamente' : 'Share it with me and I\'ll configure it automatically'}</li>
                </ol>
              </div>
            </div>
          </div>
        </motion.div>
      ) : (
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="bg-green-50 border border-green-200 rounded-xl p-4">
          <div className="flex items-center gap-3">
            <Activity className="w-5 h-5 text-green-600" />
            <div>
              <h3 className="font-semibold text-green-800 text-sm">
                {es ? 'Google Analytics Activo' : 'Google Analytics Active'}
              </h3>
              <p className="text-green-700 text-xs mt-0.5">
                {es ? 'Rastreando tráfico con ID: ' : 'Tracking traffic with ID: '}<code className="bg-green-100 px-1.5 py-0.5 rounded text-xs">{gaId}</code>
                {' — '}<a href="https://analytics.google.com/analytics/web/" target="_blank" rel="noopener noreferrer" className="text-green-700 underline hover:text-green-900">{es ? 'Ver dashboard completo' : 'View full dashboard'}</a>
              </p>
            </div>
          </div>
        </motion.div>
      )}

      {/* Lead Metrics */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: 'Total Leads', value: totalLeads, icon: Users, bgColor: 'bg-blue-50', iconColor: 'text-blue-600', desc: es ? 'Consultas recibidas' : 'Inquiries received' },
          { label: es ? 'Leads Nuevos' : 'New Leads', value: newLeads, icon: Target, bgColor: 'bg-green-50', iconColor: 'text-green-600', desc: es ? 'Pendientes de contactar' : 'Pending contact' },
          { label: es ? 'Contactados' : 'Contacted', value: contactedLeads, icon: Phone, bgColor: 'bg-purple-50', iconColor: 'text-purple-600', desc: es ? 'En seguimiento' : 'In follow-up' },
          { label: es ? 'Tasa Conversión' : 'Conversion Rate', value: `${conversionRate}%`, icon: TrendingUp, bgColor: 'bg-red-50', iconColor: 'text-red-600', desc: es ? 'Contactados / total' : 'Contacted / total' },
        ].map((m, i) => (
          <motion.div key={i} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.1 }} className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${m.bgColor} mb-3`}>
              <m.icon className={`w-5 h-5 ${m.iconColor}`} />
            </div>
            <p className="text-2xl font-bold text-gray-900">{m.value}</p>
            <p className="text-sm font-medium text-gray-700 mt-0.5">{m.label}</p>
            <p className="text-xs text-gray-400 mt-0.5">{m.desc}</p>
          </motion.div>
        ))}
      </div>

      {/* Inventory Metrics */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: es ? 'Inventario Total' : 'Total Inventory', value: stats?.totalVehicles ?? 0, icon: BarChart3, bgColor: 'bg-indigo-50', iconColor: 'text-indigo-600' },
          { label: es ? 'Disponibles' : 'Available', value: stats?.availableVehicles ?? 0, icon: Eye, bgColor: 'bg-emerald-50', iconColor: 'text-emerald-600' },
          { label: es ? 'Vendidos' : 'Sold', value: stats?.soldVehicles ?? 0, icon: MousePointerClick, bgColor: 'bg-orange-50', iconColor: 'text-orange-600' },
          { label: es ? 'Destacados' : 'Featured', value: stats?.featuredVehicles ?? 0, icon: PieChart, bgColor: 'bg-pink-50', iconColor: 'text-pink-600' },
        ].map((m, i) => (
          <motion.div key={i} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.4 + i * 0.1 }} className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${m.bgColor} mb-3`}>
              <m.icon className={`w-5 h-5 ${m.iconColor}`} />
            </div>
            <p className="text-2xl font-bold text-gray-900">{m.value}</p>
            <p className="text-sm font-medium text-gray-700 mt-0.5">{m.label}</p>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top Viewed */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.6 }} className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <Eye className="w-5 h-5 text-red-500" />
            {es ? 'Vehículos Más Vistos' : 'Most Viewed Vehicles'}
          </h2>
          {topViewed.length === 0 ? (
            <p className="text-gray-400 text-sm">{es ? 'Sin datos aún' : 'No data yet'}</p>
          ) : (
            <div className="space-y-3">
              {topViewed.map((v: any, i: number) => (
                <div key={i} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                  <div className="flex items-center gap-3">
                    <span className="text-xs font-bold text-gray-400 w-5">#{i + 1}</span>
                    <div>
                      <p className="text-sm font-medium text-gray-800 truncate max-w-[250px]">{v.title}</p>
                      <p className="text-xs text-gray-400">${(v.price ?? 0).toLocaleString()}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-1 text-sm font-semibold text-gray-700">
                    <Eye className="w-3.5 h-3.5 text-gray-400" />
                    {v.viewCount ?? 0}
                  </div>
                </div>
              ))}
            </div>
          )}
        </motion.div>

        {/* Recent Leads */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.7 }} className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <MessageSquare className="w-5 h-5 text-red-500" />
            {es ? 'Leads Recientes' : 'Recent Leads'}
          </h2>
          {recentLeads.length === 0 ? (
            <p className="text-gray-400 text-sm">{es ? 'Sin leads aún' : 'No leads yet'}</p>
          ) : (
            <div className="space-y-3">
              {recentLeads.map((lead: any, i: number) => {
                const statusColors: Record<string, string> = {
                  NEW: 'bg-green-100 text-green-700',
                  CONTACTED: 'bg-blue-100 text-blue-700',
                  CLOSED: 'bg-gray-100 text-gray-600',
                  LOST: 'bg-red-100 text-red-600',
                };
                return (
                  <div key={i} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-red-50 rounded-full flex items-center justify-center">
                        <Mail className="w-4 h-4 text-red-500" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-800">{lead.name}</p>
                        <p className="text-xs text-gray-400">{lead.email}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${statusColors[lead.status] || 'bg-gray-100 text-gray-600'}`}>
                        {lead.status}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </motion.div>
      </div>

      {/* Leads by Source + Month */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.8 }} className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <PieChart className="w-5 h-5 text-red-500" />
            {es ? 'Leads por Fuente' : 'Leads by Source'}
          </h2>
          {leadsBySource.length === 0 ? (
            <p className="text-gray-400 text-sm">{es ? 'Sin datos' : 'No data'}</p>
          ) : (
            <div className="space-y-3">
              {leadsBySource.map((s: any, i: number) => {
                const sourceColors: Record<string, string> = { CONTACT_FORM: 'bg-blue-500', PHONE: 'bg-green-500', WHATSAPP: 'bg-emerald-500', EMAIL: 'bg-purple-500' };
                const pct = totalLeads > 0 ? Math.round((s._count / totalLeads) * 100) : 0;
                return (
                  <div key={i}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm text-gray-700 font-medium">{(s.source || 'Unknown').replace(/_/g, ' ')}</span>
                      <span className="text-sm text-gray-500">{s._count} ({pct}%)</span>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-2">
                      <div className={`h-2 rounded-full ${sourceColors[s.source] || 'bg-gray-400'}`} style={{ width: `${pct}%` }} />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.9 }} className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <Calendar className="w-5 h-5 text-red-500" />
            {es ? 'Leads por Mes (últimos 6 meses)' : 'Leads by Month (last 6 months)'}
          </h2>
          {leadsByMonth.length === 0 ? (
            <p className="text-gray-400 text-sm">{es ? 'Sin datos' : 'No data'}</p>
          ) : (
            <div className="space-y-3">
              {leadsByMonth.map((m: any, i: number) => {
                const maxCount = Math.max(...leadsByMonth.map((x: any) => Number(x.count) || 0), 1);
                const pct = Math.round(((Number(m.count) || 0) / maxCount) * 100);
                return (
                  <div key={i}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm text-gray-700 font-medium">{m.month}</span>
                      <span className="text-sm text-gray-500">{m.count} leads</span>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-2">
                      <div className="h-2 rounded-full bg-red-500" style={{ width: `${pct}%` }} />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </motion.div>
      </div>
    </div>
  );
}
