/**
 * AnalysisRequestForm Component
 * Structured request builder for complex LLM analysis tasks
 * OQI-007: LLM Strategy Agent
 */

import React, { useState, useMemo } from 'react';
import {
  ChartBarIcon,
  CalendarIcon,
  AdjustmentsHorizontalIcon,
  BeakerIcon,
  DocumentTextIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  PaperAirplaneIcon,
  BookmarkIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import { SparklesIcon } from '@heroicons/react/24/solid';

// ============================================================================
// Types
// ============================================================================

export interface AnalysisRequest {
  symbol: string;
  timeframes: string[];
  dateRange: { start: string; end: string };
  indicators: string[];
  strategyType: string;
  riskParams: {
    maxDrawdown: number;
    riskPerTrade: number;
    targetRR: number;
  };
  includeContext: {
    recentSignals: boolean;
    portfolioContext: boolean;
    marketRegime: boolean;
  };
  notes?: string;
}

export interface AnalysisTemplate {
  id: string;
  name: string;
  description: string;
  config: Partial<AnalysisRequest>;
}

interface AnalysisRequestFormProps {
  onSubmit: (request: AnalysisRequest) => void;
  onSaveTemplate?: (template: Omit<AnalysisTemplate, 'id'>) => void;
  savedTemplates?: AnalysisTemplate[];
  onLoadTemplate?: (templateId: string) => void;
  initialSymbol?: string;
  isLoading?: boolean;
  estimatedTokens?: number;
}

// ============================================================================
// Constants
// ============================================================================

const TIMEFRAMES = ['1m', '5m', '15m', '30m', '1h', '4h', '1d', '1w'];
const INDICATORS = [
  'SMA', 'EMA', 'RSI', 'MACD', 'Bollinger Bands', 'ATR', 'Stochastic',
  'VWAP', 'Fibonacci', 'Ichimoku', 'Volume Profile', 'OBV',
];
const STRATEGY_TYPES = [
  'Trend Following', 'Mean Reversion', 'Breakout', 'Scalping',
  'Swing Trading', 'Position Trading', 'Custom',
];

// ============================================================================
// Component
// ============================================================================

export const AnalysisRequestForm: React.FC<AnalysisRequestFormProps> = ({
  onSubmit,
  onSaveTemplate,
  savedTemplates = [],
  onLoadTemplate,
  initialSymbol = '',
  isLoading = false,
  estimatedTokens,
}) => {
  const [expandedSection, setExpandedSection] = useState<string>('symbol');
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [templateName, setTemplateName] = useState('');

  const [request, setRequest] = useState<AnalysisRequest>({
    symbol: initialSymbol,
    timeframes: ['1h', '4h'],
    dateRange: {
      start: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      end: new Date().toISOString().split('T')[0],
    },
    indicators: ['EMA', 'RSI', 'MACD'],
    strategyType: 'Trend Following',
    riskParams: {
      maxDrawdown: 10,
      riskPerTrade: 2,
      targetRR: 2,
    },
    includeContext: {
      recentSignals: true,
      portfolioContext: false,
      marketRegime: true,
    },
    notes: '',
  });

  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? '' : section);
  };

  const updateRequest = <K extends keyof AnalysisRequest>(
    key: K,
    value: AnalysisRequest[K]
  ) => {
    setRequest((prev) => ({ ...prev, [key]: value }));
  };

  const toggleTimeframe = (tf: string) => {
    setRequest((prev) => ({
      ...prev,
      timeframes: prev.timeframes.includes(tf)
        ? prev.timeframes.filter((t) => t !== tf)
        : [...prev.timeframes, tf],
    }));
  };

  const toggleIndicator = (indicator: string) => {
    setRequest((prev) => ({
      ...prev,
      indicators: prev.indicators.includes(indicator)
        ? prev.indicators.filter((i) => i !== indicator)
        : [...prev.indicators, indicator],
    }));
  };

  const isValid = useMemo(() => {
    return (
      request.symbol.trim() !== '' &&
      request.timeframes.length > 0 &&
      request.indicators.length > 0
    );
  }, [request]);

  const handleSubmit = () => {
    if (isValid && !isLoading) {
      onSubmit(request);
    }
  };

  const handleSaveTemplate = () => {
    if (templateName.trim() && onSaveTemplate) {
      onSaveTemplate({
        name: templateName,
        description: `${request.strategyType} analysis for ${request.symbol}`,
        config: request,
      });
      setShowSaveDialog(false);
      setTemplateName('');
    }
  };

  const SectionHeader: React.FC<{
    id: string;
    icon: React.ReactNode;
    title: string;
    badge?: string;
  }> = ({ id, icon, title, badge }) => (
    <button
      onClick={() => toggleSection(id)}
      className="w-full flex items-center justify-between p-3 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
    >
      <div className="flex items-center gap-2">
        <span className="text-gray-500 dark:text-gray-400">{icon}</span>
        <span className="font-medium text-gray-900 dark:text-white">{title}</span>
        {badge && (
          <span className="px-2 py-0.5 bg-primary-500/20 text-primary-400 text-xs rounded-full">
            {badge}
          </span>
        )}
      </div>
      {expandedSection === id ? (
        <ChevronUpIcon className="w-5 h-5 text-gray-400" />
      ) : (
        <ChevronDownIcon className="w-5 h-5 text-gray-400" />
      )}
    </button>
  );

  return (
    <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <SparklesIcon className="w-5 h-5 text-primary-500" />
            <h3 className="font-semibold text-gray-900 dark:text-white">Analysis Request</h3>
          </div>
          {savedTemplates.length > 0 && (
            <select
              onChange={(e) => onLoadTemplate?.(e.target.value)}
              className="text-sm bg-gray-100 dark:bg-gray-800 border-0 rounded-lg px-3 py-1.5 text-gray-700 dark:text-gray-300"
            >
              <option value="">Load Template...</option>
              {savedTemplates.map((t) => (
                <option key={t.id} value={t.id}>{t.name}</option>
              ))}
            </select>
          )}
        </div>
      </div>

      {/* Form Sections */}
      <div className="divide-y divide-gray-200 dark:divide-gray-700">
        {/* Symbol & Timeframes */}
        <div>
          <SectionHeader
            id="symbol"
            icon={<ChartBarIcon className="w-5 h-5" />}
            title="Symbol & Timeframes"
            badge={request.symbol || undefined}
          />
          {expandedSection === 'symbol' && (
            <div className="p-4 pt-0 space-y-4">
              <div>
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">Symbol</label>
                <input
                  type="text"
                  value={request.symbol}
                  onChange={(e) => updateRequest('symbol', e.target.value.toUpperCase())}
                  placeholder="e.g., EURUSD, BTCUSD"
                  className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white placeholder-gray-500 focus:ring-2 focus:ring-primary-500"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-2">Timeframes</label>
                <div className="flex flex-wrap gap-2">
                  {TIMEFRAMES.map((tf) => (
                    <button
                      key={tf}
                      onClick={() => toggleTimeframe(tf)}
                      className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                        request.timeframes.includes(tf)
                          ? 'bg-primary-500 text-white'
                          : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
                      }`}
                    >
                      {tf}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Date Range */}
        <div>
          <SectionHeader
            id="dateRange"
            icon={<CalendarIcon className="w-5 h-5" />}
            title="Date Range"
          />
          {expandedSection === 'dateRange' && (
            <div className="p-4 pt-0 grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">Start Date</label>
                <input
                  type="date"
                  value={request.dateRange.start}
                  onChange={(e) => updateRequest('dateRange', { ...request.dateRange, start: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">End Date</label>
                <input
                  type="date"
                  value={request.dateRange.end}
                  onChange={(e) => updateRequest('dateRange', { ...request.dateRange, end: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white"
                />
              </div>
            </div>
          )}
        </div>

        {/* Indicators */}
        <div>
          <SectionHeader
            id="indicators"
            icon={<AdjustmentsHorizontalIcon className="w-5 h-5" />}
            title="Indicators"
            badge={`${request.indicators.length} selected`}
          />
          {expandedSection === 'indicators' && (
            <div className="p-4 pt-0">
              <div className="flex flex-wrap gap-2">
                {INDICATORS.map((indicator) => (
                  <button
                    key={indicator}
                    onClick={() => toggleIndicator(indicator)}
                    className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                      request.indicators.includes(indicator)
                        ? 'bg-emerald-500 text-white'
                        : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
                    }`}
                  >
                    {indicator}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Strategy & Risk */}
        <div>
          <SectionHeader
            id="strategy"
            icon={<BeakerIcon className="w-5 h-5" />}
            title="Strategy & Risk"
          />
          {expandedSection === 'strategy' && (
            <div className="p-4 pt-0 space-y-4">
              <div>
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">Strategy Type</label>
                <select
                  value={request.strategyType}
                  onChange={(e) => updateRequest('strategyType', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white"
                >
                  {STRATEGY_TYPES.map((type) => (
                    <option key={type} value={type}>{type}</option>
                  ))}
                </select>
              </div>
              <div className="grid grid-cols-3 gap-3">
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Max DD %</label>
                  <input
                    type="number"
                    value={request.riskParams.maxDrawdown}
                    onChange={(e) => updateRequest('riskParams', { ...request.riskParams, maxDrawdown: Number(e.target.value) })}
                    className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white text-sm"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Risk/Trade %</label>
                  <input
                    type="number"
                    value={request.riskParams.riskPerTrade}
                    onChange={(e) => updateRequest('riskParams', { ...request.riskParams, riskPerTrade: Number(e.target.value) })}
                    className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white text-sm"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Target R:R</label>
                  <input
                    type="number"
                    step="0.5"
                    value={request.riskParams.targetRR}
                    onChange={(e) => updateRequest('riskParams', { ...request.riskParams, targetRR: Number(e.target.value) })}
                    className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white text-sm"
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Context Options */}
        <div>
          <SectionHeader
            id="context"
            icon={<DocumentTextIcon className="w-5 h-5" />}
            title="Include Context"
          />
          {expandedSection === 'context' && (
            <div className="p-4 pt-0 space-y-3">
              {[
                { key: 'recentSignals' as const, label: 'Recent Signals', desc: 'Include last 5 generated signals' },
                { key: 'portfolioContext' as const, label: 'Portfolio Context', desc: 'Include current positions' },
                { key: 'marketRegime' as const, label: 'Market Regime', desc: 'Include volatility analysis' },
              ].map((item) => (
                <label key={item.key} className="flex items-start gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={request.includeContext[item.key]}
                    onChange={(e) => updateRequest('includeContext', {
                      ...request.includeContext,
                      [item.key]: e.target.checked,
                    })}
                    className="mt-1 w-4 h-4 rounded border-gray-300 text-primary-500 focus:ring-primary-500"
                  />
                  <div>
                    <div className="text-sm font-medium text-gray-900 dark:text-white">{item.label}</div>
                    <div className="text-xs text-gray-500">{item.desc}</div>
                  </div>
                </label>
              ))}
              <div className="pt-2">
                <label className="block text-sm text-gray-600 dark:text-gray-400 mb-1">Additional Notes</label>
                <textarea
                  value={request.notes}
                  onChange={(e) => updateRequest('notes', e.target.value)}
                  placeholder="Any specific questions or focus areas..."
                  rows={2}
                  className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white placeholder-gray-500 resize-none"
                />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Footer */}
      <div className="p-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
        {estimatedTokens && (
          <div className="text-xs text-gray-500 mb-3">
            Estimated context: ~{estimatedTokens.toLocaleString()} tokens
          </div>
        )}
        <div className="flex items-center gap-2">
          {onSaveTemplate && (
            <button
              onClick={() => setShowSaveDialog(true)}
              className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors flex items-center gap-2"
            >
              <BookmarkIcon className="w-4 h-4" />
              Save
            </button>
          )}
          <button
            onClick={handleSubmit}
            disabled={!isValid || isLoading}
            className="flex-1 px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
          >
            {isLoading ? (
              <>
                <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                Analyzing...
              </>
            ) : (
              <>
                <PaperAirplaneIcon className="w-4 h-4" />
                Run Analysis
              </>
            )}
          </button>
        </div>
      </div>

      {/* Save Template Dialog */}
      {showSaveDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-900 rounded-xl p-6 w-96 shadow-xl">
            <div className="flex items-center justify-between mb-4">
              <h4 className="font-semibold text-gray-900 dark:text-white">Save Template</h4>
              <button onClick={() => setShowSaveDialog(false)}>
                <XMarkIcon className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <input
              type="text"
              value={templateName}
              onChange={(e) => setTemplateName(e.target.value)}
              placeholder="Template name..."
              className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-800 border-0 rounded-lg text-gray-900 dark:text-white mb-4"
            />
            <button
              onClick={handleSaveTemplate}
              disabled={!templateName.trim()}
              className="w-full px-4 py-2 bg-primary-600 text-white rounded-lg font-medium disabled:opacity-50"
            >
              Save Template
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default AnalysisRequestForm;
