import React, { useState } from 'react';
import { Brain, TrendingUp, AlertTriangle, Lightbulb, Target, Zap, Download, RefreshCw } from 'lucide-react';
import { Button, Card, Badge } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';

const AIInsightsPage: React.FC = () => {
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [isRefreshing, setIsRefreshing] = useState(false);

  const insights = [
    {
      id: '1',
      type: 'optimization',
      priority: 'high',
      title: 'Optimización de Producción de Croissants',
      description: 'La demanda de croissants aumenta un 23% los viernes. Recomendamos incrementar la producción en 15 unidades.',
      impact: 'Aumento estimado de ingresos: €180/semana',
      confidence: 87,
      category: 'production',
      timestamp: '2024-01-26 09:30',
      actionable: true,
      metrics: {
        currentProduction: 45,
        recommendedProduction: 60,
        expectedIncrease: '+23%'
      }
    },
    {
      id: '2',
      type: 'alert',
      priority: 'medium',
      title: 'Patrón de Compra en Tardes',
      description: 'Los clientes compran más productos salados después de las 16:00. Considera promocionar empanadas durante estas horas.',
      impact: 'Potencial aumento de ventas: 12%',
      confidence: 92,
      category: 'sales',
      timestamp: '2024-01-26 08:45',
      actionable: true,
      metrics: {
        afternoonSales: '+15%',
        savoryProducts: '68%',
        conversionRate: '12.3%'
      }
    },
    {
      id: '3',
      type: 'prediction',
      priority: 'high',
      title: 'Predicción de Demanda de San Valentín',
      description: 'Se espera un incremento del 40% en la demanda de productos de repostería especiales entre el 10-14 de febrero.',
      impact: 'Preparar stock adicional de ingredientes premium',
      confidence: 94,
      category: 'forecasting',
      timestamp: '2024-01-26 07:15',
      actionable: true,
      metrics: {
        expectedIncrease: '+40%',
        daysAhead: 18,
        recommendedPrep: '3 días'
      }
    },
    {
      id: '4',
      type: 'recommendation',
      priority: 'low',
      title: 'Optimización de Inventario de Harina',
      description: 'El consumo de harina integral ha disminuido 8% este mes. Considera ajustar las órdenes de compra.',
      impact: 'Reducción de desperdicios: €45/mes',
      confidence: 78,
      category: 'inventory',
      timestamp: '2024-01-25 16:20',
      actionable: false,
      metrics: {
        consumption: '-8%',
        currentStock: '45kg',
        recommendedOrder: '25kg'
      }
    },
    {
      id: '5',
      type: 'insight',
      priority: 'medium',
      title: 'Análisis de Satisfacción del Cliente',
      description: 'Los clientes valoran más la frescura (95%) que el precio (67%). Enfoque en destacar la calidad artesanal.',
      impact: 'Mejorar estrategia de marketing',
      confidence: 89,
      category: 'customer',
      timestamp: '2024-01-25 14:30',
      actionable: true,
      metrics: {
        freshnessScore: '95%',
        priceScore: '67%',
        qualityScore: '91%'
      }
    }
  ];

  const categories = [
    { value: 'all', label: 'Todas las Categorías', count: insights.length },
    { value: 'production', label: 'Producción', count: insights.filter(i => i.category === 'production').length },
    { value: 'sales', label: 'Ventas', count: insights.filter(i => i.category === 'sales').length },
    { value: 'forecasting', label: 'Pronósticos', count: insights.filter(i => i.category === 'forecasting').length },
    { value: 'inventory', label: 'Inventario', count: insights.filter(i => i.category === 'inventory').length },
    { value: 'customer', label: 'Clientes', count: insights.filter(i => i.category === 'customer').length },
  ];

  const aiMetrics = {
    totalInsights: insights.length,
    actionableInsights: insights.filter(i => i.actionable).length,
    averageConfidence: Math.round(insights.reduce((sum, i) => sum + i.confidence, 0) / insights.length),
    highPriorityInsights: insights.filter(i => i.priority === 'high').length,
  };

  const getTypeIcon = (type: string) => {
    const iconProps = { className: "w-5 h-5" };
    switch (type) {
      case 'optimization': return <Target {...iconProps} />;
      case 'alert': return <AlertTriangle {...iconProps} />;
      case 'prediction': return <TrendingUp {...iconProps} />;
      case 'recommendation': return <Lightbulb {...iconProps} />;
      case 'insight': return <Brain {...iconProps} />;
      default: return <Brain {...iconProps} />;
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'red';
      case 'medium': return 'yellow';
      case 'low': return 'green';
      default: return 'gray';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'optimization': return 'bg-[var(--color-info)]/10 text-[var(--color-info)]';
      case 'alert': return 'bg-[var(--color-error)]/10 text-[var(--color-error)]';
      case 'prediction': return 'bg-purple-100 text-purple-800';
      case 'recommendation': return 'bg-[var(--color-success)]/10 text-[var(--color-success)]';
      case 'insight': return 'bg-[var(--color-primary)]/10 text-[var(--color-primary)]';
      default: return 'bg-[var(--bg-tertiary)] text-[var(--text-primary)]';
    }
  };

  const filteredInsights = selectedCategory === 'all' 
    ? insights 
    : insights.filter(insight => insight.category === selectedCategory);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await new Promise(resolve => setTimeout(resolve, 2000));
    setIsRefreshing(false);
  };

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Inteligencia Artificial"
        description="Insights inteligentes y recomendaciones automáticas para optimizar tu panadería"
        action={
          <div className="flex space-x-2">
            <Button variant="outline" onClick={handleRefresh} disabled={isRefreshing}>
              <RefreshCw className={`w-4 h-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />
              Actualizar
            </Button>
            <Button variant="outline">
              <Download className="w-4 h-4 mr-2" />
              Exportar
            </Button>
          </div>
        }
      />

      {/* AI Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Total Insights</p>
              <p className="text-3xl font-bold text-[var(--color-info)]">{aiMetrics.totalInsights}</p>
            </div>
            <div className="h-12 w-12 bg-[var(--color-info)]/10 rounded-full flex items-center justify-center">
              <Brain className="h-6 w-6 text-[var(--color-info)]" />
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Accionables</p>
              <p className="text-3xl font-bold text-[var(--color-success)]">{aiMetrics.actionableInsights}</p>
            </div>
            <div className="h-12 w-12 bg-[var(--color-success)]/10 rounded-full flex items-center justify-center">
              <Zap className="h-6 w-6 text-[var(--color-success)]" />
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Confianza Promedio</p>
              <p className="text-3xl font-bold text-purple-600">{aiMetrics.averageConfidence}%</p>
            </div>
            <div className="h-12 w-12 bg-purple-100 rounded-full flex items-center justify-center">
              <Target className="h-6 w-6 text-purple-600" />
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-[var(--text-secondary)]">Alta Prioridad</p>
              <p className="text-3xl font-bold text-[var(--color-error)]">{aiMetrics.highPriorityInsights}</p>
            </div>
            <div className="h-12 w-12 bg-[var(--color-error)]/10 rounded-full flex items-center justify-center">
              <AlertTriangle className="h-6 w-6 text-[var(--color-error)]" />
            </div>
          </div>
        </Card>
      </div>

      {/* Category Filter */}
      <Card className="p-6">
        <div className="flex flex-wrap gap-2">
          {categories.map((category) => (
            <button
              key={category.value}
              onClick={() => setSelectedCategory(category.value)}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedCategory === category.value
                  ? 'bg-blue-600 text-white'
                  : 'bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:bg-[var(--bg-quaternary)]'
              }`}
            >
              {category.label} ({category.count})
            </button>
          ))}
        </div>
      </Card>

      {/* Insights List */}
      <div className="space-y-4">
        {filteredInsights.map((insight) => (
          <Card key={insight.id} className="p-6">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center space-x-3 mb-3">
                  <div className={`p-2 rounded-lg ${getTypeColor(insight.type)}`}>
                    {getTypeIcon(insight.type)}
                  </div>
                  <div className="flex items-center space-x-2">
                    <Badge variant={getPriorityColor(insight.priority)}>
                      {insight.priority === 'high' ? 'Alta' : insight.priority === 'medium' ? 'Media' : 'Baja'} Prioridad
                    </Badge>
                    <Badge variant="gray">{insight.confidence}% confianza</Badge>
                    {insight.actionable && (
                      <Badge variant="blue">Accionable</Badge>
                    )}
                  </div>
                </div>
                
                <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">{insight.title}</h3>
                <p className="text-[var(--text-secondary)] mb-3">{insight.description}</p>
                <p className="text-sm font-medium text-[var(--color-success)] mb-4">{insight.impact}</p>

                {/* Metrics */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                  {Object.entries(insight.metrics).map(([key, value]) => (
                    <div key={key} className="bg-[var(--bg-secondary)] p-3 rounded-lg">
                      <p className="text-xs text-[var(--text-tertiary)] uppercase tracking-wider">
                        {key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())}
                      </p>
                      <p className="text-sm font-semibold text-[var(--text-primary)]">{value}</p>
                    </div>
                  ))}
                </div>

                <div className="flex items-center justify-between">
                  <p className="text-xs text-[var(--text-tertiary)]">{insight.timestamp}</p>
                  {insight.actionable && (
                    <Button size="sm">
                      Aplicar Recomendación
                    </Button>
                  )}
                </div>
              </div>
            </div>
          </Card>
        ))}
      </div>

      {filteredInsights.length === 0 && (
        <Card className="p-12 text-center">
          <Brain className="h-12 w-12 text-[var(--text-tertiary)] mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">No hay insights disponibles</h3>
          <p className="text-[var(--text-secondary)] mb-4">
            No se encontraron insights para la categoría seleccionada.
          </p>
          <Button onClick={handleRefresh}>
            <RefreshCw className="w-4 h-4 mr-2" />
            Generar Nuevos Insights
          </Button>
        </Card>
      )}
    </div>
  );
};

export default AIInsightsPage;