import { useState, useEffect } from 'react';
import { Shield, Calculator, TrendingUp, AlertTriangle } from 'lucide-react';
import { calculatePositionSize, formatPrice } from '@/utils/indicators';

interface RiskManagementProps {
  currentPrice: number;
  cash: number;
  position: any;
  trades: any[];
  onSetStopLoss?: (price: number) => void;
  onSetTakeProfit?: (price: number) => void;
}

export default function RiskManagement({
  currentPrice,
  cash,
  position: _position,
  trades,
  onSetStopLoss,
  onSetTakeProfit,
}: RiskManagementProps) {
  const [riskPercent, setRiskPercent] = useState<number>(2);
  const [stopLossPercent, setStopLossPercent] = useState<number>(2);
  const [takeProfitPercent, setTakeProfitPercent] = useState<number>(4);
  const [positionSize, setPositionSize] = useState<number>(0);
  const [stopLossPrice, setStopLossPrice] = useState<number>(0);
  const [takeProfitPrice, setTakeProfitPrice] = useState<number>(0);

  // Calculate position size based on risk
  useEffect(() => {
    const riskAmount = cash * (riskPercent / 100);
    const stopLossDiff = currentPrice * (stopLossPercent / 100);
    const maxQuantity = riskAmount / stopLossDiff;

    setPositionSize(Number(maxQuantity.toFixed(4)));
    setStopLossPrice(Number((currentPrice * (1 - stopLossPercent / 100)).toFixed(2)));
    setTakeProfitPrice(Number((currentPrice * (1 + takeProfitPercent / 100)).toFixed(2)));
  }, [currentPrice, cash, riskPercent, stopLossPercent, takeProfitPercent]);

  // Calculate Kelly Criterion recommendation
  const getKellyRecommendation = () => {
    if (trades.length < 10) {
      return { size: 0, message: 'Need at least 10 trades for Kelly calculation' };
    }

    const completedTrades = trades.filter((t: any) => t.pnl !== undefined);
    const winningTrades = completedTrades.filter((t: any) => t.pnl > 0);
    const losingTrades = completedTrades.filter((t: any) => t.pnl <= 0);

    if (winningTrades.length === 0 || losingTrades.length === 0) {
      return { size: 0, message: 'Need both winning and losing trades' };
    }

    const winRate = winningTrades.length / completedTrades.length;
    const avgWin = winningTrades.reduce((sum: number, t: any) => sum + t.pnl, 0) / winningTrades.length;
    const avgLoss = Math.abs(losingTrades.reduce((sum: number, t: any) => sum + t.pnl, 0) / losingTrades.length);

    const kellySize = calculatePositionSize(cash, winRate, avgWin, avgLoss);

    return {
      size: kellySize,
      message: `Kelly suggests ${formatPrice(kellySize)} position size`,
    };
  };

  const kellyRec = getKellyRecommendation();

  const maxLoss = positionSize * (currentPrice * (stopLossPercent / 100));
  const maxProfit = positionSize * (currentPrice * (takeProfitPercent / 100));
  const riskRewardRatio = takeProfitPercent / stopLossPercent;

  return (
    <div className="card">
      <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
        <Shield className="w-5 h-5 text-blue-500" />
        Risk Management
      </h3>

      {/* Risk Parameters */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm text-gray-400 mb-2">
            Risk per Trade (% of Capital)
          </label>
          <div className="flex items-center gap-2">
            <input
              type="range"
              min="0.5"
              max="5"
              step="0.5"
              value={riskPercent}
              onChange={(e) => setRiskPercent(Number(e.target.value))}
              className="flex-1"
            />
            <span className="text-sm font-medium w-12">{riskPercent}%</span>
          </div>
          <p className="text-xs text-gray-500 mt-1">
            Max risk: {formatPrice(cash * (riskPercent / 100))}
          </p>
        </div>

        <div>
          <label className="block text-sm text-gray-400 mb-2">Stop Loss (%)</label>
          <div className="flex items-center gap-2">
            <input
              type="range"
              min="0.5"
              max="10"
              step="0.5"
              value={stopLossPercent}
              onChange={(e) => setStopLossPercent(Number(e.target.value))}
              className="flex-1"
            />
            <span className="text-sm font-medium w-12">{stopLossPercent}%</span>
          </div>
          <p className="text-xs text-gray-500 mt-1">
            Stop at: {formatPrice(stopLossPrice)}
          </p>
        </div>

        <div>
          <label className="block text-sm text-gray-400 mb-2">Take Profit (%)</label>
          <div className="flex items-center gap-2">
            <input
              type="range"
              min="1"
              max="20"
              step="0.5"
              value={takeProfitPercent}
              onChange={(e) => setTakeProfitPercent(Number(e.target.value))}
              className="flex-1"
            />
            <span className="text-sm font-medium w-12">{takeProfitPercent}%</span>
          </div>
          <p className="text-xs text-gray-500 mt-1">
            Target: {formatPrice(takeProfitPrice)}
          </p>
        </div>
      </div>

      {/* Recommended Position Size */}
      <div className="mt-4 p-4 bg-dark-bg rounded-lg border border-dark-border">
        <div className="flex items-center gap-2 mb-3">
          <Calculator className="w-4 h-4 text-blue-500" />
          <h4 className="font-semibold">Recommended Position</h4>
        </div>

        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-gray-400">Position Size:</span>
            <span className="font-bold">{positionSize.toFixed(4)} oz</span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-400">Cost:</span>
            <span className="font-medium">{formatPrice(positionSize * currentPrice)}</span>
          </div>
          <div className="flex justify-between border-t border-dark-border pt-2">
            <span className="text-gray-400">Max Loss:</span>
            <span className="font-semibold text-red-500">-{formatPrice(maxLoss)}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-400">Max Profit:</span>
            <span className="font-semibold text-green-500">+{formatPrice(maxProfit)}</span>
          </div>
          <div className="flex justify-between border-t border-dark-border pt-2">
            <span className="text-gray-400">R:R Ratio:</span>
            <span
              className={`font-semibold ${
                riskRewardRatio >= 2 ? 'text-green-500' : 'text-yellow-500'
              }`}
            >
              1:{riskRewardRatio.toFixed(2)}
            </span>
          </div>
        </div>
      </div>

      {/* Kelly Criterion */}
      {trades.length >= 10 && (
        <div className="mt-4 p-4 bg-blue-500/10 rounded-lg border border-blue-500/30">
          <div className="flex items-center gap-2 mb-2">
            <TrendingUp className="w-4 h-4 text-blue-500" />
            <h4 className="font-semibold text-sm">Kelly Criterion</h4>
          </div>
          <p className="text-xs text-gray-300 mb-2">{kellyRec.message}</p>
          {kellyRec.size > 0 && (
            <div className="flex justify-between text-sm">
              <span className="text-gray-400">Suggested oz:</span>
              <span className="font-medium">
                {(kellyRec.size / currentPrice).toFixed(4)} oz
              </span>
            </div>
          )}
        </div>
      )}

      {/* Risk Warning */}
      <div className="mt-4 p-3 bg-yellow-500/10 rounded-lg border border-yellow-500/30">
        <div className="flex items-start gap-2">
          <AlertTriangle className="w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5" />
          <div className="text-xs text-gray-300">
            <p className="font-medium text-yellow-500 mb-1">Risk Guidelines:</p>
            <ul className="space-y-1 list-disc list-inside">
              <li>Never risk more than 2% per trade</li>
              <li>Maintain R:R ratio of at least 1:2</li>
              <li>Always use stop losses</li>
              <li>Consider Kelly Criterion for sizing</li>
            </ul>
          </div>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="mt-4 space-y-2">
        <button
          onClick={() => onSetStopLoss?.(stopLossPrice)}
          className="btn w-full bg-red-600 hover:bg-red-700 text-white flex items-center justify-center gap-2"
        >
          <Shield className="w-4 h-4" />
          Set Stop Loss ({formatPrice(stopLossPrice)})
        </button>
        <button
          onClick={() => onSetTakeProfit?.(takeProfitPrice)}
          className="btn w-full bg-green-600 hover:bg-green-700 text-white flex items-center justify-center gap-2"
        >
          <TrendingUp className="w-4 h-4" />
          Set Take Profit ({formatPrice(takeProfitPrice)})
        </button>
      </div>
    </div>
  );
}
