/**
 * StrategyTemplateSelector Component
 * Pre-built strategy templates with AI quick-suggestions
 * OQI-007: LLM Strategy Agent
 */

import React, { useState } from 'react';
import {
  SparklesIcon,
  ChartBarIcon,
  ArrowTrendingUpIcon,
  ArrowsRightLeftIcon,
  BoltIcon,
  ClockIcon,
  ScaleIcon,
  CheckCircleIcon,
  XMarkIcon,
  InformationCircleIcon,
} from '@heroicons/react/24/outline';
import { StarIcon } from '@heroicons/react/24/solid';

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

export interface StrategyTemplate {
  id: string;
  name: string;
  description: string;
  category: 'trend' | 'reversal' | 'breakout' | 'scalping' | 'swing' | 'position';
  riskLevel: 'low' | 'medium' | 'high';
  metrics: {
    winRate: number;
    avgRR: number;
    maxDrawdown: number;
    sharpeRatio: number;
  };
  bestTimeframes: string[];
  indicators: string[];
  marketConditions: string[];
  isAIRecommended?: boolean;
  popularity?: number;
}

interface StrategyTemplateSelectorProps {
  templates: StrategyTemplate[];
  aiRecommendations?: string[];
  onSelectTemplate: (template: StrategyTemplate) => void;
  onCompare?: (templates: StrategyTemplate[]) => void;
  selectedTemplateId?: string;
  compact?: boolean;
}

// ============================================================================
// Helper Functions
// ============================================================================

const getCategoryIcon = (category: StrategyTemplate['category']) => {
  switch (category) {
    case 'trend':
      return ArrowTrendingUpIcon;
    case 'reversal':
      return ArrowsRightLeftIcon;
    case 'breakout':
      return BoltIcon;
    case 'scalping':
      return BoltIcon;
    case 'swing':
      return ClockIcon;
    case 'position':
      return ScaleIcon;
    default:
      return ChartBarIcon;
  }
};

const getCategoryColor = (category: StrategyTemplate['category']) => {
  switch (category) {
    case 'trend':
      return 'bg-blue-500/20 text-blue-400';
    case 'reversal':
      return 'bg-purple-500/20 text-purple-400';
    case 'breakout':
      return 'bg-amber-500/20 text-amber-400';
    case 'scalping':
      return 'bg-red-500/20 text-red-400';
    case 'swing':
      return 'bg-emerald-500/20 text-emerald-400';
    case 'position':
      return 'bg-cyan-500/20 text-cyan-400';
    default:
      return 'bg-gray-500/20 text-gray-400';
  }
};

const getRiskColor = (riskLevel: StrategyTemplate['riskLevel']) => {
  switch (riskLevel) {
    case 'low':
      return 'text-emerald-400';
    case 'medium':
      return 'text-yellow-400';
    case 'high':
      return 'text-red-400';
    default:
      return 'text-gray-400';
  }
};

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

export const StrategyTemplateSelector: React.FC<StrategyTemplateSelectorProps> = ({
  templates,
  aiRecommendations = [],
  onSelectTemplate,
  onCompare,
  selectedTemplateId,
  compact = false,
}) => {
  const [filterCategory, setFilterCategory] = useState<StrategyTemplate['category'] | 'all'>('all');
  const [compareMode, setCompareMode] = useState(false);
  const [compareList, setCompareList] = useState<string[]>([]);
  const [showDetails, setShowDetails] = useState<string | null>(null);

  const categories: Array<{ value: StrategyTemplate['category'] | 'all'; label: string }> = [
    { value: 'all', label: 'All' },
    { value: 'trend', label: 'Trend' },
    { value: 'reversal', label: 'Reversal' },
    { value: 'breakout', label: 'Breakout' },
    { value: 'scalping', label: 'Scalping' },
    { value: 'swing', label: 'Swing' },
    { value: 'position', label: 'Position' },
  ];

  const filteredTemplates = templates.filter(
    (t) => filterCategory === 'all' || t.category === filterCategory
  );

  const recommendedTemplates = templates.filter((t) => aiRecommendations.includes(t.id));

  const toggleCompare = (templateId: string) => {
    setCompareList((prev) =>
      prev.includes(templateId)
        ? prev.filter((id) => id !== templateId)
        : prev.length < 3
        ? [...prev, templateId]
        : prev
    );
  };

  const handleCompare = () => {
    const templatesToCompare = templates.filter((t) => compareList.includes(t.id));
    onCompare?.(templatesToCompare);
  };

  const TemplateCard: React.FC<{ template: StrategyTemplate }> = ({ template }) => {
    const Icon = getCategoryIcon(template.category);
    const isSelected = selectedTemplateId === template.id;
    const isInCompare = compareList.includes(template.id);
    const isRecommended = aiRecommendations.includes(template.id);

    return (
      <div
        className={`relative p-4 bg-white dark:bg-gray-800 rounded-xl border-2 transition-all cursor-pointer ${
          isSelected
            ? 'border-primary-500 ring-2 ring-primary-500/20'
            : isInCompare
            ? 'border-emerald-500'
            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
        }`}
        onClick={() => !compareMode && onSelectTemplate(template)}
      >
        {/* AI Recommended Badge */}
        {isRecommended && (
          <div className="absolute -top-2 -right-2 flex items-center gap-1 px-2 py-0.5 bg-gradient-to-r from-purple-500 to-pink-500 text-white text-xs font-medium rounded-full">
            <SparklesIcon className="w-3 h-3" />
            AI Pick
          </div>
        )}

        {/* Compare Checkbox */}
        {compareMode && (
          <div
            onClick={(e) => {
              e.stopPropagation();
              toggleCompare(template.id);
            }}
            className="absolute top-3 right-3"
          >
            <div
              className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
                isInCompare
                  ? 'bg-emerald-500 border-emerald-500'
                  : 'border-gray-300 dark:border-gray-600'
              }`}
            >
              {isInCompare && <CheckCircleIcon className="w-4 h-4 text-white" />}
            </div>
          </div>
        )}

        {/* Header */}
        <div className="flex items-start gap-3 mb-3">
          <div className={`p-2 rounded-lg ${getCategoryColor(template.category)}`}>
            <Icon className="w-5 h-5" />
          </div>
          <div className="flex-1 min-w-0">
            <h4 className="font-semibold text-gray-900 dark:text-white truncate">
              {template.name}
            </h4>
            <p className="text-sm text-gray-500 dark:text-gray-400 line-clamp-2">
              {template.description}
            </p>
          </div>
        </div>

        {/* Metrics */}
        <div className="grid grid-cols-2 gap-2 mb-3">
          <div className="text-center p-2 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <div className="text-lg font-bold text-emerald-400">{template.metrics.winRate}%</div>
            <div className="text-xs text-gray-500">Win Rate</div>
          </div>
          <div className="text-center p-2 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
            <div className="text-lg font-bold text-blue-400">{template.metrics.avgRR}:1</div>
            <div className="text-xs text-gray-500">Avg R:R</div>
          </div>
        </div>

        {/* Tags */}
        <div className="flex flex-wrap gap-1">
          <span className={`px-2 py-0.5 text-xs rounded capitalize ${getRiskColor(template.riskLevel)}`}>
            {template.riskLevel} risk
          </span>
          {template.bestTimeframes.slice(0, 2).map((tf) => (
            <span key={tf} className="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded">
              {tf}
            </span>
          ))}
        </div>

        {/* Info Button */}
        <button
          onClick={(e) => {
            e.stopPropagation();
            setShowDetails(showDetails === template.id ? null : template.id);
          }}
          className="absolute bottom-3 right-3 p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
        >
          <InformationCircleIcon className="w-4 h-4" />
        </button>
      </div>
    );
  };

  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 mb-3">
          <div className="flex items-center gap-2">
            <ChartBarIcon className="w-5 h-5 text-primary-500" />
            <h3 className="font-semibold text-gray-900 dark:text-white">Strategy Templates</h3>
          </div>
          {onCompare && (
            <button
              onClick={() => {
                if (compareMode && compareList.length >= 2) {
                  handleCompare();
                }
                setCompareMode(!compareMode);
                if (!compareMode) setCompareList([]);
              }}
              className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
                compareMode
                  ? compareList.length >= 2
                    ? 'bg-emerald-500 text-white'
                    : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                  : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
              }`}
            >
              {compareMode
                ? compareList.length >= 2
                  ? `Compare (${compareList.length})`
                  : `Select ${2 - compareList.length} more`
                : 'Compare'}
            </button>
          )}
        </div>

        {/* Category Filter */}
        <div className="flex gap-1 overflow-x-auto pb-1">
          {categories.map((cat) => (
            <button
              key={cat.value}
              onClick={() => setFilterCategory(cat.value)}
              className={`px-3 py-1 text-sm rounded-lg whitespace-nowrap transition-colors ${
                filterCategory === cat.value
                  ? 'bg-primary-500 text-white'
                  : 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700'
              }`}
            >
              {cat.label}
            </button>
          ))}
        </div>
      </div>

      {/* AI Recommendations */}
      {recommendedTemplates.length > 0 && filterCategory === 'all' && (
        <div className="p-4 bg-gradient-to-r from-purple-500/10 to-pink-500/10 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2 mb-3">
            <SparklesIcon className="w-4 h-4 text-purple-400" />
            <span className="text-sm font-medium text-purple-400">AI Recommended for Current Market</span>
          </div>
          <div className={`grid ${compact ? 'grid-cols-1' : 'grid-cols-2 lg:grid-cols-3'} gap-3`}>
            {recommendedTemplates.slice(0, 3).map((template) => (
              <TemplateCard key={template.id} template={template} />
            ))}
          </div>
        </div>
      )}

      {/* All Templates */}
      <div className="p-4">
        <div className={`grid ${compact ? 'grid-cols-1' : 'grid-cols-2 lg:grid-cols-3'} gap-3`}>
          {filteredTemplates
            .filter((t) => !aiRecommendations.includes(t.id) || filterCategory !== 'all')
            .map((template) => (
              <TemplateCard key={template.id} template={template} />
            ))}
        </div>

        {filteredTemplates.length === 0 && (
          <div className="text-center py-8 text-gray-500">
            No templates found for this category
          </div>
        )}
      </div>

      {/* Details Modal */}
      {showDetails && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-900 rounded-xl max-w-lg w-full max-h-[80vh] overflow-y-auto">
            {(() => {
              const template = templates.find((t) => t.id === showDetails);
              if (!template) return null;
              const Icon = getCategoryIcon(template.category);

              return (
                <>
                  <div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`p-2 rounded-lg ${getCategoryColor(template.category)}`}>
                        <Icon className="w-5 h-5" />
                      </div>
                      <h4 className="font-semibold text-gray-900 dark:text-white">{template.name}</h4>
                    </div>
                    <button onClick={() => setShowDetails(null)}>
                      <XMarkIcon className="w-5 h-5 text-gray-400" />
                    </button>
                  </div>
                  <div className="p-4 space-y-4">
                    <p className="text-gray-600 dark:text-gray-400">{template.description}</p>

                    <div>
                      <h5 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Performance Metrics</h5>
                      <div className="grid grid-cols-2 gap-3">
                        <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                          <div className="text-xl font-bold text-emerald-400">{template.metrics.winRate}%</div>
                          <div className="text-xs text-gray-500">Win Rate</div>
                        </div>
                        <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                          <div className="text-xl font-bold text-blue-400">{template.metrics.avgRR}:1</div>
                          <div className="text-xs text-gray-500">Avg R:R</div>
                        </div>
                        <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                          <div className="text-xl font-bold text-red-400">{template.metrics.maxDrawdown}%</div>
                          <div className="text-xs text-gray-500">Max Drawdown</div>
                        </div>
                        <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                          <div className="text-xl font-bold text-purple-400">{template.metrics.sharpeRatio}</div>
                          <div className="text-xs text-gray-500">Sharpe Ratio</div>
                        </div>
                      </div>
                    </div>

                    <div>
                      <h5 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Best Timeframes</h5>
                      <div className="flex flex-wrap gap-2">
                        {template.bestTimeframes.map((tf) => (
                          <span key={tf} className="px-3 py-1 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 rounded-lg text-sm">
                            {tf}
                          </span>
                        ))}
                      </div>
                    </div>

                    <div>
                      <h5 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Indicators Used</h5>
                      <div className="flex flex-wrap gap-2">
                        {template.indicators.map((ind) => (
                          <span key={ind} className="px-3 py-1 bg-primary-500/20 text-primary-400 rounded-lg text-sm">
                            {ind}
                          </span>
                        ))}
                      </div>
                    </div>

                    <div>
                      <h5 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Best Market Conditions</h5>
                      <div className="flex flex-wrap gap-2">
                        {template.marketConditions.map((cond) => (
                          <span key={cond} className="px-3 py-1 bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 rounded-lg text-sm">
                            {cond}
                          </span>
                        ))}
                      </div>
                    </div>

                    <button
                      onClick={() => {
                        onSelectTemplate(template);
                        setShowDetails(null);
                      }}
                      className="w-full py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg font-medium transition-colors"
                    >
                      Use This Template
                    </button>
                  </div>
                </>
              );
            })()}
          </div>
        </div>
      )}
    </div>
  );
};

export default StrategyTemplateSelector;
