import { useState, useEffect } from 'react';
import { TrendingUp, TrendingDown, RotateCcw, Sparkles } from 'lucide-react';

interface TradeControlsProps {
  currentPrice: number;
  cash: number;
  onBuy: (quantity: number) => void;
  onSell: (quantity: number) => void;
  onReset: () => void;
  onAIAnalysis: () => void;
  hasPosition: boolean;
  isAnalyzing?: boolean;
}

export default function TradeControls({
  currentPrice,
  cash,
  onBuy,
  onSell,
  onReset,
  onAIAnalysis,
  hasPosition,
  isAnalyzing = false,
}: TradeControlsProps) {
  const [quantity, setQuantity] = useState<string>('1');
  const [usdAmount, setUsdAmount] = useState<string>('');

  // Initialize USD amount when currentPrice changes
  useEffect(() => {
    const qty = parseFloat(quantity);
    if (!isNaN(qty) && qty > 0 && currentPrice > 0) {
      setUsdAmount((qty * currentPrice).toFixed(2));
    }
  }, [currentPrice]);

  const handleQuantityChange = (value: string) => {
    // Allow empty string, numbers, and decimal points
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setQuantity(value);
      const num = parseFloat(value);
      if (!isNaN(num) && num > 0) {
        setUsdAmount((num * currentPrice).toFixed(2));
      } else {
        setUsdAmount('');
      }
    }
  };

  const handleUsdChange = (value: string) => {
    // Allow empty string, numbers, and decimal points
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setUsdAmount(value);
      const num = parseFloat(value);
      if (!isNaN(num) && num > 0 && currentPrice > 0) {
        setQuantity((num / currentPrice).toFixed(4));
      } else {
        setQuantity('');
      }
    }
  };

  const handleBuy = () => {
    const qty = parseFloat(quantity);
    if (isNaN(qty) || qty <= 0) {
      alert('Please enter a valid quantity greater than 0');
      return;
    }
    
    const cost = qty * currentPrice;
    if (cost > cash) {
      alert(`Insufficient funds! You need $${cost.toFixed(2)} but only have $${cash.toFixed(2)}`);
      return;
    }

    onBuy(qty);
    setQuantity('1');
    setUsdAmount((1 * currentPrice).toFixed(2));
  };

  const handleSell = () => {
    const qty = parseFloat(quantity);
    if (isNaN(qty) || qty <= 0) {
      alert('Please enter a valid quantity greater than 0');
      return;
    }

    if (!hasPosition) {
      alert('You have no position to sell!');
      return;
    }

    onSell(qty);
    setQuantity('1');
    setUsdAmount((1 * currentPrice).toFixed(2));
  };

  const maxBuyQuantity = currentPrice > 0 ? cash / currentPrice : 0;
  const qty = parseFloat(quantity);
  const totalCost = !isNaN(qty) && qty > 0 ? qty * currentPrice : 0;
  const canBuy = !isNaN(qty) && qty > 0 && totalCost <= cash && currentPrice > 0;

  return (
    <div className="card">
      <h3 className="text-lg font-semibold mb-4">Trade Controls</h3>

      <div className="space-y-4">
        <div>
          <label className="block text-sm text-gray-400 mb-2">Current Price</label>
          <div className="bg-dark-bg rounded-lg p-3 text-xl font-bold text-gold-500">
            ${currentPrice.toFixed(2)}
          </div>
        </div>

        <div>
          <label className="block text-sm text-gray-400 mb-2">Quantity (oz)</label>
          <div className="flex gap-2 mb-2">
            <input
              type="text"
              value={quantity}
              onChange={(e) => handleQuantityChange(e.target.value)}
              className="input flex-1"
              placeholder="0.00"
            />
            <button
              onClick={() => handleQuantityChange(maxBuyQuantity.toFixed(4))}
              className="px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-md text-sm font-medium"
              disabled={maxBuyQuantity <= 0}
            >
              Max
            </button>
          </div>
          <div className="flex gap-1 mb-1">
            <button
              onClick={() => handleUsdChange((cash * 0.25).toFixed(2))}
              className="text-xs px-2 py-1 bg-dark-bg hover:bg-dark-hover rounded"
            >
              25%
            </button>
            <button
              onClick={() => handleUsdChange((cash * 0.5).toFixed(2))}
              className="text-xs px-2 py-1 bg-dark-bg hover:bg-dark-hover rounded"
            >
              50%
            </button>
            <button
              onClick={() => handleUsdChange((cash * 0.75).toFixed(2))}
              className="text-xs px-2 py-1 bg-dark-bg hover:bg-dark-hover rounded"
            >
              75%
            </button>
          </div>
          <p className="text-xs text-gray-500">
            Max: {maxBuyQuantity.toFixed(4)} oz
          </p>
        </div>

        <div>
          <label className="block text-sm text-gray-400 mb-2">USD Amount</label>
          <input
            type="number"
            value={usdAmount}
            onChange={(e) => handleUsdChange(e.target.value)}
            className="input w-full"
            min="0"
            step="0.01"
            placeholder="0.00"
          />
          <p className="text-xs text-gray-500 mt-1">
            Total: ${totalCost.toFixed(2)}
          </p>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <button
            onClick={handleBuy}
            disabled={!canBuy}
            className="btn-success flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            title={!canBuy ? (cash === 0 ? 'No funds available' : 'Invalid quantity or insufficient funds') : 'Buy gold (Ctrl+B)'}
          >
            <TrendingUp className="w-4 h-4" />
            Buy
          </button>
          <button
            onClick={handleSell}
            disabled={!hasPosition || isNaN(qty) || qty <= 0}
            className="btn-danger flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            title={!hasPosition ? 'No position to sell' : 'Sell gold (Ctrl+S)'}
          >
            <TrendingDown className="w-4 h-4" />
            Sell
          </button>
        </div>

        <div className="border-t border-dark-border pt-4 space-y-3">
          <button
            onClick={onAIAnalysis}
            disabled={isAnalyzing}
            className="btn-primary w-full flex items-center justify-center gap-2 disabled:opacity-50"
          >
            <Sparkles className="w-4 h-4" />
            {isAnalyzing ? 'Analyzing...' : 'AI Analysis'}
          </button>

          <button
            onClick={onReset}
            className="btn w-full bg-gray-700 hover:bg-gray-600 text-white flex items-center justify-center gap-2"
          >
            <RotateCcw className="w-4 h-4" />
            Reset Simulation
          </button>
        </div>
      </div>
    </div>
  );
}
