/**
 * RiskBasedPositionSizer Component
 * Standalone risk calculator for position sizing before entry
 */

import React, { useState, useMemo } from 'react';
import {
  Calculator,
  DollarSign,
  Percent,
  TrendingUp,
  TrendingDown,
  Target,
  Shield,
  AlertTriangle,
  Info,
  Copy,
  Check,
} from 'lucide-react';

interface RiskBasedPositionSizerProps {
  accountBalance?: number;
  defaultSymbol?: string;
  defaultRiskPercent?: number;
  onCalculate?: (result: CalculationResult) => void;
  onApplyToOrder?: (lots: number) => void;
  compact?: boolean;
}

interface CalculationResult {
  lots: number;
  riskAmount: number;
  potentialLoss: number;
  potentialProfit: number;
  riskRewardRatio: number;
  pipValue: number;
  slPips: number;
  tpPips: number;
}

interface RiskScenario {
  riskPercent: number;
  lots: number;
  riskAmount: number;
}

const RiskBasedPositionSizer: React.FC<RiskBasedPositionSizerProps> = ({
  accountBalance = 10000,
  defaultSymbol = 'EURUSD',
  defaultRiskPercent = 1,
  onCalculate,
  onApplyToOrder,
  compact = false,
}) => {
  const [balance, setBalance] = useState<string>(accountBalance.toString());
  const [riskPercent, setRiskPercent] = useState<string>(defaultRiskPercent.toString());
  const [symbol, setSymbol] = useState(defaultSymbol);
  const [entryPrice, setEntryPrice] = useState<string>('');
  const [stopLoss, setStopLoss] = useState<string>('');
  const [takeProfit, setTakeProfit] = useState<string>('');
  const [tradeType, setTradeType] = useState<'BUY' | 'SELL'>('BUY');
  const [copied, setCopied] = useState(false);

  const pipValue = symbol.includes('JPY') ? 0.01 : 0.0001;
  const pipValueUsd = 10; // Approximate USD value per pip per lot for majors

  // Calculate position size and metrics
  const calculation = useMemo<CalculationResult | null>(() => {
    const balanceNum = parseFloat(balance) || 0;
    const riskPercentNum = parseFloat(riskPercent) || 0;
    const entry = parseFloat(entryPrice) || 0;
    const sl = parseFloat(stopLoss) || 0;
    const tp = parseFloat(takeProfit) || 0;

    if (!balanceNum || !riskPercentNum || !entry || !sl) {
      return null;
    }

    // Calculate pips to SL
    const slPips = Math.abs(entry - sl) / pipValue;
    const tpPips = tp ? Math.abs(tp - entry) / pipValue : 0;

    // Risk amount in currency
    const riskAmount = (balanceNum * riskPercentNum) / 100;

    // Position size (lots)
    const lots = riskAmount / (slPips * pipValueUsd);
    const roundedLots = Math.floor(lots * 100) / 100; // Round down to 0.01

    // Potential P&L
    const potentialLoss = roundedLots * slPips * pipValueUsd;
    const potentialProfit = tp ? roundedLots * tpPips * pipValueUsd : 0;

    // Risk/Reward ratio
    const riskRewardRatio = potentialProfit && potentialLoss ? potentialProfit / potentialLoss : 0;

    const result: CalculationResult = {
      lots: roundedLots,
      riskAmount,
      potentialLoss,
      potentialProfit,
      riskRewardRatio,
      pipValue: roundedLots * pipValueUsd,
      slPips,
      tpPips,
    };

    onCalculate?.(result);
    return result;
  }, [balance, riskPercent, entryPrice, stopLoss, takeProfit, symbol, onCalculate]);

  // Generate risk scenarios
  const scenarios: RiskScenario[] = useMemo(() => {
    const balanceNum = parseFloat(balance) || 0;
    const entry = parseFloat(entryPrice) || 0;
    const sl = parseFloat(stopLoss) || 0;

    if (!balanceNum || !entry || !sl) return [];

    const slPips = Math.abs(entry - sl) / pipValue;
    const percents = [0.5, 1, 2, 5];

    return percents.map((pct) => {
      const risk = (balanceNum * pct) / 100;
      const lots = Math.floor((risk / (slPips * pipValueUsd)) * 100) / 100;
      return {
        riskPercent: pct,
        lots,
        riskAmount: risk,
      };
    });
  }, [balance, entryPrice, stopLoss, symbol]);

  const handleCopyLots = async () => {
    if (calculation) {
      await navigator.clipboard.writeText(calculation.lots.toFixed(2));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleApply = () => {
    if (calculation && onApplyToOrder) {
      onApplyToOrder(calculation.lots);
    }
  };

  const isValidSL = () => {
    const entry = parseFloat(entryPrice) || 0;
    const sl = parseFloat(stopLoss) || 0;
    if (!entry || !sl) return true;

    if (tradeType === 'BUY') {
      return sl < entry;
    } else {
      return sl > entry;
    }
  };

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center gap-2 mb-4">
        <Calculator className="w-5 h-5 text-blue-400" />
        <h3 className="font-semibold text-white">Position Sizer</h3>
      </div>

      <div className="space-y-4">
        {/* Account Balance */}
        <div>
          <label className="block text-sm text-gray-400 mb-1.5">Account Balance</label>
          <div className="relative">
            <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="number"
              value={balance}
              onChange={(e) => setBalance(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
            />
          </div>
        </div>

        {/* Risk Percent */}
        <div>
          <label className="block text-sm text-gray-400 mb-1.5">Risk Per Trade</label>
          <div className="relative">
            <Percent className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="number"
              value={riskPercent}
              onChange={(e) => setRiskPercent(e.target.value)}
              step="0.5"
              min="0.1"
              max="10"
              className="w-full pl-10 pr-4 py-2.5 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
            />
          </div>
          <div className="flex gap-2 mt-2">
            {[0.5, 1, 2, 3].map((pct) => (
              <button
                key={pct}
                onClick={() => setRiskPercent(pct.toString())}
                className={`px-3 py-1 text-xs rounded ${
                  parseFloat(riskPercent) === pct
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                {pct}%
              </button>
            ))}
          </div>
        </div>

        {/* Trade Type */}
        <div>
          <label className="block text-sm text-gray-400 mb-1.5">Trade Direction</label>
          <div className="grid grid-cols-2 gap-2">
            <button
              onClick={() => setTradeType('BUY')}
              className={`flex items-center justify-center gap-2 py-2.5 rounded-lg font-medium transition-colors ${
                tradeType === 'BUY'
                  ? 'bg-green-600 text-white'
                  : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
              }`}
            >
              <TrendingUp className="w-4 h-4" />
              BUY
            </button>
            <button
              onClick={() => setTradeType('SELL')}
              className={`flex items-center justify-center gap-2 py-2.5 rounded-lg font-medium transition-colors ${
                tradeType === 'SELL'
                  ? 'bg-red-600 text-white'
                  : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
              }`}
            >
              <TrendingDown className="w-4 h-4" />
              SELL
            </button>
          </div>
        </div>

        {/* Entry, SL, TP */}
        <div className="grid grid-cols-3 gap-3">
          <div>
            <label className="block text-xs text-gray-500 mb-1">Entry Price</label>
            <input
              type="number"
              value={entryPrice}
              onChange={(e) => setEntryPrice(e.target.value)}
              step="0.00001"
              placeholder="1.08500"
              className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm font-mono focus:outline-none focus:border-blue-500"
            />
          </div>
          <div>
            <label className="flex items-center gap-1 text-xs text-gray-500 mb-1">
              <Shield className="w-3 h-3 text-red-400" />
              Stop Loss
            </label>
            <input
              type="number"
              value={stopLoss}
              onChange={(e) => setStopLoss(e.target.value)}
              step="0.00001"
              placeholder="1.08300"
              className={`w-full px-3 py-2 bg-gray-900 border rounded-lg text-white text-sm font-mono focus:outline-none ${
                !isValidSL() ? 'border-red-500' : 'border-gray-700 focus:border-red-500'
              }`}
            />
          </div>
          <div>
            <label className="flex items-center gap-1 text-xs text-gray-500 mb-1">
              <Target className="w-3 h-3 text-green-400" />
              Take Profit
            </label>
            <input
              type="number"
              value={takeProfit}
              onChange={(e) => setTakeProfit(e.target.value)}
              step="0.00001"
              placeholder="1.08900"
              className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm font-mono focus:outline-none focus:border-green-500"
            />
          </div>
        </div>

        {/* Invalid SL Warning */}
        {!isValidSL() && (
          <div className="flex items-center gap-2 p-2 bg-red-500/10 border border-red-500/30 rounded-lg">
            <AlertTriangle className="w-4 h-4 text-red-400" />
            <span className="text-xs text-red-400">
              Stop loss should be {tradeType === 'BUY' ? 'below' : 'above'} entry price for {tradeType} trades
            </span>
          </div>
        )}

        {/* Result */}
        {calculation && isValidSL() && (
          <div className="p-4 bg-blue-500/10 border border-blue-500/30 rounded-xl space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-400">Recommended Position Size</span>
              <div className="flex items-center gap-2">
                <span className="text-2xl font-bold text-white">{calculation.lots.toFixed(2)}</span>
                <span className="text-gray-400">lots</span>
                <button
                  onClick={handleCopyLots}
                  className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded"
                  title="Copy"
                >
                  {copied ? (
                    <Check className="w-4 h-4 text-green-400" />
                  ) : (
                    <Copy className="w-4 h-4" />
                  )}
                </button>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3 pt-3 border-t border-blue-500/20">
              <div>
                <div className="text-xs text-gray-500">Risk Amount</div>
                <div className="text-red-400 font-medium">${calculation.riskAmount.toFixed(2)}</div>
              </div>
              <div>
                <div className="text-xs text-gray-500">Max Loss</div>
                <div className="text-red-400 font-medium">${calculation.potentialLoss.toFixed(2)}</div>
              </div>
              {calculation.potentialProfit > 0 && (
                <>
                  <div>
                    <div className="text-xs text-gray-500">Potential Profit</div>
                    <div className="text-green-400 font-medium">${calculation.potentialProfit.toFixed(2)}</div>
                  </div>
                  <div>
                    <div className="text-xs text-gray-500">R:R Ratio</div>
                    <div className="text-white font-medium">1:{calculation.riskRewardRatio.toFixed(2)}</div>
                  </div>
                </>
              )}
            </div>

            <div className="flex items-center gap-2 pt-2 text-xs text-gray-500">
              <Info className="w-3 h-3" />
              <span>SL: {calculation.slPips.toFixed(1)} pips • Pip value: ${calculation.pipValue.toFixed(2)}</span>
            </div>

            {onApplyToOrder && (
              <button
                onClick={handleApply}
                className="w-full py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors"
              >
                Apply to Order
              </button>
            )}
          </div>
        )}

        {/* Risk Scenarios */}
        {scenarios.length > 0 && !compact && (
          <div>
            <div className="flex items-center gap-2 mb-2">
              <span className="text-xs text-gray-500">Quick Scenarios</span>
            </div>
            <div className="grid grid-cols-4 gap-2">
              {scenarios.map((scenario) => (
                <button
                  key={scenario.riskPercent}
                  onClick={() => setRiskPercent(scenario.riskPercent.toString())}
                  className={`p-2 rounded-lg text-center transition-colors ${
                    parseFloat(riskPercent) === scenario.riskPercent
                      ? 'bg-blue-600/20 border border-blue-500/50'
                      : 'bg-gray-900/50 border border-gray-700 hover:border-gray-600'
                  }`}
                >
                  <div className="text-xs text-gray-400">{scenario.riskPercent}%</div>
                  <div className="text-white font-bold">{scenario.lots.toFixed(2)}</div>
                  <div className="text-xs text-red-400">${scenario.riskAmount.toFixed(0)}</div>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default RiskBasedPositionSizer;
