import { useState, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { TrendingUp, Users, MapPin, Calendar, DollarSign } from "lucide-react";

const StatsSection = () => {
  const [stats, setStats] = useState({
    totalUsers: 50000,
    totalReservations: 125000,
    totalBusinesses: 2500,
    totalRevenue: 15000000
  });

  const [isAnimating, setIsAnimating] = useState(false);

  useEffect(() => {
    // Simular animación de contadores al cargar
    setIsAnimating(true);
    
    // Simular actualizaciones en tiempo real (en producción vendría de la API)
    const interval = setInterval(() => {
      setStats(prev => ({
        totalUsers: prev.totalUsers + Math.floor(Math.random() * 3),
        totalReservations: prev.totalReservations + Math.floor(Math.random() * 5),
        totalBusinesses: prev.totalBusinesses + Math.floor(Math.random() * 2),
        totalRevenue: prev.totalRevenue + Math.floor(Math.random() * 10000)
      }));
    }, 10000); // Actualizar cada 10 segundos

    return () => clearInterval(interval);
  }, []);

  const formatNumber = (num: number) => {
    if (num >= 1000000) {
      return `${(num / 1000000).toFixed(1)}M`;
    }
    if (num >= 1000) {
      return `${(num / 1000).toFixed(1)}K`;
    }
    return num.toLocaleString();
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('es-DO', {
      style: 'currency',
      currency: 'DOP',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const statItems = [
    {
      icon: <Users className="w-8 h-8" />,
      label: "Usuarios Activos",
      value: formatNumber(stats.totalUsers),
      change: "+12.5%",
      changeType: "positive" as const,
      color: "primary"
    },
    {
      icon: <Calendar className="w-8 h-8" />,
      label: "Reservas Totales", 
      value: formatNumber(stats.totalReservations),
      change: "+8.3%",
      changeType: "positive" as const,
      color: "secondary"
    },
    {
      icon: <MapPin className="w-8 h-8" />,
      label: "Negocios Registrados",
      value: formatNumber(stats.totalBusinesses),
      change: "+15.2%",
      changeType: "positive" as const,
      color: "success"
    },
    {
      icon: <DollarSign className="w-8 h-8" />,
      label: "Volumen de Transacciones",
      value: formatCurrency(stats.totalRevenue),
      change: "+22.1%",
      changeType: "positive" as const,
      color: "warning"
    }
  ];

  const getColorClasses = (color: string) => {
    switch (color) {
      case "primary":
        return "text-primary bg-primary/10";
      case "secondary":
        return "text-secondary bg-secondary/10";
      case "success":
        return "text-success bg-success/10";
      case "warning":
        return "text-warning bg-warning/10";
      default:
        return "text-primary bg-primary/10";
    }
  };

  return (
    <section className="py-20 bg-background">
      <div className="max-w-7xl mx-auto px-4">
        {/* Section Header */}
        <div className="text-center mb-16">
          <div className="inline-block px-4 py-2 bg-success/10 text-success rounded-full text-sm font-medium mb-4">
            Impacto en Tiempo Real
          </div>
          <h2 className="text-4xl md:text-5xl font-bold mb-6">
            Transformando el{" "}
            <span className="text-gradient">Turismo Caribeño</span>
          </h2>
          <p className="text-xl text-muted-foreground max-w-3xl mx-auto">
            Nuestras métricas en vivo muestran el crecimiento constante del ecosistema turístico más completo del Caribe.
          </p>
        </div>

        {/* Stats Grid */}
        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8 mb-16">
          {statItems.map((stat, index) => (
            <Card 
              key={index} 
              className={`card-tropical p-8 text-center group ${isAnimating ? 'animate-in fade-in slide-in-from-bottom-4' : ''}`}
              style={{ animationDelay: `${index * 150}ms` }}
            >
              {/* Icon */}
              <div className={`w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6 ${getColorClasses(stat.color)} group-hover:scale-110 transition-transform duration-300`}>
                {stat.icon}
              </div>

              {/* Value */}
              <div className="text-4xl font-bold mb-2 text-foreground">
                {stat.value}
              </div>

              {/* Label */}
              <div className="text-muted-foreground font-medium mb-4">
                {stat.label}
              </div>

              {/* Change Indicator */}
              <div className="flex items-center justify-center gap-1">
                <TrendingUp className="w-4 h-4 text-success" />
                <span className="text-sm font-medium text-success">
                  {stat.change}
                </span>
                <span className="text-xs text-muted-foreground">
                  vs mes anterior
                </span>
              </div>
            </Card>
          ))}
        </div>

        {/* Live Activity Feed */}
        <Card className="card-tropical p-8">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-2xl font-bold">Actividad en Vivo</h3>
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 bg-success rounded-full animate-pulse"></div>
              <span className="text-sm text-muted-foreground">En tiempo real</span>
            </div>
          </div>

          <div className="space-y-4">
            {[
              { 
                text: "Nueva reserva de hotel en Santo Domingo",
                time: "Hace 2 minutos",
                type: "reservation"
              },
              {
                text: "Guía turístico se unió en San Juan",
                time: "Hace 5 minutos", 
                type: "guide"
              },
              {
                text: "Restaurante activó menús digitales",
                time: "Hace 8 minutos",
                type: "restaurant"
              },
              {
                text: "Nuevo usuario registrado desde Punta Cana",
                time: "Hace 12 minutos",
                type: "user"
              }
            ].map((activity, index) => (
              <div key={index} className="flex items-center gap-4 p-4 bg-muted/30 rounded-lg">
                <div className="w-2 h-2 bg-primary rounded-full"></div>
                <div className="flex-1">
                  <p className="text-sm font-medium">{activity.text}</p>
                  <p className="text-xs text-muted-foreground">{activity.time}</p>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </section>
  );
};

export default StatsSection;