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 { useReasoningTranslation } from '../../../../hooks/useReasoningTranslation';

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

  // Fetch real insights from API
  const { data: insightsData, isLoading, refetch } = useAIInsights(
    tenantId || '',
    {
      status: 'active',
      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?.insights_by_category?.production || 0 },
    { value: 'sales', label: 'Ventas', count: stats?.insights_by_category?.sales || 0 },
    { value: 'demand', label: 'Pronósticos', count: stats?.insights_by_category?.demand || 0 },
    { value: 'inventory', label: 'Inventario', count: stats?.insights_by_category?.inventory || 0 },
    { value: 'procurement', label: 'Compras', count: stats?.insights_by_category?.procurement || 0 },
  ];

  const aiMetrics = {
    totalInsights: stats?.total_insights || 0,
    actionableInsights: stats?.actionable_insights || 0,
    averageConfidence: stats?.avg_confidence ? Math.round(stats.avg_confidence) : 0,
    highPriorityInsights: stats?.insights_by_priority?.high || stats?.insights_by_priority?.urgent || 0,
    mediumPriorityInsights: stats?.insights_by_priority?.medium || 0,
    lowPriorityInsights: stats?.insights_by_priority?.low || 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">
        <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="secondary">{insight.confidence}% confianza</Badge>
                    {insight.actionable && (
                      <Badge variant="primary">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">{getInsightDescription(insight)}</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 && (
                    <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;
