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 { AnalyticsPageLayout, AnalyticsCard } from '../../../../components/analytics';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import { useAIInsights, useAIInsightStats, useApplyInsight, useDismissInsight } from '../../../../api/hooks/aiInsights';
import { AIInsight } from '../../../../api/services/aiInsights';
import { useTranslation } from 'react-i18next';

const AIInsightsPage: React.FC = () => {
  const [selectedCategory, setSelectedCategory] = useState('all');
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const tenantId = currentTenant?.id || user?.tenant_id;
  const { t } = useTranslation('reasoning');

  // Fetch real insights from API
  // Note: Backend expects status values: 'new', 'acknowledged', 'in_progress', 'applied', 'dismissed', 'expired'
  // We fetch 'new' and 'acknowledged' insights (not dismissed, applied, or expired)
  const { data: insightsData, isLoading, refetch } = useAIInsights(
    tenantId || '',
    {
      category: selectedCategory === 'all' ? undefined : selectedCategory,
      limit: 100,
    },
    { enabled: !!tenantId }
  );

  // Fetch stats
  const { data: stats } = useAIInsightStats(
    tenantId || '',
    {},
    { enabled: !!tenantId }
  );

  // Mutations
  const applyMutation = useApplyInsight();
  const dismissMutation = useDismissInsight();

  const insights: AIInsight[] = insightsData?.items || [];

  // Use real insights data
  const displayInsights = insights;

  const categories = [
    { value: 'all', label: 'Todas las Categorías', count: stats?.total_insights || 0 },
    { value: 'production', label: 'Producción', count: stats?.by_category?.production || 0 },
    { value: 'sales', label: 'Ventas', count: stats?.by_category?.sales || 0 },
    { value: 'demand', label: 'Pronósticos', count: stats?.by_category?.demand || stats?.by_category?.forecasting || 0 },
    { value: 'inventory', label: 'Inventario', count: stats?.by_category?.inventory || 0 },
    { value: 'procurement', label: 'Compras', count: stats?.by_category?.procurement || 0 },
  ];

  const aiMetrics = {
    totalInsights: stats?.total_insights || 0,
    actionableInsights: stats?.actionable_insights || 0,
    averageConfidence: stats?.average_confidence ? Math.round(stats.average_confidence) : 0,
    highPriorityInsights: (stats?.high_priority_count || 0) + (stats?.critical_priority_count || 0),
    mediumPriorityInsights: stats?.medium_priority_count || 0,
    lowPriorityInsights: stats?.low_priority_count || 0,
  };

  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 'error';
      case 'medium': return 'warning';
      case 'low': return 'success';
      default: return 'default';
    }
  };

  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'
    ? displayInsights
    : displayInsights.filter(insight => insight.category === selectedCategory);

  const handleRefresh = async () => {
    await refetch();
  };

  const handleApplyInsight = async (insightId: string) => {
    if (!tenantId) return;
    try {
      await applyMutation.mutateAsync({ tenantId, insightId });
      await refetch();
    } catch (error) {
      console.error('Failed to apply insight:', error);
    }
  };

  const handleDismissInsight = async (insightId: string) => {
    if (!tenantId) return;
    try {
      await dismissMutation.mutateAsync({ tenantId, insightId });
      await refetch();
    } catch (error) {
      console.error('Failed to dismiss insight:', error);
    }
  };

  /**
   * Get translated description for an insight
   * Uses reasoning_data if available, otherwise falls back to description field
   */
  const getInsightDescription = (insight: AIInsight): string => {
    if (insight.reasoning_data?.type) {
      // Determine the category prefix based on source
      let category = 'aiInsights';
      if (insight.source_model === 'safety_stock_calculator') {
        category = 'safetyStock';
      } else if (insight.source_model === 'price_forecaster') {
        category = 'priceForecaster';
      } else if (insight.source_model === 'optimization') {
        category = 'optimization';
      }

      try {
        const params = {
          ...insight.reasoning_data.parameters,
          defaultValue: insight.description || `${category}: ${insight.reasoning_data.type}`
        };
        const translated = t(`${category}.${insight.reasoning_data.type}`, params);
        return translated || insight.description || `AI Insight: ${insight.reasoning_data.type}`;
      } catch (e) {
        // Fall back to description if translation key not found
        return insight.description || 'AI Insight';
      }
    }
    return insight.description || 'AI Insight';
  };

  return (
    <AnalyticsPageLayout
      title="Inteligencia Artificial"
      description="Insights inteligentes y recomendaciones automáticas para optimizar tu panadería"
      subscriptionLoading={false}
      hasAccess={true}
      dataLoading={isLoading || applyMutation.isLoading || dismissMutation.isLoading}
      actions={[
        {
          id: 'refresh',
          label: 'Actualizar',
          icon: RefreshCw,
          onClick: handleRefresh,
          variant: 'outline',
          disabled: isLoading,
        },
        {
          id: 'export',
          label: 'Exportar',
          icon: Download,
          onClick: () => {},
          variant: 'outline',
        },
      ]}
      stats={[
        {
          title: "Total Insights",
          value: aiMetrics.totalInsights,
          icon: Brain,
          variant: "info"
        },
        {
          title: "Accionables",
          value: aiMetrics.actionableInsights,
          icon: Zap,
          variant: "success"
        },
        {
          title: "Confianza Promedio",
          value: `${aiMetrics.averageConfidence}%`,
          icon: Target,
          variant: "info"
        },
        {
          title: "Alta Prioridad",
          value: aiMetrics.highPriorityInsights,
          icon: AlertTriangle,
          variant: "error"
        },
        {
          title: "Media Prioridad",
          value: aiMetrics.mediumPriorityInsights,
          icon: TrendingUp,
          variant: "warning"
        },
        {
          title: "Baja Prioridad",
          value: aiMetrics.lowPriorityInsights,
          icon: Lightbulb,
          variant: "success"
        }
      ]}
      statsColumns={6}
      showMobileNotice={true}
    >
      {/* Category Filter */}
      <Card className="p-6 bg-gradient-to-br from-[var(--bg-primary)] to-[var(--bg-secondary)]">
        <h3 className="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wider mb-4">Filtrar por Categoría</h3>
        <div className="flex flex-wrap gap-3">
          {categories.map((category) => (
            <button
              key={category.value}
              onClick={() => setSelectedCategory(category.value)}
              className={`px-5 py-2.5 rounded-full text-sm font-semibold transition-all transform hover:scale-105 ${
                selectedCategory === category.value
                  ? 'bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-light)] text-white shadow-lg'
                  : 'bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:bg-[var(--bg-quaternary)] border border-[var(--border-primary)]'
              }`}
            >
              {category.label} <span className="ml-1 opacity-75">({category.count})</span>
            </button>
          ))}
        </div>
      </Card>

      {/* Insights List */}
      <div className="space-y-4">
        {filteredInsights.map((insight) => (
          <Card key={insight.id} className="p-6 hover:shadow-lg transition-shadow border-l-4" style={{borderLeftColor: insight.priority === 'high' ? 'var(--color-error)' : insight.priority === 'medium' ? 'var(--color-warning)' : 'var(--color-success)'}}>
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center space-x-3 mb-4">
                  <div className={`p-3 rounded-xl ${getTypeColor(insight.type)} shadow-sm`}>
                    {getTypeIcon(insight.type)}
                  </div>
                  <div className="flex flex-wrap items-center gap-2">
                    <Badge variant={getPriorityColor(insight.priority)}>
                      {insight.priority === 'high' ? '🔴 Alta' : insight.priority === 'medium' ? '🟡 Media' : '🟢 Baja'} Prioridad
                    </Badge>
                    <Badge variant="secondary">
                      <Target className="w-3 h-3 mr-1" />
                      {insight.confidence}% confianza
                    </Badge>
                    {insight.actionable && (
                      <Badge variant="primary">
                        <Zap className="w-3 h-3 mr-1" />
                        Accionable
                      </Badge>
                    )}
                  </div>
                </div>

                <h3 className="text-xl font-bold text-[var(--text-primary)] mb-2">{insight.title}</h3>
                <p className="text-[var(--text-secondary)] leading-relaxed mb-4">{getInsightDescription(insight)}</p>

                {/* Impact */}
                {insight.impact_value && insight.impact_type && (
                  <div className="mb-4 p-3 bg-[var(--color-success)]/10 border border-[var(--color-success)]/20 rounded-lg">
                    <p className="text-sm font-medium text-[var(--color-success)]">
                      💰 Impacto: {insight.impact_type.replace(/_/g, ' ')} - {insight.impact_value} {insight.impact_unit || ''}
                    </p>
                  </div>
                )}

                {/* Recommendation */}
                {insight.recommendation_actions && insight.recommendation_actions.length > 0 && (
                  <div className="mb-4 p-4 bg-[var(--color-primary)]/5 border border-[var(--color-primary)]/20 rounded-lg">
                    <div className="flex items-start gap-2 mb-2">
                      <Lightbulb className="w-5 h-5 text-[var(--color-primary)] flex-shrink-0 mt-0.5" />
                      <h4 className="text-sm font-semibold text-[var(--text-primary)]">Recomendaciones</h4>
                    </div>
                    <ul className="space-y-2 ml-7">
                      {insight.recommendation_actions.map((action, idx) => (
                        <li key={idx} className="text-sm text-[var(--text-secondary)] flex items-start gap-2">
                          <span className="text-[var(--color-primary)] flex-shrink-0">•</span>
                          <span>{action.label || action.action}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}

                {/* Metrics - Only show non-redundant metrics */}
                {insight.metrics_json && Object.keys(insight.metrics_json).length > 0 && (
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                    {Object.entries(insight.metrics_json)
                      .filter(([key]) => !['pattern', 'recommendation'].includes(key)) // Filter out already displayed data
                      .map(([key, value]) => {
                        // Format the value for display
                        let displayValue: string;
                        if (typeof value === 'object' && value !== null) {
                          // For objects, try to display them nicely
                          if (Object.keys(value).length < 5) {
                            displayValue = Object.entries(value)
                              .map(([k, v]) => `${k}: ${v}`)
                              .join(', ');
                          } else {
                            displayValue = JSON.stringify(value, null, 2);
                          }
                        } else if (typeof value === 'number') {
                          displayValue = value.toLocaleString();
                        } else {
                          displayValue = String(value);
                        }

                        return (
                          <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(/_/g, ' ').replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())}
                            </p>
                            <p className="text-sm font-semibold text-[var(--text-primary)] break-words">
                              {displayValue}
                            </p>
                          </div>
                        );
                      })}
                  </div>
                )}

                <div className="flex items-center justify-between">
                  <p className="text-xs text-[var(--text-tertiary)]">{insight.created_at ? new Date(insight.created_at).toLocaleString() : ''}</p>
                  {insight.actionable && (
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        onClick={() => handleApplyInsight(insight.id)}
                        disabled={applyMutation.isLoading}
                      >
                        Aplicar Recomendación
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleDismissInsight(insight.id)}
                        disabled={dismissMutation.isLoading}
                      >
                        Descartar
                      </Button>
                    </div>
                  )}
                </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>
      )}
    </AnalyticsPageLayout>
  );
};

export default AIInsightsPage;
