// ================================================================
// frontend/src/components/domain/dashboard/TrendVisualizationComponent.tsx
// ================================================================
/**
 * Trend Visualization Component
 *
 * Displays visual trend indicators for TREND_WARNING type alerts.
 * Shows historical comparison with simple sparkline/arrow indicators.
 *
 * Design: Lightweight, inline trend indicators with color coding
 */

import React from 'react';
import { TrendingUp, TrendingDown, Minus, AlertTriangle } from 'lucide-react';
import { Badge } from '../../ui/Badge';
import { useTranslation } from 'react-i18next';

export interface TrendData {
  direction: 'increasing' | 'decreasing' | 'stable';
  percentageChange?: number;
  historicalComparison?: string;
  dataPoints?: number[];
  threshold?: number;
  current?: number;
}

export interface TrendVisualizationProps {
  trend: TrendData;
  label?: string;
  showSparkline?: boolean;
  size?: 'sm' | 'md' | 'lg';
  className?: string;
}

export function TrendVisualizationComponent({
  trend,
  label,
  showSparkline = false,
  size = 'md',
  className = '',
}: TrendVisualizationProps) {
  const { t } = useTranslation('alerts');

  const getTrendIcon = () => {
    switch (trend.direction) {
      case 'increasing':
        return TrendingUp;
      case 'decreasing':
        return TrendingDown;
      case 'stable':
        return Minus;
    }
  };

  const getTrendColor = () => {
    switch (trend.direction) {
      case 'increasing':
        return 'var(--color-error-500)';
      case 'decreasing':
        return 'var(--color-success-500)';
      case 'stable':
        return 'var(--text-tertiary)';
    }
  };

  const getTrendBadgeVariant = (): 'error' | 'success' | 'secondary' => {
    switch (trend.direction) {
      case 'increasing':
        return 'error';
      case 'decreasing':
        return 'success';
      case 'stable':
        return 'secondary';
    }
  };

  const getTrendLabel = () => {
    if (trend.percentageChange !== undefined) {
      const sign = trend.percentageChange > 0 ? '+' : '';
      return `${sign}${trend.percentageChange.toFixed(1)}%`;
    }
    return trend.direction.charAt(0).toUpperCase() + trend.direction.slice(1);
  };

  const isNearThreshold = trend.threshold !== undefined && trend.current !== undefined
    ? Math.abs(trend.current - trend.threshold) / trend.threshold < 0.1
    : false;

  const TrendIcon = getTrendIcon();
  const trendColor = getTrendColor();

  const iconSizes = {
    sm: 'w-3 h-3',
    md: 'w-4 h-4',
    lg: 'w-5 h-5',
  };

  return (
    <div className={`inline-flex items-center gap-2 ${className}`}>
      {/* Trend Indicator */}
      <div className="flex items-center gap-1.5">
        <TrendIcon
          className={iconSizes[size]}
          style={{ color: trendColor }}
        />
        <Badge variant={getTrendBadgeVariant()} size={size === 'sm' ? 'sm' : 'md'}>
          {getTrendLabel()}
        </Badge>
      </div>

      {/* Optional Label */}
      {label && (
        <span
          className={`font-medium ${size === 'sm' ? 'text-xs' : size === 'lg' ? 'text-base' : 'text-sm'}`}
          style={{ color: 'var(--text-secondary)' }}
        >
          {label}
        </span>
      )}

      {/* Threshold Warning */}
      {isNearThreshold && (
        <div className="flex items-center gap-1">
          <AlertTriangle className="w-3 h-3" style={{ color: 'var(--color-warning-500)' }} />
          <span className="text-xs font-medium" style={{ color: 'var(--color-warning-600)' }}>
            {t('trend.near_threshold', 'Near threshold')}
          </span>
        </div>
      )}

      {/* Sparkline (Simple Mini Chart) */}
      {showSparkline && trend.dataPoints && trend.dataPoints.length > 0 && (
        <div className="flex items-end gap-0.5 h-6">
          {trend.dataPoints.slice(-8).map((value, idx) => {
            const maxValue = Math.max(...trend.dataPoints!);
            const heightPercent = (value / maxValue) * 100;

            return (
              <div
                key={idx}
                className="w-1 rounded-t transition-all"
                style={{
                  height: `${heightPercent}%`,
                  backgroundColor: trendColor,
                  opacity: 0.3 + (idx / trend.dataPoints!.length) * 0.7,
                }}
                title={`${value}`}
              />
            );
          })}
        </div>
      )}

      {/* Historical Comparison Text */}
      {trend.historicalComparison && (
        <span
          className={`${size === 'sm' ? 'text-xs' : 'text-sm'}`}
          style={{ color: 'var(--text-tertiary)' }}
        >
          {trend.historicalComparison}
        </span>
      )}
    </div>
  );
}

/**
 * Compact version for inline use in alert cards
 */
export function TrendVisualizationInline({ trend }: { trend: TrendData }) {
  const TrendIcon = trend.direction === 'increasing' ? TrendingUp
    : trend.direction === 'decreasing' ? TrendingDown
    : Minus;

  const color = trend.direction === 'increasing' ? 'var(--color-error-500)'
    : trend.direction === 'decreasing' ? 'var(--color-success-500)'
    : 'var(--text-tertiary)';

  return (
    <div className="inline-flex items-center gap-1">
      <TrendIcon className="w-3 h-3" style={{ color }} />
      {trend.percentageChange !== undefined && (
        <span className="text-xs font-semibold" style={{ color }}>
          {trend.percentageChange > 0 ? '+' : ''}{trend.percentageChange.toFixed(1)}%
        </span>
      )}
    </div>
  );
}
