/**
 * OrderForm Component
 * Form to create buy/sell orders for paper trading
 */

import { useState } from 'react';
import type { CreateOrderInput } from '../../../types/trading.types';

interface OrderFormProps {
  symbol: string;
  currentPrice: number;
  balance: number;
  onSubmit: (orderData: CreateOrderInput) => Promise<void>;
}

export default function OrderForm({
  symbol,
  currentPrice,
  balance,
  onSubmit,
}: OrderFormProps) {
  const [direction, setDirection] = useState<'long' | 'short'>('long');
  const [orderType, setOrderType] = useState<'market' | 'limit'>('market');
  const [lotSize, setLotSize] = useState<string>('0.01');
  const [limitPrice, setLimitPrice] = useState<string>(currentPrice.toString());
  const [stopLoss, setStopLoss] = useState<string>('');
  const [takeProfit, setTakeProfit] = useState<string>('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Calculate estimated value
  const getEstimatedValue = () => {
    const lot = parseFloat(lotSize) || 0;
    const price = orderType === 'market' ? currentPrice : (parseFloat(limitPrice) || currentPrice);
    return lot * price;
  };

  const estimatedValue = getEstimatedValue();
  const hasInsufficientBalance = estimatedValue > balance;

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    // Validation
    const lot = parseFloat(lotSize);
    if (!lot || lot <= 0) {
      setError('Invalid lot size');
      return;
    }

    if (hasInsufficientBalance) {
      setError('Insufficient balance');
      return;
    }

    if (orderType === 'limit') {
      const price = parseFloat(limitPrice);
      if (!price || price <= 0) {
        setError('Invalid limit price');
        return;
      }
    }

    // Build order data
    const orderData: CreateOrderInput = {
      symbol,
      direction,
      lotSize: lot,
      orderType,
    };

    if (orderType === 'limit') {
      orderData.entryPrice = parseFloat(limitPrice);
    }

    if (stopLoss) {
      const sl = parseFloat(stopLoss);
      if (sl > 0) {
        orderData.stopLoss = sl;
      }
    }

    if (takeProfit) {
      const tp = parseFloat(takeProfit);
      if (tp > 0) {
        orderData.takeProfit = tp;
      }
    }

    // Submit order
    setIsSubmitting(true);
    try {
      await onSubmit(orderData);
      // Reset form on success
      setLotSize('0.01');
      setStopLoss('');
      setTakeProfit('');
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create order');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="p-4 space-y-4">
      {/* Direction Selector */}
      <div className="grid grid-cols-2 gap-2">
        <button
          type="button"
          onClick={() => setDirection('long')}
          className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
            direction === 'long'
              ? 'bg-green-600 text-white'
              : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
          }`}
        >
          BUY
        </button>
        <button
          type="button"
          onClick={() => setDirection('short')}
          className={`px-4 py-2 rounded-lg font-semibold transition-colors ${
            direction === 'short'
              ? 'bg-red-600 text-white'
              : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
          }`}
        >
          SELL
        </button>
      </div>

      {/* Lot Size */}
      <div>
        <label className="block text-sm text-gray-400 mb-1">Amount</label>
        <input
          type="number"
          step="0.001"
          min="0"
          value={lotSize}
          onChange={(e) => setLotSize(e.target.value)}
          className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
          placeholder="0.01"
        />
      </div>

      {/* Order Type */}
      <div>
        <label className="block text-sm text-gray-400 mb-1">Type</label>
        <div className="flex gap-4">
          <label className="flex items-center cursor-pointer">
            <input
              type="radio"
              name="orderType"
              value="market"
              checked={orderType === 'market'}
              onChange={(e) => setOrderType(e.target.value as 'market' | 'limit')}
              className="mr-2"
            />
            <span className="text-white">Market</span>
          </label>
          <label className="flex items-center cursor-pointer">
            <input
              type="radio"
              name="orderType"
              value="limit"
              checked={orderType === 'limit'}
              onChange={(e) => setOrderType(e.target.value as 'market' | 'limit')}
              className="mr-2"
            />
            <span className="text-white">Limit</span>
          </label>
        </div>
      </div>

      {/* Limit Price (only if limit order) */}
      {orderType === 'limit' && (
        <div>
          <label className="block text-sm text-gray-400 mb-1">Price</label>
          <input
            type="number"
            step="0.01"
            min="0"
            value={limitPrice}
            onChange={(e) => setLimitPrice(e.target.value)}
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
            placeholder={currentPrice.toString()}
          />
        </div>
      )}

      {/* Stop Loss */}
      <div>
        <label className="block text-sm text-gray-400 mb-1">Stop Loss (Optional)</label>
        <input
          type="number"
          step="0.01"
          min="0"
          value={stopLoss}
          onChange={(e) => setStopLoss(e.target.value)}
          className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
          placeholder="0.00"
        />
      </div>

      {/* Take Profit */}
      <div>
        <label className="block text-sm text-gray-400 mb-1">Take Profit (Optional)</label>
        <input
          type="number"
          step="0.01"
          min="0"
          value={takeProfit}
          onChange={(e) => setTakeProfit(e.target.value)}
          className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
          placeholder="0.00"
        />
      </div>

      {/* Estimated Value */}
      <div className="pt-2 border-t border-gray-700">
        <div className="flex justify-between text-sm">
          <span className="text-gray-400">Est. Value:</span>
          <span className={`font-mono ${hasInsufficientBalance ? 'text-red-400' : 'text-white'}`}>
            ${estimatedValue.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </span>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <div className="p-3 bg-red-900/20 border border-red-800 rounded-lg">
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {/* Submit Button */}
      <button
        type="submit"
        disabled={isSubmitting || hasInsufficientBalance}
        className={`w-full py-3 rounded-lg font-semibold transition-colors ${
          direction === 'long'
            ? 'bg-green-600 hover:bg-green-700 disabled:bg-gray-700'
            : 'bg-red-600 hover:bg-red-700 disabled:bg-gray-700'
        } text-white disabled:text-gray-500 disabled:cursor-not-allowed`}
      >
        {isSubmitting
          ? 'Placing Order...'
          : `Place ${direction === 'long' ? 'Buy' : 'Sell'} Order`}
      </button>
    </form>
  );
}
