import { useState, useEffect } from 'react';
import type { BacktestConfig } from '../types';

interface BacktestConfigurationProps {
  onSubmit: (config: BacktestConfig) => void;
  disabled?: boolean;
  initialConfig?: BacktestConfig;
}

export function BacktestConfiguration({ onSubmit, disabled, initialConfig }: BacktestConfigurationProps) {
  const [formData, setFormData] = useState<BacktestConfig>(initialConfig || {
    name: '',
    startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago
    endDate: new Date(),
    initialCapital: 100000,
    symbols: [],
    strategy: 'sma-crossover',
    speedMultiplier: 1,
    commission: 0.001, // 0.1%
    slippage: 0.0005, // 0.05%
  });

  const [symbolInput, setSymbolInput] = useState('');

  useEffect(() => {
    if (initialConfig) {
      setFormData(initialConfig);
    }
  }, [initialConfig]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (formData.symbols.length === 0) {
      alert('Please add at least one symbol');
      return;
    }
    onSubmit(formData);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? parseFloat(value) : 
               type === 'date' ? new Date(value) : value
    }));
  };

  const handleAddSymbol = () => {
    const symbol = symbolInput.trim().toUpperCase();
    if (symbol && !formData.symbols.includes(symbol)) {
      setFormData(prev => ({
        ...prev,
        symbols: [...prev.symbols, symbol]
      }));
      setSymbolInput('');
    }
  };

  const handleRemoveSymbol = (symbol: string) => {
    setFormData(prev => ({
      ...prev,
      symbols: prev.symbols.filter(s => s !== symbol)
    }));
  };

  const formatDate = (date: Date) => {
    return date.toISOString().split('T')[0];
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-text-secondary mb-1">
            Backtest Name
          </label>
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
            placeholder="My Strategy Backtest"
            className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
            disabled={disabled}
            required
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1">
              Start Date
            </label>
            <input
              type="date"
              name="startDate"
              value={formatDate(formData.startDate)}
              onChange={handleChange}
              className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
              disabled={disabled}
              required
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1">
              End Date
            </label>
            <input
              type="date"
              name="endDate"
              value={formatDate(formData.endDate)}
              onChange={handleChange}
              className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
              disabled={disabled}
              required
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text-secondary mb-1">
            Initial Capital ($)
          </label>
          <input
            type="number"
            name="initialCapital"
            value={formData.initialCapital}
            onChange={handleChange}
            min="1000"
            step="1000"
            className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
            disabled={disabled}
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-text-secondary mb-1">
            Symbols
          </label>
          <div className="flex gap-2 mb-2">
            <input
              type="text"
              value={symbolInput}
              onChange={(e) => setSymbolInput(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddSymbol())}
              placeholder="AAPL"
              className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
              disabled={disabled}
            />
            <button
              type="button"
              onClick={handleAddSymbol}
              className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50"
              disabled={disabled}
            >
              Add
            </button>
          </div>
          <div className="flex flex-wrap gap-2">
            {formData.symbols.map(symbol => (
              <span
                key={symbol}
                className="inline-flex items-center gap-1 px-2 py-1 bg-primary-500/10 text-primary-400 rounded-md text-sm"
              >
                {symbol}
                <button
                  type="button"
                  onClick={() => handleRemoveSymbol(symbol)}
                  className="text-primary-400 hover:text-primary-300"
                  disabled={disabled}
                >
                  ×
                </button>
              </span>
            ))}
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text-secondary mb-1">
            Strategy
          </label>
          <select
            name="strategy"
            value={formData.strategy}
            onChange={handleChange}
            className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
            disabled={disabled}
          >
            <option value="sma-crossover">SMA Crossover</option>
            <option value="mean-reversion">Mean Reversion</option>
            <option value="ml-enhanced">ML Enhanced (Advanced)</option>
            <option value="momentum">Momentum (Coming Soon)</option>
            <option value="pairs-trading">Pairs Trading (Coming Soon)</option>
          </select>
          <p className="text-xs text-text-muted mt-1">
            {formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'}
            {formData.strategy === 'mean-reversion' && 'Trades when price deviates from mean by 2+ std devs'}
            {formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'}
            {formData.strategy === 'momentum' && 'Follows strong price trends'}
            {formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'}
          </p>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1">
              Commission (%)
            </label>
            <input
              type="number"
              name="commission"
              value={formData.commission * 100}
              onChange={(e) => setFormData(prev => ({ ...prev, commission: parseFloat(e.target.value) / 100 }))}
              min="0"
              step="0.01"
              className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
              disabled={disabled}
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1">
              Slippage (%)
            </label>
            <input
              type="number"
              name="slippage"
              value={formData.slippage * 100}
              onChange={(e) => setFormData(prev => ({ ...prev, slippage: parseFloat(e.target.value) / 100 }))}
              min="0"
              step="0.01"
              className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
              disabled={disabled}
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text-secondary mb-1">
            Speed Multiplier
          </label>
          <input
            type="number"
            name="speedMultiplier"
            value={formData.speedMultiplier}
            onChange={handleChange}
            min="0.1"
            max="1000"
            step="0.1"
            className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
            disabled={disabled}
          />
          <p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
        </div>

        <button
          type="submit"
          className="w-full px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          disabled={disabled}
        >
          Save
        </button>
      </form>
  );
}