import React from 'react';
import { TrendingUp, Clock, AlertTriangle, BarChart3 } from 'lucide-react';
import { Badge } from '../../ui/Badge';
import type { AlertAnalytics } from '../../../hooks/useAlertAnalytics';

export interface AlertTrendsProps {
  analytics: AlertAnalytics | undefined;
  className?: string;
}

const AlertTrends: React.FC<AlertTrendsProps> = ({ analytics, className }) => {
  // Debug logging
  console.log('[AlertTrends] Received analytics:', analytics);
  console.log('[AlertTrends] Has trends?', analytics?.trends);
  console.log('[AlertTrends] Is array?', Array.isArray(analytics?.trends));

  // Safety check: handle undefined or missing analytics data
  if (!analytics || !analytics.trends || !Array.isArray(analytics.trends)) {
    console.log('[AlertTrends] Showing loading state');
    return (
      <div className={`bg-[var(--bg-secondary)] rounded-lg p-4 border border-[var(--border-primary)] ${className}`}>
        <div className="flex items-center justify-center h-32 text-[var(--text-secondary)]">
          Cargando analíticas...
        </div>
      </div>
    );
  }

  console.log('[AlertTrends] Rendering analytics with', analytics.trends.length, 'trends');

  // Ensure we have valid trend data
  const validTrends = analytics.trends.filter(t => t && typeof t.count === 'number');
  const maxCount = validTrends.length > 0 ? Math.max(...validTrends.map(t => t.count), 1) : 1;

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    if (date.toDateString() === today.toDateString()) {
      return 'Hoy';
    }
    if (date.toDateString() === yesterday.toDateString()) {
      return 'Ayer';
    }
    return date.toLocaleDateString('es-ES', { weekday: 'short', day: 'numeric' });
  };

  return (
    <div className={`bg-[var(--bg-secondary)] rounded-lg p-4 border border-[var(--border-primary)] ${className}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <BarChart3 className="w-5 h-5 text-[var(--color-primary)]" />
          <h3 className="font-semibold text-[var(--text-primary)]">
            Tendencias (7 días)
          </h3>
        </div>
        <Badge variant="secondary" size="sm">
          {analytics.totalAlerts} total
        </Badge>
      </div>

      {/* Chart */}
      <div className="mb-4">
        <div className="flex items-end justify-between gap-1 h-32">
          {analytics.trends.map((trend, index) => {
            const heightPercentage = maxCount > 0 ? (trend.count / maxCount) * 100 : 0;

            return (
              <div
                key={trend.date}
                className="flex-1 flex flex-col items-center gap-1"
              >
                <div className="w-full flex flex-col justify-end" style={{ height: '100px' }}>
                  {/* Bar */}
                  <div
                    className="w-full bg-gradient-to-t from-[var(--color-primary)] to-[var(--color-primary)]/60 rounded-t transition-all hover:opacity-80 cursor-pointer relative group"
                    style={{ height: `${heightPercentage}%`, minHeight: trend.count > 0 ? '4px' : '0' }}
                    title={`${trend.count} alertas`}
                  >
                    {/* Tooltip on hover */}
                    <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                      <div className="bg-[var(--text-primary)] text-white text-xs rounded px-2 py-1 whitespace-nowrap">
                        {trend.count} alertas
                        <div className="text-[10px] opacity-75">
                          🔴 {trend.urgentCount} • 🟠 {trend.highCount} • 🔵 {trend.mediumCount} • 🟢 {trend.lowCount}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Label */}
                <span className="text-[10px] text-[var(--text-secondary)] text-center">
                  {formatDate(trend.date)}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-3 pt-3 border-t border-[var(--border-primary)]">
        {/* Average Response Time */}
        <div className="flex items-center gap-2">
          <div className="p-2 bg-blue-500/10 rounded">
            <Clock className="w-4 h-4 text-blue-500" />
          </div>
          <div>
            <div className="text-xs text-[var(--text-secondary)]">Respuesta promedio</div>
            <div className="text-sm font-semibold text-[var(--text-primary)]">
              {analytics.averageResponseTime > 0 ? `${analytics.averageResponseTime} min` : 'N/A'}
            </div>
          </div>
        </div>

        {/* Daily Average */}
        <div className="flex items-center gap-2">
          <div className="p-2 bg-purple-500/10 rounded">
            <TrendingUp className="w-4 h-4 text-purple-500" />
          </div>
          <div>
            <div className="text-xs text-[var(--text-secondary)]">Promedio diario</div>
            <div className="text-sm font-semibold text-[var(--text-primary)]">
              {analytics.predictedDailyAverage} alertas
            </div>
          </div>
        </div>

        {/* Resolution Rate */}
        <div className="flex items-center gap-2">
          <div className="p-2 bg-green-500/10 rounded">
            <BarChart3 className="w-4 h-4 text-green-500" />
          </div>
          <div>
            <div className="text-xs text-[var(--text-secondary)]">Tasa de resolución</div>
            <div className="text-sm font-semibold text-[var(--text-primary)]">
              {analytics.resolutionRate}%
            </div>
          </div>
        </div>

        {/* Busiest Day */}
        <div className="flex items-center gap-2">
          <div className="p-2 bg-orange-500/10 rounded">
            <AlertTriangle className="w-4 h-4 text-orange-500" />
          </div>
          <div>
            <div className="text-xs text-[var(--text-secondary)]">Día más activo</div>
            <div className="text-sm font-semibold text-[var(--text-primary)]">
              {analytics.busiestDay}
            </div>
          </div>
        </div>
      </div>

      {/* Top Categories */}
      {analytics.topCategories.length > 0 && (
        <div className="mt-3 pt-3 border-t border-[var(--border-primary)]">
          <div className="text-xs font-semibold text-[var(--text-secondary)] mb-2">
            Categorías principales
          </div>
          <div className="flex flex-wrap gap-2">
            {analytics.topCategories.map((cat) => (
              <Badge key={cat.category} variant="secondary" size="sm">
                {cat.count} ({cat.percentage}%)
              </Badge>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default AlertTrends;
