import React, { useState, useEffect } from 'react';
import { CheckCircle, Star, Rocket, Gift, Download, Share2, ArrowRight, Calendar } from 'lucide-react';
import { Button, Card, Badge } from '../../../ui';
import { OnboardingStepProps } from '../OnboardingWizard';

interface CompletionStats {
  totalProducts: number;
  inventoryItems: number;
  suppliersConfigured: number;
  mlModelAccuracy: number;
  estimatedTimeSaved: string;
  completionScore: number;
}

export const CompletionStep: React.FC<OnboardingStepProps> = ({
  data,
  onDataChange,
  onNext,
  onPrevious,
  isFirstStep,
  isLastStep
}) => {
  const [showConfetti, setShowConfetti] = useState(false);
  const [completionStats, setCompletionStats] = useState<CompletionStats | null>(null);

  useEffect(() => {
    // Show confetti animation
    setShowConfetti(true);
    const timer = setTimeout(() => setShowConfetti(false), 3000);

    // Calculate completion stats
    const stats: CompletionStats = {
      totalProducts: data.detectedProducts?.filter((p: any) => p.status === 'approved').length || 0,
      inventoryItems: data.inventoryItems?.length || 0,
      suppliersConfigured: data.suppliers?.length || 0,
      mlModelAccuracy: data.trainingMetrics?.accuracy * 100 || 0,
      estimatedTimeSaved: '15-20 horas',
      completionScore: calculateCompletionScore()
    };

    setCompletionStats(stats);

    // Update parent data
    onDataChange({
      ...data,
      completionStats: stats,
      onboardingCompleted: true,
      completedAt: new Date().toISOString()
    });

    return () => clearTimeout(timer);
  }, []);

  const calculateCompletionScore = () => {
    let score = 0;
    
    // Base score for completing setup
    if (data.bakery?.tenant_id) score += 20;
    
    // Data upload and analysis
    if (data.validation?.is_valid) score += 15;
    if (data.analysisStatus === 'completed') score += 15;
    
    // Product review
    const approvedProducts = data.detectedProducts?.filter((p: any) => p.status === 'approved').length || 0;
    if (approvedProducts > 0) score += 20;
    
    // Inventory setup
    if (data.inventoryItems?.length > 0) score += 15;
    
    // ML training
    if (data.trainingStatus === 'completed') score += 15;
    
    return Math.min(score, 100);
  };

  const generateCertificate = () => {
    // Mock certificate generation
    const certificateData = {
      bakeryName: data.bakery?.name || 'Tu Panadería',
      completionDate: new Date().toLocaleDateString('es-ES'),
      score: completionStats?.completionScore || 0,
      features: [
        'Configuración de Tenant Multi-inquilino',
        'Análisis de Datos con IA',
        'Gestión de Inventario Inteligente',
        'Entrenamiento de Modelo ML',
        'Integración de Proveedores'
      ]
    };

    console.log('Generating certificate:', certificateData);
    alert(`🎓 Certificado generado para ${certificateData.bakeryName}\nPuntuación: ${certificateData.score}/100`);
  };

  const scheduleDemo = () => {
    // Mock demo scheduling
    alert('📅 Te contactaremos pronto para agendar una demostración personalizada de las funcionalidades avanzadas.');
  };

  const shareSuccess = () => {
    // Mock social sharing
    const shareText = `¡Acabo de completar la configuración de mi panadería inteligente con IA! 🥖🤖 Puntuación: ${completionStats?.completionScore}/100`;
    navigator.clipboard.writeText(shareText);
    alert('✅ Texto copiado al portapapeles. ¡Compártelo en tus redes sociales!');
  };

  const quickStartActions = [
    {
      id: 'dashboard',
      title: 'Ir al Dashboard',
      description: 'Explora tu panel de control personalizado',
      icon: <ArrowRight className="w-5 h-5" />,
      action: () => onNext(),
      primary: true
    },
    {
      id: 'inventory',
      title: 'Gestionar Inventario',
      description: 'Revisa y actualiza tu stock actual',
      icon: <Gift className="w-5 h-5" />,
      action: () => console.log('Navigate to inventory'),
      primary: false
    },
    {
      id: 'predictions',
      title: 'Ver Predicciones IA',
      description: 'Consulta las predicciones de demanda',
      icon: <Rocket className="w-5 h-5" />,
      action: () => console.log('Navigate to predictions'),
      primary: false
    }
  ];

  const achievementBadges = [
    {
      title: 'Pionero IA',
      description: 'Primera configuración con Machine Learning',
      icon: '🤖',
      earned: data.trainingStatus === 'completed'
    },
    {
      title: 'Organizador',
      description: 'Inventario completamente configurado',
      icon: '📦',
      earned: (data.inventoryItems?.length || 0) >= 5
    },
    {
      title: 'Analista',
      description: 'Análisis de datos exitoso',
      icon: '📊',
      earned: data.analysisStatus === 'completed'
    },
    {
      title: 'Perfeccionista',
      description: 'Puntuación de configuración 90+',
      icon: '⭐',
      earned: (completionStats?.completionScore || 0) >= 90
    }
  ];

  return (
    <div className="space-y-6">
      {/* Confetti Effect */}
      {showConfetti && (
        <div className="fixed inset-0 pointer-events-none z-50 overflow-hidden">
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="text-6xl animate-bounce">🎉</div>
          </div>
          {/* Additional confetti elements could be added here */}
        </div>
      )}

      {/* Celebration Header */}
      <div className="text-center mb-8">
        <div className="w-24 h-24 bg-gradient-to-br from-[var(--color-success)] to-[var(--color-primary)] rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg">
          <CheckCircle className="w-12 h-12 text-white" />
        </div>
        <h1 className="text-4xl font-bold text-[var(--text-primary)] mb-4">
          ¡Felicidades! 🎉
        </h1>
        <h2 className="text-xl font-semibold text-[var(--color-success)] mb-4">
          {data.bakery?.name} está listo para funcionar
        </h2>
        <p className="text-[var(--text-secondary)] max-w-3xl mx-auto text-lg leading-relaxed">
          Has completado exitosamente la configuración inicial de tu panadería inteligente. 
          Tu sistema está optimizado con IA y listo para transformar la gestión de tu negocio.
        </p>
      </div>

      {/* Completion Stats */}
      {completionStats && (
        <Card className="p-6">
          <div className="text-center mb-6">
            <div className="inline-flex items-center justify-center w-24 h-24 bg-gradient-to-br from-[var(--color-success)] to-[var(--color-primary)] rounded-full mb-4">
              <span className="text-2xl font-bold text-white">{completionStats.completionScore}</span>
              <span className="text-sm text-white/80 ml-1">/100</span>
            </div>
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
              Puntuación de Configuración
            </h3>
            <p className="text-sm text-[var(--text-secondary)]">
              ¡Excelente trabajo! Has superado el promedio de la industria (78/100)
            </p>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
              <p className="text-2xl font-bold text-[var(--color-info)]">{completionStats.totalProducts}</p>
              <p className="text-xs text-[var(--text-secondary)]">Productos</p>
            </div>
            <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
              <p className="text-2xl font-bold text-[var(--color-primary)]">{completionStats.inventoryItems}</p>
              <p className="text-xs text-[var(--text-secondary)]">Inventario</p>
            </div>
            <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
              <p className="text-2xl font-bold text-[var(--color-success)]">{completionStats.suppliersConfigured}</p>
              <p className="text-xs text-[var(--text-secondary)]">Proveedores</p>
            </div>
            <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
              <p className="text-2xl font-bold text-[var(--color-secondary)]">{completionStats.mlModelAccuracy.toFixed(1)}%</p>
              <p className="text-xs text-[var(--text-secondary)]">Precisión IA</p>
            </div>
            <div className="text-center p-3 bg-[var(--bg-secondary)] rounded-lg">
              <p className="text-lg font-bold text-[var(--color-warning)]">{completionStats.estimatedTimeSaved}</p>
              <p className="text-xs text-[var(--text-secondary)]">Tiempo Ahorrado</p>
            </div>
          </div>
        </Card>
      )}

      {/* Achievement Badges */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4 text-center">
          🏆 Logros Desbloqueados
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {achievementBadges.map((badge, index) => (
            <div
              key={index}
              className={`text-center p-4 rounded-lg border-2 transition-all duration-200 ${
                badge.earned
                  ? 'border-[var(--color-success)]/50 bg-[var(--color-success)]/10'
                  : 'border-[var(--border-secondary)] bg-[var(--bg-secondary)] opacity-50'
              }`}
            >
              <div className="text-2xl mb-2">{badge.icon}</div>
              <h4 className="font-medium text-[var(--text-primary)] mb-1 text-sm">{badge.title}</h4>
              <p className="text-xs text-[var(--text-secondary)]">{badge.description}</p>
              {badge.earned && (
                <div className="mt-2">
                  <Badge variant="green" className="text-xs">Conseguido</Badge>
                </div>
              )}
            </div>
          ))}
        </div>
      </Card>

      {/* Quick Actions */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">
          🚀 Próximos Pasos
        </h3>
        <div className="space-y-3">
          {quickStartActions.map((action) => (
            <button
              key={action.id}
              onClick={action.action}
              className={`w-full text-left p-4 rounded-lg border transition-all duration-200 hover:shadow-md ${
                action.primary
                  ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/5'
                  : 'border-[var(--border-secondary)] bg-[var(--bg-secondary)]'
              }`}
            >
              <div className="flex items-center space-x-4">
                <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                  action.primary ? 'bg-[var(--color-primary)]' : 'bg-[var(--bg-tertiary)]'
                }`}>
                  <span className={action.primary ? 'text-white' : 'text-[var(--text-secondary)]'}>
                    {action.icon}
                  </span>
                </div>
                <div className="flex-1">
                  <h4 className={`font-medium ${
                    action.primary ? 'text-[var(--color-primary)]' : 'text-[var(--text-primary)]'
                  }`}>
                    {action.title}
                  </h4>
                  <p className="text-sm text-[var(--text-secondary)]">{action.description}</p>
                </div>
                <ArrowRight className="w-4 h-4 text-[var(--text-tertiary)]" />
              </div>
            </button>
          ))}
        </div>
      </Card>

      {/* Additional Actions */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-4 text-center">
          <Download className="w-6 h-6 text-[var(--color-info)] mx-auto mb-2" />
          <h4 className="font-medium text-[var(--text-primary)] mb-2">Certificado</h4>
          <p className="text-sm text-[var(--text-secondary)] mb-3">
            Descarga tu certificado de configuración
          </p>
          <Button size="sm" variant="outline" onClick={generateCertificate}>
            Descargar
          </Button>
        </Card>

        <Card className="p-4 text-center">
          <Calendar className="w-6 h-6 text-[var(--color-primary)] mx-auto mb-2" />
          <h4 className="font-medium text-[var(--text-primary)] mb-2">Demo Personal</h4>
          <p className="text-sm text-[var(--text-secondary)] mb-3">
            Agenda una demostración 1-a-1
          </p>
          <Button size="sm" variant="outline" onClick={scheduleDemo}>
            Agendar
          </Button>
        </Card>

        <Card className="p-4 text-center">
          <Share2 className="w-6 h-6 text-[var(--color-success)] mx-auto mb-2" />
          <h4 className="font-medium text-[var(--text-primary)] mb-2">Compartir Éxito</h4>
          <p className="text-sm text-[var(--text-secondary)] mb-3">
            Comparte tu logro en redes sociales
          </p>
          <Button size="sm" variant="outline" onClick={shareSuccess}>
            Compartir
          </Button>
        </Card>
      </div>

      {/* Summary & Thanks */}
      <Card className="p-6 bg-gradient-to-br from-[var(--color-primary)]/5 to-[var(--color-success)]/5 border-[var(--color-primary)]/20">
        <div className="text-center">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-3">
            🙏 ¡Gracias por confiar en nuestra plataforma!
          </h3>
          <p className="text-[var(--text-secondary)] mb-4">
            Tu panadería ahora cuenta con tecnología de vanguardia para:
          </p>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-left mb-6">
            <div className="space-y-2">
              <div className="flex items-center space-x-2 text-sm">
                <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
                <span>Predicciones de demanda con IA</span>
              </div>
              <div className="flex items-center space-x-2 text-sm">
                <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
                <span>Gestión inteligente de inventario</span>
              </div>
              <div className="flex items-center space-x-2 text-sm">
                <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
                <span>Optimización de compras</span>
              </div>
            </div>
            <div className="space-y-2">
              <div className="flex items-center space-x-2 text-sm">
                <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
                <span>Alertas automáticas de restock</span>
              </div>
              <div className="flex items-center space-x-2 text-sm">
                <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
                <span>Análisis de tendencias de venta</span>
              </div>
              <div className="flex items-center space-x-2 text-sm">
                <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
                <span>Control multi-tenant seguro</span>
              </div>
            </div>
          </div>

          <div className="bg-[var(--color-info)]/10 rounded-lg p-4">
            <p className="text-sm text-[var(--color-info)]">
              💡 <strong>Consejo:</strong> Explora el dashboard para descubrir todas las funcionalidades disponibles. 
              El sistema aprenderá de tus patrones y mejorará sus recomendaciones con el tiempo.
            </p>
          </div>
        </div>
      </Card>

    </div>
  );
};