/**
 * CreateBotModal Component
 * ========================
 * Multi-step wizard for creating a new trading bot
 * Steps: 1. Select Template, 2. Configure Symbol, 3. Risk Management, 4. Review & Create
 */

import React, { useState, useCallback, useEffect } from 'react';
import {
  X,
  ChevronRight,
  ChevronLeft,
  Shield,
  Target,
  Rocket,
  Settings,
  AlertTriangle,
  Check,
  Loader2,
} from 'lucide-react';
import { useBotTemplates, useCreateBot } from '../../hooks/useBots';
import type {
  BotTemplate,
  StrategyType,
  Timeframe,
  CreateBotInput,
} from '../../../../services/bots.service';

interface CreateBotModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

type Step = 1 | 2 | 3 | 4;

interface FormData {
  strategyType: StrategyType | null;
  name: string;
  symbols: string[];
  timeframe: Timeframe;
  initialCapital: number;
  maxPositionSizePct: number;
  maxDailyLossPct: number;
  maxDrawdownPct: number;
}

const INITIAL_FORM_DATA: FormData = {
  strategyType: null,
  name: '',
  symbols: [],
  timeframe: '1h',
  initialCapital: 10000,
  maxPositionSizePct: 10,
  maxDailyLossPct: 3,
  maxDrawdownPct: 10,
};

const TIMEFRAME_OPTIONS: { value: Timeframe; label: string }[] = [
  { value: '1m', label: '1 Minute' },
  { value: '5m', label: '5 Minutes' },
  { value: '15m', label: '15 Minutes' },
  { value: '30m', label: '30 Minutes' },
  { value: '1h', label: '1 Hour' },
  { value: '4h', label: '4 Hours' },
  { value: '1d', label: '1 Day' },
];

const POPULAR_SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'XRPUSDT', 'ADAUSDT'];

export const CreateBotModal: React.FC<CreateBotModalProps> = ({ isOpen, onClose, onSuccess }) => {
  const [step, setStep] = useState<Step>(1);
  const [formData, setFormData] = useState<FormData>(INITIAL_FORM_DATA);
  const [symbolInput, setSymbolInput] = useState('');

  const { data: templates, isLoading: templatesLoading } = useBotTemplates();
  const createBotMutation = useCreateBot();

  // Reset form when modal closes
  useEffect(() => {
    if (!isOpen) {
      setStep(1);
      setFormData(INITIAL_FORM_DATA);
      setSymbolInput('');
    }
  }, [isOpen]);

  const handleClose = useCallback(() => {
    onClose();
  }, [onClose]);

  const handleSelectTemplate = useCallback((type: StrategyType, template?: BotTemplate) => {
    setFormData((prev) => ({
      ...prev,
      strategyType: type,
      name: template ? `My ${template.name.split(' - ')[0]} Bot` : 'My Custom Bot',
      timeframe: template?.recommendedTimeframes[0] || '1h',
      symbols: template?.recommendedSymbols.slice(0, 3) || [],
    }));
    setStep(2);
  }, []);

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

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

  const handleSubmit = useCallback(async () => {
    if (!formData.strategyType || formData.symbols.length === 0) return;

    const input: CreateBotInput = {
      name: formData.name,
      symbols: formData.symbols,
      timeframe: formData.timeframe,
      initialCapital: formData.initialCapital,
      strategyType: formData.strategyType,
      maxPositionSizePct: formData.maxPositionSizePct,
      maxDailyLossPct: formData.maxDailyLossPct,
      maxDrawdownPct: formData.maxDrawdownPct,
    };

    try {
      await createBotMutation.mutateAsync(input);
      onSuccess?.();
      handleClose();
    } catch (error) {
      console.error('Failed to create bot:', error);
    }
  }, [formData, createBotMutation, onSuccess, handleClose]);

  const canProceedToStep2 = formData.strategyType !== null;
  const canProceedToStep3 = canProceedToStep2 && formData.name.trim() && formData.symbols.length > 0;
  const canProceedToStep4 = canProceedToStep3 && formData.initialCapital >= 100;
  const canSubmit = canProceedToStep4;

  if (!isOpen) return null;

  const selectedTemplate = templates?.find((t) => t.type === formData.strategyType);

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-gray-900 rounded-xl shadow-2xl border border-gray-700 w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-700">
          <div>
            <h2 className="text-xl font-bold text-white">Create Trading Bot</h2>
            <p className="text-gray-400 text-sm mt-1">Step {step} of 4</p>
          </div>
          <button onClick={handleClose} className="text-gray-400 hover:text-white transition-colors">
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* Progress Bar */}
        <div className="px-6 pt-4">
          <div className="flex gap-2">
            {[1, 2, 3, 4].map((s) => (
              <div
                key={s}
                className={`h-1 flex-1 rounded-full transition-colors ${
                  s <= step ? 'bg-blue-500' : 'bg-gray-700'
                }`}
              />
            ))}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* Step 1: Select Template */}
          {step === 1 && (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-white mb-4">Select Bot Template</h3>

              {templatesLoading ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
                </div>
              ) : (
                <div className="grid gap-4">
                  {templates?.map((template) => (
                    <TemplateCard
                      key={template.type}
                      template={template}
                      selected={formData.strategyType === template.type}
                      onClick={() => handleSelectTemplate(template.type, template)}
                    />
                  ))}
                  <TemplateCard
                    template={{
                      type: 'custom',
                      name: 'Custom Strategy',
                      description: 'Build your own strategy from scratch',
                      riskLevel: 'medium',
                      recommendedTimeframes: ['1h'],
                      recommendedSymbols: ['BTCUSDT'],
                      defaultConfig: {},
                    }}
                    selected={formData.strategyType === 'custom'}
                    onClick={() => handleSelectTemplate('custom')}
                  />
                </div>
              )}
            </div>
          )}

          {/* Step 2: Configure Symbol */}
          {step === 2 && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-white">Configure Trading Pair</h3>

              {/* Bot Name */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Bot Name</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                  className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="My Trading Bot"
                />
              </div>

              {/* Symbols */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Trading Symbols</label>
                <div className="flex gap-2 mb-3">
                  <input
                    type="text"
                    value={symbolInput}
                    onChange={(e) => setSymbolInput(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && handleAddSymbol()}
                    className="flex-1 px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Enter symbol (e.g., BTCUSDT)"
                  />
                  <button
                    onClick={handleAddSymbol}
                    className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
                  >
                    Add
                  </button>
                </div>

                {/* Selected Symbols */}
                <div className="flex flex-wrap gap-2 mb-4">
                  {formData.symbols.map((symbol) => (
                    <span
                      key={symbol}
                      className="inline-flex items-center gap-1 px-3 py-1 bg-blue-600/20 text-blue-400 rounded-full text-sm"
                    >
                      {symbol}
                      <button onClick={() => handleRemoveSymbol(symbol)} className="hover:text-blue-300">
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  ))}
                </div>

                {/* Quick Add */}
                <div className="mt-2">
                  <span className="text-xs text-gray-500">Quick add:</span>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {POPULAR_SYMBOLS.filter((s) => !formData.symbols.includes(s)).map((symbol) => (
                      <button
                        key={symbol}
                        onClick={() =>
                          setFormData((prev) => ({ ...prev, symbols: [...prev.symbols, symbol] }))
                        }
                        className="px-2 py-1 text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 rounded transition-colors"
                      >
                        +{symbol}
                      </button>
                    ))}
                  </div>
                </div>
              </div>

              {/* Timeframe */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Timeframe</label>
                <select
                  value={formData.timeframe}
                  onChange={(e) => setFormData((prev) => ({ ...prev, timeframe: e.target.value as Timeframe }))}
                  className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  {TIMEFRAME_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
                {selectedTemplate && (
                  <p className="text-xs text-gray-500 mt-1">
                    Recommended: {selectedTemplate.recommendedTimeframes.join(', ')}
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Step 3: Risk Management */}
          {step === 3 && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-white">Risk Management</h3>

              {/* Initial Capital */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">Initial Capital (USD)</label>
                <input
                  type="number"
                  min={100}
                  value={formData.initialCapital}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, initialCapital: Number(e.target.value) }))
                  }
                  className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <p className="text-xs text-gray-500 mt-1">Minimum: $100</p>
              </div>

              {/* Max Position Size */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Max Position Size (% of capital)
                </label>
                <input
                  type="number"
                  min={1}
                  max={100}
                  value={formData.maxPositionSizePct}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, maxPositionSizePct: Number(e.target.value) }))
                  }
                  className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Max Daily Loss */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Max Daily Loss (% of capital)
                </label>
                <input
                  type="number"
                  min={0.5}
                  max={20}
                  step={0.5}
                  value={formData.maxDailyLossPct}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, maxDailyLossPct: Number(e.target.value) }))
                  }
                  className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Max Drawdown */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Max Drawdown (% of capital)
                </label>
                <input
                  type="number"
                  min={1}
                  max={50}
                  value={formData.maxDrawdownPct}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, maxDrawdownPct: Number(e.target.value) }))
                  }
                  className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Risk Warning */}
              <div className="flex items-start gap-3 p-4 bg-yellow-900/20 border border-yellow-700/50 rounded-lg">
                <AlertTriangle className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" />
                <div className="text-sm text-yellow-400">
                  <p className="font-semibold">Risk Warning</p>
                  <p className="text-yellow-500/80 mt-1">
                    Trading involves substantial risk. Never trade with money you cannot afford to lose.
                    Past performance does not guarantee future results.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Step 4: Review */}
          {step === 4 && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-white">Review Configuration</h3>

              <div className="space-y-4">
                <ReviewItem label="Strategy" value={selectedTemplate?.name || 'Custom'} />
                <ReviewItem label="Bot Name" value={formData.name} />
                <ReviewItem label="Symbols" value={formData.symbols.join(', ')} />
                <ReviewItem
                  label="Timeframe"
                  value={TIMEFRAME_OPTIONS.find((t) => t.value === formData.timeframe)?.label || formData.timeframe}
                />
                <ReviewItem label="Initial Capital" value={`$${formData.initialCapital.toLocaleString()}`} />
                <ReviewItem label="Max Position Size" value={`${formData.maxPositionSizePct}%`} />
                <ReviewItem label="Max Daily Loss" value={`${formData.maxDailyLossPct}%`} />
                <ReviewItem label="Max Drawdown" value={`${formData.maxDrawdownPct}%`} />
              </div>

              {createBotMutation.isError && (
                <div className="p-4 bg-red-900/20 border border-red-700/50 rounded-lg text-red-400 text-sm">
                  {createBotMutation.error instanceof Error
                    ? createBotMutation.error.message
                    : 'Failed to create bot'}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-6 border-t border-gray-700">
          <button
            onClick={() => (step === 1 ? handleClose() : setStep((s) => (s - 1) as Step))}
            className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white transition-colors"
          >
            <ChevronLeft className="w-4 h-4" />
            {step === 1 ? 'Cancel' : 'Back'}
          </button>

          {step < 4 ? (
            <button
              onClick={() => setStep((s) => (s + 1) as Step)}
              disabled={
                (step === 1 && !canProceedToStep2) ||
                (step === 2 && !canProceedToStep3) ||
                (step === 3 && !canProceedToStep4)
              }
              className="flex items-center gap-2 px-6 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
            >
              Next
              <ChevronRight className="w-4 h-4" />
            </button>
          ) : (
            <button
              onClick={handleSubmit}
              disabled={!canSubmit || createBotMutation.isPending}
              className="flex items-center gap-2 px-6 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-700 disabled:text-gray-500 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
            >
              {createBotMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Creating...
                </>
              ) : (
                <>
                  <Check className="w-4 h-4" />
                  Create Bot
                </>
              )}
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================================
// Sub-components
// ============================================================================

interface TemplateCardProps {
  template: BotTemplate;
  selected: boolean;
  onClick: () => void;
}

const TemplateCard: React.FC<TemplateCardProps> = ({ template, selected, onClick }) => {
  const getIcon = () => {
    switch (template.type) {
      case 'atlas':
        return <Shield className="w-6 h-6" />;
      case 'orion':
        return <Target className="w-6 h-6" />;
      case 'nova':
        return <Rocket className="w-6 h-6" />;
      default:
        return <Settings className="w-6 h-6" />;
    }
  };

  const getColor = () => {
    switch (template.type) {
      case 'atlas':
        return 'bg-blue-600';
      case 'orion':
        return 'bg-purple-600';
      case 'nova':
        return 'bg-orange-600';
      default:
        return 'bg-gray-600';
    }
  };

  const getRiskColor = () => {
    switch (template.riskLevel) {
      case 'low':
        return 'text-green-400';
      case 'medium':
        return 'text-yellow-400';
      case 'high':
        return 'text-red-400';
      default:
        return 'text-gray-400';
    }
  };

  return (
    <button
      onClick={onClick}
      className={`w-full p-4 rounded-lg border transition-all text-left ${
        selected
          ? 'bg-blue-900/30 border-blue-500'
          : 'bg-gray-800 border-gray-700 hover:border-gray-600'
      }`}
    >
      <div className="flex items-start gap-4">
        <div className={`p-3 rounded-lg ${getColor()}`}>{getIcon()}</div>
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <h4 className="text-white font-semibold">{template.name}</h4>
            <span className={`text-xs ${getRiskColor()}`}>
              {template.riskLevel.charAt(0).toUpperCase() + template.riskLevel.slice(1)} Risk
            </span>
          </div>
          <p className="text-gray-400 text-sm mt-1">{template.description}</p>
        </div>
        {selected && <Check className="w-5 h-5 text-blue-500" />}
      </div>
    </button>
  );
};

interface ReviewItemProps {
  label: string;
  value: string;
}

const ReviewItem: React.FC<ReviewItemProps> = ({ label, value }) => (
  <div className="flex justify-between items-center py-2 border-b border-gray-800">
    <span className="text-gray-400">{label}</span>
    <span className="text-white font-medium">{value}</span>
  </div>
);

export default CreateBotModal;
