/**
 * ConfidenceMeter Component
 * Advanced confidence indicator with uncertainty visualization
 * OQI-006: Senales ML
 */

import React, { useMemo } from 'react';
import {
  Gauge,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  CheckCircle,
  Info,
  ChevronDown,
  ChevronUp,
  Zap,
  BarChart3,
  Users,
} from 'lucide-react';

export interface ConfidenceData {
  overall: number;
  modelAgreement: number;
  trend: 'up' | 'down' | 'stable';
  trendChange: number;
  modelVotes: {
    bullish: number;
    bearish: number;
    neutral: number;
  };
  featureImportance?: {
    feature: string;
    contribution: number;
    direction: 'positive' | 'negative';
  }[];
  historicalConfidence?: { timestamp: string; value: number }[];
  volatility?: number;
}

interface ConfidenceMeterProps {
  confidence: ConfidenceData;
  direction?: 'BUY' | 'SELL' | 'NEUTRAL';
  symbol?: string;
  showDetails?: boolean;
  onToggleDetails?: () => void;
  compact?: boolean;
}

const ConfidenceMeter: React.FC<ConfidenceMeterProps> = ({
  confidence,
  direction = 'NEUTRAL',
  symbol,
  showDetails = false,
  onToggleDetails,
  compact = false,
}) => {
  const [isExpanded, setIsExpanded] = React.useState(showDetails);

  // Get confidence zone
  const getConfidenceZone = (value: number) => {
    if (value >= 70) return { label: 'High', color: 'green' };
    if (value >= 40) return { label: 'Medium', color: 'yellow' };
    return { label: 'Low', color: 'red' };
  };

  const zone = useMemo(() => getConfidenceZone(confidence.overall), [confidence.overall]);

  const getZoneColor = (color: string) => {
    switch (color) {
      case 'green':
        return 'text-green-400 bg-green-500/20 border-green-500/30';
      case 'yellow':
        return 'text-yellow-400 bg-yellow-500/20 border-yellow-500/30';
      case 'red':
        return 'text-red-400 bg-red-500/20 border-red-500/30';
      default:
        return 'text-gray-400 bg-gray-500/20 border-gray-500/30';
    }
  };

  const getGaugeBackground = (value: number) => {
    const percentage = Math.min(Math.max(value, 0), 100);
    const color =
      percentage >= 70
        ? 'from-green-600 to-green-400'
        : percentage >= 40
        ? 'from-yellow-600 to-yellow-400'
        : 'from-red-600 to-red-400';
    return `bg-gradient-to-r ${color}`;
  };

  const totalVotes = confidence.modelVotes.bullish + confidence.modelVotes.bearish + confidence.modelVotes.neutral;

  const formatPercent = (value: number) => `${value.toFixed(1)}%`;

  if (compact) {
    return (
      <div className="flex items-center gap-3 p-3 bg-gray-800/50 rounded-lg border border-gray-700">
        <div className={`p-2 rounded-lg ${getZoneColor(zone.color)}`}>
          <Gauge className="w-5 h-5" />
        </div>
        <div className="flex-1">
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-400">Confidence</span>
            <span className={`text-lg font-bold ${getZoneColor(zone.color).split(' ')[0]}`}>
              {confidence.overall.toFixed(0)}%
            </span>
          </div>
          <div className="h-1.5 bg-gray-700 rounded-full mt-1 overflow-hidden">
            <div className={`h-full rounded-full ${getGaugeBackground(confidence.overall)}`} style={{ width: `${confidence.overall}%` }} />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-gray-800/50 rounded-xl border border-gray-700 p-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${getZoneColor(zone.color)}`}>
            <Gauge className="w-5 h-5" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Confidence Meter</h3>
            {symbol && <p className="text-xs text-gray-500">{symbol}</p>}
          </div>
        </div>
        <div className={`px-3 py-1 rounded-full text-xs font-medium ${getZoneColor(zone.color)}`}>
          {zone.label} Confidence
        </div>
      </div>

      {/* Main Gauge */}
      <div className="mb-6">
        <div className="flex items-end justify-between mb-2">
          <span className="text-4xl font-bold text-white">{confidence.overall.toFixed(0)}%</span>
          <div className="flex items-center gap-1">
            {confidence.trend === 'up' ? (
              <TrendingUp className="w-4 h-4 text-green-400" />
            ) : confidence.trend === 'down' ? (
              <TrendingDown className="w-4 h-4 text-red-400" />
            ) : (
              <div className="w-4 h-0.5 bg-gray-500" />
            )}
            <span
              className={`text-sm ${
                confidence.trend === 'up'
                  ? 'text-green-400'
                  : confidence.trend === 'down'
                  ? 'text-red-400'
                  : 'text-gray-400'
              }`}
            >
              {confidence.trendChange > 0 ? '+' : ''}
              {confidence.trendChange.toFixed(1)}%
            </span>
          </div>
        </div>

        {/* Gauge Bar */}
        <div className="relative h-4 bg-gray-700 rounded-full overflow-hidden">
          {/* Zone indicators */}
          <div className="absolute inset-0 flex">
            <div className="w-[40%] bg-red-500/20 border-r border-gray-600" />
            <div className="w-[30%] bg-yellow-500/20 border-r border-gray-600" />
            <div className="w-[30%] bg-green-500/20" />
          </div>
          {/* Current value */}
          <div
            className={`absolute h-full ${getGaugeBackground(confidence.overall)} transition-all duration-500`}
            style={{ width: `${confidence.overall}%` }}
          />
          {/* Marker */}
          <div
            className="absolute top-0 bottom-0 w-1 bg-white shadow-lg"
            style={{ left: `${confidence.overall}%`, transform: 'translateX(-50%)' }}
          />
        </div>

        {/* Zone labels */}
        <div className="flex justify-between mt-1 text-xs text-gray-500">
          <span>Low (0-40%)</span>
          <span>Medium (40-70%)</span>
          <span>High (70-100%)</span>
        </div>
      </div>

      {/* Model Agreement */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div className="p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center gap-2 mb-2">
            <Users className="w-4 h-4 text-blue-400" />
            <span className="text-sm text-gray-400">Model Agreement</span>
          </div>
          <div className="text-xl font-bold text-white">{formatPercent(confidence.modelAgreement)}</div>
        </div>

        {confidence.volatility !== undefined && (
          <div className="p-3 bg-gray-900/50 rounded-lg">
            <div className="flex items-center gap-2 mb-2">
              <Zap className="w-4 h-4 text-yellow-400" />
              <span className="text-sm text-gray-400">Volatility Risk</span>
            </div>
            <div
              className={`text-xl font-bold ${
                confidence.volatility >= 70 ? 'text-red-400' : confidence.volatility >= 40 ? 'text-yellow-400' : 'text-green-400'
              }`}
            >
              {confidence.volatility.toFixed(0)}%
            </div>
          </div>
        )}
      </div>

      {/* Model Votes */}
      <div className="mb-4">
        <div className="text-sm text-gray-400 mb-2">Model Votes ({totalVotes} models)</div>
        <div className="flex h-3 rounded-full overflow-hidden bg-gray-700">
          <div
            className="bg-green-500 transition-all"
            style={{ width: `${(confidence.modelVotes.bullish / totalVotes) * 100}%` }}
            title={`Bullish: ${confidence.modelVotes.bullish}`}
          />
          <div
            className="bg-gray-500 transition-all"
            style={{ width: `${(confidence.modelVotes.neutral / totalVotes) * 100}%` }}
            title={`Neutral: ${confidence.modelVotes.neutral}`}
          />
          <div
            className="bg-red-500 transition-all"
            style={{ width: `${(confidence.modelVotes.bearish / totalVotes) * 100}%` }}
            title={`Bearish: ${confidence.modelVotes.bearish}`}
          />
        </div>
        <div className="flex justify-between mt-1 text-xs">
          <span className="text-green-400">{confidence.modelVotes.bullish} Bullish</span>
          <span className="text-gray-400">{confidence.modelVotes.neutral} Neutral</span>
          <span className="text-red-400">{confidence.modelVotes.bearish} Bearish</span>
        </div>
      </div>

      {/* Feature Importance (Expandable) */}
      {confidence.featureImportance && confidence.featureImportance.length > 0 && (
        <div>
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="flex items-center justify-between w-full p-2 text-sm text-gray-400 hover:bg-gray-800 rounded-lg transition-colors"
          >
            <div className="flex items-center gap-2">
              <BarChart3 className="w-4 h-4" />
              <span>Feature Importance</span>
            </div>
            {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
          </button>

          {isExpanded && (
            <div className="mt-2 space-y-2">
              {confidence.featureImportance.map((feature, idx) => (
                <div key={idx} className="flex items-center justify-between p-2 bg-gray-900/50 rounded">
                  <div className="flex items-center gap-2">
                    {feature.direction === 'positive' ? (
                      <CheckCircle className="w-3 h-3 text-green-400" />
                    ) : (
                      <AlertTriangle className="w-3 h-3 text-red-400" />
                    )}
                    <span className="text-sm text-gray-300">{feature.feature}</span>
                  </div>
                  <div
                    className={`text-sm font-medium ${
                      feature.direction === 'positive' ? 'text-green-400' : 'text-red-400'
                    }`}
                  >
                    {feature.direction === 'positive' ? '+' : '-'}
                    {Math.abs(feature.contribution).toFixed(1)}%
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Risk Advisory */}
      {confidence.overall < 40 && (
        <div className="mt-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg flex items-start gap-2">
          <AlertTriangle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
          <div>
            <p className="text-red-400 font-medium text-sm">Low Confidence Warning</p>
            <p className="text-xs text-gray-400 mt-1">
              This signal has low model agreement. Consider waiting for stronger confirmation.
            </p>
          </div>
        </div>
      )}
    </div>
  );
};

export default ConfidenceMeter;
