import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import {
  Brain,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  Target,
  Lightbulb,
  BarChart3,
  Zap,
  Clock,
  DollarSign,
  Users,
  Package
} from 'lucide-react';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useProductionDashboard } from '../../../api';

export interface AIInsight {
  id: string;
  type: 'optimization' | 'prediction' | 'alert' | 'recommendation';
  title: string;
  description: string;
  impact: 'high' | 'medium' | 'low';
  category: 'cost' | 'quality' | 'efficiency' | 'demand' | 'maintenance';
  confidence: number;
  potentialSavings?: number;
  timeToImplement?: string;
  actions: Array<{
    label: string;
    action: string;
  }>;
  data?: {
    current: number;
    predicted: number;
    unit: string;
  };
  createdAt: string;
}

export interface AIInsightsWidgetProps {
  className?: string;
  insights?: AIInsight[];
  onViewInsight?: (insightId: string) => void;
  onImplement?: (insightId: string, actionId: string) => void;
  onViewAll?: () => void;
}

const AIInsightsWidget: React.FC<AIInsightsWidgetProps> = ({
  className,
  insights,
  onViewInsight,
  onImplement,
  onViewAll
}) => {
  const { t } = useTranslation();
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  const {
    data: dashboardData,
    isLoading,
    error
  } = useProductionDashboard(tenantId);

  const aiInsights = useMemo((): AIInsight[] => {
    if (insights) return insights;

    // Mock AI-generated insights for demonstration
    return [
      {
        id: '1',
        type: 'optimization',
        title: t('ai.insights.reduce_energy_costs', 'Reduce Energy Costs by 15%'),
        description: t('ai.insights.energy_description', 'Adjust oven schedules to use off-peak electricity rates. Estimated savings: ¬45/day'),
        impact: 'high',
        category: 'cost',
        confidence: 87,
        potentialSavings: 1350,
        timeToImplement: '2 days',
        actions: [
          { label: t('ai.actions.schedule_optimization', 'Optimize Schedule'), action: 'optimize_schedule' },
          { label: t('ai.actions.view_details', 'View Details'), action: 'view_details' }
        ],
        data: {
          current: 95.2,
          predicted: 81.0,
          unit: '¬/day'
        },
        createdAt: '2024-01-23T08:30:00Z'
      },
      {
        id: '2',
        type: 'prediction',
        title: t('ai.insights.demand_increase', 'Croissant Demand Surge Predicted'),
        description: t('ai.insights.demand_description', 'Weather and event data suggest 40% increase in croissant demand this weekend'),
        impact: 'high',
        category: 'demand',
        confidence: 92,
        timeToImplement: '1 day',
        actions: [
          { label: t('ai.actions.increase_production', 'Increase Production'), action: 'adjust_production' },
          { label: t('ai.actions.order_ingredients', 'Order Ingredients'), action: 'order_ingredients' }
        ],
        data: {
          current: 150,
          predicted: 210,
          unit: 'units/day'
        },
        createdAt: '2024-01-23T07:15:00Z'
      },
      {
        id: '3',
        type: 'alert',
        title: t('ai.insights.quality_decline', 'Quality Score Decline Detected'),
        description: t('ai.insights.quality_description', 'Bread quality has decreased by 8% over the last 3 days. Check flour moisture levels'),
        impact: 'medium',
        category: 'quality',
        confidence: 78,
        timeToImplement: '4 hours',
        actions: [
          { label: t('ai.actions.check_ingredients', 'Check Ingredients'), action: 'quality_check' },
          { label: t('ai.actions.adjust_recipe', 'Adjust Recipe'), action: 'recipe_adjustment' }
        ],
        data: {
          current: 8.2,
          predicted: 7.5,
          unit: 'score'
        },
        createdAt: '2024-01-23T06:45:00Z'
      },
      {
        id: '4',
        type: 'recommendation',
        title: t('ai.insights.maintenance_due', 'Preventive Maintenance Recommended'),
        description: t('ai.insights.maintenance_description', 'Mixer #2 showing early wear patterns. Schedule maintenance to prevent breakdown'),
        impact: 'medium',
        category: 'maintenance',
        confidence: 85,
        potentialSavings: 800,
        timeToImplement: '1 week',
        actions: [
          { label: t('ai.actions.schedule_maintenance', 'Schedule Maintenance'), action: 'schedule_maintenance' },
          { label: t('ai.actions.view_equipment', 'View Equipment'), action: 'view_equipment' }
        ],
        createdAt: '2024-01-22T14:20:00Z'
      }
    ];
  }, [insights, t]);

  const getInsightConfig = (type: AIInsight['type']) => {
    const configs = {
      optimization: {
        color: 'success' as const,
        icon: TrendingUp,
        bgColor: 'bg-green-50 dark:bg-green-900/20',
        borderColor: 'border-green-200 dark:border-green-800'
      },
      prediction: {
        color: 'info' as const,
        icon: BarChart3,
        bgColor: 'bg-blue-50 dark:bg-blue-900/20',
        borderColor: 'border-blue-200 dark:border-blue-800'
      },
      alert: {
        color: 'warning' as const,
        icon: AlertTriangle,
        bgColor: 'bg-orange-50 dark:bg-orange-900/20',
        borderColor: 'border-orange-200 dark:border-orange-800'
      },
      recommendation: {
        color: 'default' as const,
        icon: Lightbulb,
        bgColor: 'bg-purple-50 dark:bg-purple-900/20',
        borderColor: 'border-purple-200 dark:border-purple-800'
      }
    };
    return configs[type];
  };

  const getCategoryIcon = (category: AIInsight['category']) => {
    const icons = {
      cost: DollarSign,
      quality: Target,
      efficiency: Zap,
      demand: BarChart3,
      maintenance: Users
    };
    return icons[category] || Package;
  };

  const getImpactColor = (impact: AIInsight['impact']) => {
    const colors = {
      high: 'text-red-600',
      medium: 'text-orange-600',
      low: 'text-green-600'
    };
    return colors[impact];
  };

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

  const highImpactInsights = aiInsights.filter(i => i.impact === 'high').length;
  const totalPotentialSavings = aiInsights.reduce((sum, i) => sum + (i.potentialSavings || 0), 0);
  const avgConfidence = aiInsights.reduce((sum, i) => sum + i.confidence, 0) / aiInsights.length;

  if (isLoading) {
    return (
      <Card className={className}>
        <CardHeader>
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">
            {t('ai.title', 'AI Insights')}
          </h3>
        </CardHeader>
        <CardBody>
          <div className="animate-pulse space-y-4">
            <div className="grid grid-cols-3 gap-4">
              <div className="h-12 bg-[var(--bg-secondary)] rounded"></div>
              <div className="h-12 bg-[var(--bg-secondary)] rounded"></div>
              <div className="h-12 bg-[var(--bg-secondary)] rounded"></div>
            </div>
            <div className="space-y-3">
              <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
              <div className="h-20 bg-[var(--bg-secondary)] rounded"></div>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={className}>
        <CardBody className="text-center py-8">
          <Brain className="w-12 h-12 text-[var(--text-tertiary)] mx-auto mb-4" />
          <p className="text-[var(--text-secondary)]">
            {t('ai.error', 'AI insights temporarily unavailable')}
          </p>
        </CardBody>
      </Card>
    );
  }

  return (
    <Card className={className}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Brain className="w-5 h-5 text-[var(--color-primary)]" />
            <div>
              <h3 className="text-lg font-semibold text-[var(--text-primary)]">
                {t('ai.title', 'AI Insights')}
              </h3>
              <p className="text-sm text-[var(--text-secondary)]">
                {t('ai.subtitle', 'AI-powered recommendations and predictions')}
              </p>
            </div>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={onViewAll}
          >
            {t('common.view_all', 'View All')}
          </Button>
        </div>
      </CardHeader>

      <CardBody className="space-y-6">
        {/* Summary Stats */}
        <div className="grid grid-cols-3 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-red-600">
              {highImpactInsights}
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('ai.high_impact', 'High Impact')}
            </div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {totalPotentialSavings > 0 ? formatCurrency(totalPotentialSavings) : ''}
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('ai.potential_savings', 'Potential Savings')}
            </div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-[var(--color-primary)]">
              {avgConfidence.toFixed(0)}%
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              {t('ai.confidence', 'Avg Confidence')}
            </div>
          </div>
        </div>

        {/* Insights List */}
        <div className="space-y-3">
          {aiInsights.slice(0, 3).map((insight) => {
            const config = getInsightConfig(insight.type);
            const CategoryIcon = getCategoryIcon(insight.category);
            const TypeIcon = config.icon;

            return (
              <div
                key={insight.id}
                className={`p-4 rounded-lg border ${config.bgColor} ${config.borderColor} hover:shadow-sm transition-all cursor-pointer`}
                onClick={() => onViewInsight?.(insight.id)}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-start space-x-3 flex-1">
                    <div className="flex items-center space-x-1">
                      <TypeIcon className="w-5 h-5 text-[var(--color-primary)]" />
                      <CategoryIcon className="w-4 h-4 text-[var(--text-tertiary)]" />
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <h4 className="font-medium text-[var(--text-primary)] text-sm">
                          {insight.title}
                        </h4>
                        <Badge variant={config.color} size="sm">
                          {insight.confidence}%
                        </Badge>
                      </div>
                      <p className="text-sm text-[var(--text-secondary)] mb-2">
                        {insight.description}
                      </p>
                      <div className="flex items-center space-x-4 text-xs text-[var(--text-tertiary)]">
                        <span className={`font-medium ${getImpactColor(insight.impact)}`}>
                          {insight.impact.toUpperCase()} {t('ai.impact', 'IMPACT')}
                        </span>
                        {insight.timeToImplement && (
                          <span className="flex items-center space-x-1">
                            <Clock className="w-3 h-3" />
                            <span>{insight.timeToImplement}</span>
                          </span>
                        )}
                        {insight.potentialSavings && (
                          <span className="font-medium text-green-600">
                            {formatCurrency(insight.potentialSavings)}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                  {insight.data && (
                    <div className="text-right ml-3">
                      <div className="text-sm font-medium text-[var(--text-primary)]">
                        {insight.data.current} ’ {insight.data.predicted}
                      </div>
                      <div className="text-xs text-[var(--text-secondary)]">
                        {insight.data.unit}
                      </div>
                    </div>
                  )}
                </div>

                {/* Action buttons */}
                <div className="flex items-center space-x-2 mt-3 pt-3 border-t border-[var(--border-primary)]">
                  {insight.actions.slice(0, 2).map((action, index) => (
                    <Button
                      key={index}
                      variant={index === 0 ? "primary" : "outline"}
                      size="xs"
                      onClick={(e) => {
                        e.stopPropagation();
                        onImplement?.(insight.id, action.action);
                      }}
                    >
                      {action.label}
                    </Button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        {/* AI Status */}
        <div className="flex items-center justify-between pt-4 border-t border-[var(--border-primary)]">
          <div className="flex items-center space-x-2">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            <span className="text-sm text-[var(--text-secondary)]">
              {t('ai.status.active', 'AI monitoring active')}
            </span>
          </div>
          <div className="text-xs text-[var(--text-tertiary)]">
            {t('ai.last_updated', 'Updated 5m ago')}
          </div>
        </div>
      </CardBody>
    </Card>
  );
};

export default AIInsightsWidget;