/**
 * RiskAnalysisPanel Component
 * Display comprehensive risk metrics and analysis for investment accounts
 * Epic: OQI-004 Cuentas de Inversion
 */

import React, { useMemo } from 'react';
import {
  Shield,
  AlertTriangle,
  TrendingDown,
  Activity,
  BarChart3,
  Target,
  Info,
  ChevronRight,
  ArrowUpRight,
  ArrowDownRight,
} from 'lucide-react';

// Types
export interface RiskMetrics {
  var95: number;           // Value at Risk 95%
  var99: number;           // Value at Risk 99%
  cvar: number;            // Conditional VaR (Expected Shortfall)
  sharpeRatio: number;     // Risk-adjusted return
  sortinoRatio: number;    // Downside risk-adjusted return
  maxDrawdown: number;     // Maximum drawdown percentage
  maxDrawdownDuration: number; // Days in drawdown
  beta: number;            // Market correlation
  alpha: number;           // Excess return over benchmark
  volatility: number;      // Standard deviation of returns
  downsideDeviation: number;
  calmarRatio: number;     // Return / Max Drawdown
}

export interface RiskScore {
  overall: number;         // 0-100
  marketRisk: number;
  liquidityRisk: number;
  operationalRisk: number;
  concentrationRisk: number;
}

export interface RiskRecommendation {
  id: string;
  type: 'warning' | 'suggestion' | 'info';
  title: string;
  description: string;
  action?: string;
}

export interface RiskAnalysisPanelProps {
  accountId: string;
  accountName: string;
  metrics: RiskMetrics;
  score: RiskScore;
  recommendations?: RiskRecommendation[];
  benchmarkName?: string;
  period?: '1M' | '3M' | '6M' | '1Y' | 'ALL';
  onPeriodChange?: (period: string) => void;
  onViewDetails?: () => void;
  compact?: boolean;
  isLoading?: boolean;
}

const PERIOD_OPTIONS = [
  { value: '1M', label: '1 Month' },
  { value: '3M', label: '3 Months' },
  { value: '6M', label: '6 Months' },
  { value: '1Y', label: '1 Year' },
  { value: 'ALL', label: 'All Time' },
];

const RiskAnalysisPanel: React.FC<RiskAnalysisPanelProps> = ({
  accountId,
  accountName,
  metrics,
  score,
  recommendations = [],
  benchmarkName = 'S&P 500',
  period = '1Y',
  onPeriodChange,
  onViewDetails,
  compact = false,
  isLoading = false,
}) => {
  // Get risk level from score
  const getRiskLevel = (scoreValue: number): { label: string; color: string; bgColor: string } => {
    if (scoreValue <= 30) return { label: 'Low', color: 'text-emerald-400', bgColor: 'bg-emerald-400' };
    if (scoreValue <= 60) return { label: 'Moderate', color: 'text-amber-400', bgColor: 'bg-amber-400' };
    if (scoreValue <= 80) return { label: 'High', color: 'text-orange-400', bgColor: 'bg-orange-400' };
    return { label: 'Very High', color: 'text-red-400', bgColor: 'bg-red-400' };
  };

  // Get metric color based on value
  const getMetricColor = (value: number, thresholds: { good: number; warning: number }, inverse = false) => {
    if (inverse) {
      if (value <= thresholds.good) return 'text-emerald-400';
      if (value <= thresholds.warning) return 'text-amber-400';
      return 'text-red-400';
    }
    if (value >= thresholds.good) return 'text-emerald-400';
    if (value >= thresholds.warning) return 'text-amber-400';
    return 'text-red-400';
  };

  // Format percentage
  const formatPercent = (value: number, decimals = 2) => {
    return `${value >= 0 ? '+' : ''}${value.toFixed(decimals)}%`;
  };

  // Overall risk level
  const overallRisk = useMemo(() => getRiskLevel(score.overall), [score.overall]);

  // Render risk score gauge
  const renderRiskGauge = () => (
    <div className="relative w-32 h-32">
      <svg className="w-full h-full transform -rotate-90" viewBox="0 0 100 100">
        {/* Background circle */}
        <circle
          cx="50"
          cy="50"
          r="40"
          fill="none"
          stroke="currentColor"
          strokeWidth="12"
          className="text-slate-700"
        />
        {/* Score arc */}
        <circle
          cx="50"
          cy="50"
          r="40"
          fill="none"
          stroke="currentColor"
          strokeWidth="12"
          strokeDasharray={`${(score.overall / 100) * 251.2} 251.2`}
          strokeLinecap="round"
          className={overallRisk.color}
        />
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span className="text-2xl font-bold text-white">{score.overall}</span>
        <span className={`text-xs font-medium ${overallRisk.color}`}>{overallRisk.label} Risk</span>
      </div>
    </div>
  );

  // Render risk breakdown bars
  const renderRiskBreakdown = () => {
    const risks = [
      { label: 'Market Risk', value: score.marketRisk, icon: TrendingDown },
      { label: 'Liquidity Risk', value: score.liquidityRisk, icon: Activity },
      { label: 'Operational Risk', value: score.operationalRisk, icon: Shield },
      { label: 'Concentration Risk', value: score.concentrationRisk, icon: Target },
    ];

    return (
      <div className="space-y-3">
        {risks.map((risk) => {
          const level = getRiskLevel(risk.value);
          const Icon = risk.icon;
          return (
            <div key={risk.label}>
              <div className="flex items-center justify-between mb-1">
                <div className="flex items-center gap-2">
                  <Icon className="w-4 h-4 text-slate-500" />
                  <span className="text-sm text-slate-300">{risk.label}</span>
                </div>
                <span className={`text-sm font-medium ${level.color}`}>{risk.value}</span>
              </div>
              <div className="h-1.5 bg-slate-700 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all ${level.bgColor}`}
                  style={{ width: `${risk.value}%` }}
                />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // Render key metrics
  const renderKeyMetrics = () => {
    const keyMetrics = [
      {
        label: 'Sharpe Ratio',
        value: metrics.sharpeRatio.toFixed(2),
        description: 'Risk-adjusted return',
        color: getMetricColor(metrics.sharpeRatio, { good: 1.5, warning: 1.0 }),
        icon: BarChart3,
      },
      {
        label: 'Sortino Ratio',
        value: metrics.sortinoRatio.toFixed(2),
        description: 'Downside risk-adjusted',
        color: getMetricColor(metrics.sortinoRatio, { good: 2.0, warning: 1.0 }),
        icon: TrendingDown,
      },
      {
        label: 'Max Drawdown',
        value: formatPercent(-metrics.maxDrawdown),
        description: `${metrics.maxDrawdownDuration} days duration`,
        color: getMetricColor(metrics.maxDrawdown, { good: 10, warning: 20 }, true),
        icon: ArrowDownRight,
      },
      {
        label: 'Volatility',
        value: formatPercent(metrics.volatility),
        description: 'Annualized std. dev.',
        color: getMetricColor(metrics.volatility, { good: 15, warning: 25 }, true),
        icon: Activity,
      },
    ];

    return (
      <div className="grid grid-cols-2 gap-4">
        {keyMetrics.map((metric) => {
          const Icon = metric.icon;
          return (
            <div
              key={metric.label}
              className="bg-slate-800/50 rounded-lg p-3 border border-slate-700"
            >
              <div className="flex items-center gap-2 mb-2">
                <Icon className="w-4 h-4 text-slate-500" />
                <span className="text-slate-400 text-sm">{metric.label}</span>
              </div>
              <p className={`text-xl font-semibold ${metric.color}`}>{metric.value}</p>
              <p className="text-slate-500 text-xs mt-1">{metric.description}</p>
            </div>
          );
        })}
      </div>
    );
  };

  // Render VaR metrics
  const renderVaRMetrics = () => (
    <div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
      <div className="flex items-center gap-2 mb-4">
        <AlertTriangle className="w-5 h-5 text-amber-400" />
        <h4 className="text-white font-medium">Value at Risk (VaR)</h4>
        <button className="ml-auto text-slate-500 hover:text-slate-300">
          <Info className="w-4 h-4" />
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <div>
          <span className="text-slate-400 text-sm block mb-1">VaR (95%)</span>
          <span className="text-red-400 text-lg font-semibold">
            ${Math.abs(metrics.var95).toLocaleString()}
          </span>
          <span className="text-slate-500 text-xs block">
            5% chance of loss exceeding this
          </span>
        </div>
        <div>
          <span className="text-slate-400 text-sm block mb-1">VaR (99%)</span>
          <span className="text-red-400 text-lg font-semibold">
            ${Math.abs(metrics.var99).toLocaleString()}
          </span>
          <span className="text-slate-500 text-xs block">
            1% chance of loss exceeding this
          </span>
        </div>
        <div>
          <span className="text-slate-400 text-sm block mb-1">CVaR (ES)</span>
          <span className="text-red-400 text-lg font-semibold">
            ${Math.abs(metrics.cvar).toLocaleString()}
          </span>
          <span className="text-slate-500 text-xs block">
            Expected loss in worst 5%
          </span>
        </div>
      </div>
    </div>
  );

  // Render benchmark comparison
  const renderBenchmarkComparison = () => (
    <div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
      <div className="flex items-center justify-between mb-4">
        <h4 className="text-white font-medium">vs {benchmarkName}</h4>
      </div>

      <div className="grid grid-cols-2 gap-6">
        <div>
          <span className="text-slate-400 text-sm block mb-1">Alpha</span>
          <div className="flex items-center gap-2">
            {metrics.alpha >= 0 ? (
              <ArrowUpRight className="w-5 h-5 text-emerald-400" />
            ) : (
              <ArrowDownRight className="w-5 h-5 text-red-400" />
            )}
            <span className={`text-xl font-semibold ${metrics.alpha >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              {formatPercent(metrics.alpha)}
            </span>
          </div>
          <span className="text-slate-500 text-xs">
            {metrics.alpha >= 0 ? 'Outperforming' : 'Underperforming'} benchmark
          </span>
        </div>
        <div>
          <span className="text-slate-400 text-sm block mb-1">Beta</span>
          <span className="text-white text-xl font-semibold">{metrics.beta.toFixed(2)}</span>
          <span className="text-slate-500 text-xs block">
            {metrics.beta < 1 ? 'Lower' : metrics.beta > 1 ? 'Higher' : 'Same'} market sensitivity
          </span>
        </div>
      </div>
    </div>
  );

  // Render recommendations
  const renderRecommendations = () => {
    if (recommendations.length === 0) return null;

    const getRecommendationStyles = (type: RiskRecommendation['type']) => {
      switch (type) {
        case 'warning':
          return { icon: AlertTriangle, color: 'text-amber-400', bg: 'bg-amber-900/20', border: 'border-amber-800/50' };
        case 'suggestion':
          return { icon: Target, color: 'text-blue-400', bg: 'bg-blue-900/20', border: 'border-blue-800/50' };
        case 'info':
        default:
          return { icon: Info, color: 'text-slate-400', bg: 'bg-slate-800/50', border: 'border-slate-700' };
      }
    };

    return (
      <div className="space-y-3">
        <h4 className="text-white font-medium">Recommendations</h4>
        {recommendations.map((rec) => {
          const styles = getRecommendationStyles(rec.type);
          const Icon = styles.icon;
          return (
            <div
              key={rec.id}
              className={`rounded-lg p-3 border ${styles.bg} ${styles.border}`}
            >
              <div className="flex items-start gap-3">
                <Icon className={`w-5 h-5 ${styles.color} flex-shrink-0 mt-0.5`} />
                <div className="flex-1">
                  <p className="text-white font-medium text-sm">{rec.title}</p>
                  <p className="text-slate-400 text-sm mt-1">{rec.description}</p>
                  {rec.action && (
                    <button className="text-blue-400 text-sm mt-2 flex items-center gap-1 hover:text-blue-300">
                      {rec.action}
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // Loading state
  if (isLoading) {
    return (
      <div className="bg-slate-900 rounded-xl border border-slate-800 p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-6 bg-slate-800 rounded w-1/3" />
          <div className="h-32 bg-slate-800 rounded" />
          <div className="grid grid-cols-2 gap-4">
            <div className="h-24 bg-slate-800 rounded" />
            <div className="h-24 bg-slate-800 rounded" />
          </div>
        </div>
      </div>
    );
  }

  // Compact view
  if (compact) {
    return (
      <div className="bg-slate-900 rounded-xl border border-slate-800 p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Shield className="w-5 h-5 text-blue-400" />
            <h3 className="text-white font-medium">Risk Analysis</h3>
          </div>
          <div className={`px-2 py-1 rounded text-xs font-medium ${overallRisk.color} bg-slate-800`}>
            {overallRisk.label} Risk ({score.overall})
          </div>
        </div>

        <div className="grid grid-cols-4 gap-4 text-center">
          <div>
            <span className="text-slate-500 text-xs block">Sharpe</span>
            <span className={`font-semibold ${getMetricColor(metrics.sharpeRatio, { good: 1.5, warning: 1.0 })}`}>
              {metrics.sharpeRatio.toFixed(2)}
            </span>
          </div>
          <div>
            <span className="text-slate-500 text-xs block">Max DD</span>
            <span className={`font-semibold ${getMetricColor(metrics.maxDrawdown, { good: 10, warning: 20 }, true)}`}>
              {formatPercent(-metrics.maxDrawdown)}
            </span>
          </div>
          <div>
            <span className="text-slate-500 text-xs block">VaR 95%</span>
            <span className="text-red-400 font-semibold">${Math.abs(metrics.var95).toLocaleString()}</span>
          </div>
          <div>
            <span className="text-slate-500 text-xs block">Beta</span>
            <span className="text-white font-semibold">{metrics.beta.toFixed(2)}</span>
          </div>
        </div>

        {onViewDetails && (
          <button
            onClick={onViewDetails}
            className="w-full mt-4 text-blue-400 text-sm flex items-center justify-center gap-1 hover:text-blue-300"
          >
            View Full Analysis
            <ChevronRight className="w-4 h-4" />
          </button>
        )}
      </div>
    );
  }

  // Full view
  return (
    <div className="bg-slate-900 rounded-xl border border-slate-800">
      {/* Header */}
      <div className="p-6 border-b border-slate-800">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Shield className="w-6 h-6 text-blue-400" />
            <div>
              <h2 className="text-white text-lg font-semibold">Risk Analysis</h2>
              <p className="text-slate-400 text-sm">{accountName}</p>
            </div>
          </div>

          {/* Period Selector */}
          <div className="flex items-center gap-2">
            {PERIOD_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                onClick={() => onPeriodChange?.(opt.value)}
                className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                  period === opt.value
                    ? 'bg-blue-600 text-white'
                    : 'text-slate-400 hover:text-white hover:bg-slate-800'
                }`}
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="p-6 space-y-6">
        {/* Risk Score Section */}
        <div className="flex items-start gap-8">
          <div className="flex-shrink-0">
            {renderRiskGauge()}
          </div>
          <div className="flex-1">
            {renderRiskBreakdown()}
          </div>
        </div>

        {/* Key Metrics */}
        <div>
          <h4 className="text-white font-medium mb-4">Key Risk Metrics</h4>
          {renderKeyMetrics()}
        </div>

        {/* VaR Section */}
        {renderVaRMetrics()}

        {/* Benchmark Comparison */}
        {renderBenchmarkComparison()}

        {/* Additional Metrics */}
        <div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
          <h4 className="text-white font-medium mb-4">Additional Metrics</h4>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <span className="text-slate-400 text-sm block">Downside Deviation</span>
              <span className="text-white font-semibold">{formatPercent(metrics.downsideDeviation)}</span>
            </div>
            <div>
              <span className="text-slate-400 text-sm block">Calmar Ratio</span>
              <span className={`font-semibold ${getMetricColor(metrics.calmarRatio, { good: 2.0, warning: 1.0 })}`}>
                {metrics.calmarRatio.toFixed(2)}
              </span>
            </div>
            <div>
              <span className="text-slate-400 text-sm block">Recovery Factor</span>
              <span className="text-white font-semibold">
                {(metrics.calmarRatio * 0.8).toFixed(2)}
              </span>
            </div>
          </div>
        </div>

        {/* Recommendations */}
        {renderRecommendations()}
      </div>
    </div>
  );
};

export default RiskAnalysisPanel;
