/**
 * PromptLibrary Component
 * Browse and select predefined prompts/templates for LLM interactions
 * OQI-007: LLM Strategy Agent
 */

import React, { useState, useMemo } from 'react';
import {
  BookOpen,
  Search,
  Star,
  StarOff,
  Clock,
  TrendingUp,
  BarChart3,
  Brain,
  Target,
  Zap,
  Copy,
  Check,
  ChevronRight,
  Filter,
  X,
  Plus,
} from 'lucide-react';

export type PromptCategory =
  | 'analysis'
  | 'strategy'
  | 'education'
  | 'trading'
  | 'risk'
  | 'custom';

export interface Prompt {
  id: string;
  title: string;
  description: string;
  template: string;
  category: PromptCategory;
  tags: string[];
  variables?: string[]; // Placeholders like {{symbol}}, {{timeframe}}
  isFavorite?: boolean;
  usageCount?: number;
  lastUsed?: string;
  createdBy?: 'system' | 'user';
}

export interface PromptLibraryProps {
  prompts: Prompt[];
  onSelectPrompt: (prompt: Prompt) => void;
  onToggleFavorite?: (promptId: string) => void;
  onCreatePrompt?: () => void;
  selectedPromptId?: string;
  showSearch?: boolean;
  showCategories?: boolean;
  compact?: boolean;
}

const CATEGORY_CONFIG: Record<PromptCategory, {
  icon: React.ReactNode;
  label: string;
  color: string;
  bgColor: string;
}> = {
  analysis: {
    icon: <BarChart3 className="w-4 h-4" />,
    label: 'Analysis',
    color: 'text-blue-400',
    bgColor: 'bg-blue-500/20',
  },
  strategy: {
    icon: <Target className="w-4 h-4" />,
    label: 'Strategy',
    color: 'text-purple-400',
    bgColor: 'bg-purple-500/20',
  },
  education: {
    icon: <BookOpen className="w-4 h-4" />,
    label: 'Education',
    color: 'text-green-400',
    bgColor: 'bg-green-500/20',
  },
  trading: {
    icon: <TrendingUp className="w-4 h-4" />,
    label: 'Trading',
    color: 'text-yellow-400',
    bgColor: 'bg-yellow-500/20',
  },
  risk: {
    icon: <Zap className="w-4 h-4" />,
    label: 'Risk',
    color: 'text-red-400',
    bgColor: 'bg-red-500/20',
  },
  custom: {
    icon: <Brain className="w-4 h-4" />,
    label: 'Custom',
    color: 'text-cyan-400',
    bgColor: 'bg-cyan-500/20',
  },
};

const PromptLibrary: React.FC<PromptLibraryProps> = ({
  prompts,
  onSelectPrompt,
  onToggleFavorite,
  onCreatePrompt,
  selectedPromptId,
  showSearch = true,
  showCategories = true,
  compact = false,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<PromptCategory | 'all'>('all');
  const [showFavoritesOnly, setShowFavoritesOnly] = useState(false);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  const filteredPrompts = useMemo(() => {
    return prompts.filter((prompt) => {
      // Search filter
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        const matchesTitle = prompt.title.toLowerCase().includes(query);
        const matchesDescription = prompt.description.toLowerCase().includes(query);
        const matchesTags = prompt.tags.some((tag) => tag.toLowerCase().includes(query));
        if (!matchesTitle && !matchesDescription && !matchesTags) return false;
      }

      // Category filter
      if (selectedCategory !== 'all' && prompt.category !== selectedCategory) return false;

      // Favorites filter
      if (showFavoritesOnly && !prompt.isFavorite) return false;

      return true;
    });
  }, [prompts, searchQuery, selectedCategory, showFavoritesOnly]);

  const categories = useMemo(() => {
    const counts: Record<string, number> = { all: prompts.length };
    prompts.forEach((p) => {
      counts[p.category] = (counts[p.category] || 0) + 1;
    });
    return counts;
  }, [prompts]);

  const handleCopyPrompt = async (prompt: Prompt) => {
    try {
      await navigator.clipboard.writeText(prompt.template);
      setCopiedId(prompt.id);
      setTimeout(() => setCopiedId(null), 2000);
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  };

  const PromptCard: React.FC<{ prompt: Prompt }> = ({ prompt }) => {
    const config = CATEGORY_CONFIG[prompt.category];
    const isSelected = prompt.id === selectedPromptId;

    return (
      <div
        onClick={() => onSelectPrompt(prompt)}
        className={`p-4 rounded-lg border cursor-pointer transition-all ${
          isSelected
            ? 'bg-blue-500/20 border-blue-500'
            : 'bg-gray-800/50 border-gray-700 hover:border-gray-600 hover:bg-gray-800'
        }`}
      >
        {/* Header */}
        <div className="flex items-start justify-between mb-2">
          <div className="flex items-center gap-2">
            <div className={`p-1.5 rounded ${config.bgColor} ${config.color}`}>
              {config.icon}
            </div>
            <div>
              <h4 className="font-medium text-white text-sm">{prompt.title}</h4>
              {!compact && (
                <span className={`text-xs ${config.color}`}>{config.label}</span>
              )}
            </div>
          </div>

          <div className="flex items-center gap-1">
            {onToggleFavorite && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onToggleFavorite(prompt.id);
                }}
                className={`p-1 rounded hover:bg-gray-700 transition-colors ${
                  prompt.isFavorite ? 'text-yellow-400' : 'text-gray-500'
                }`}
              >
                {prompt.isFavorite ? (
                  <Star className="w-4 h-4 fill-current" />
                ) : (
                  <StarOff className="w-4 h-4" />
                )}
              </button>
            )}
            <button
              onClick={(e) => {
                e.stopPropagation();
                handleCopyPrompt(prompt);
              }}
              className="p-1 rounded hover:bg-gray-700 transition-colors text-gray-500 hover:text-white"
              title="Copy prompt"
            >
              {copiedId === prompt.id ? (
                <Check className="w-4 h-4 text-green-400" />
              ) : (
                <Copy className="w-4 h-4" />
              )}
            </button>
          </div>
        </div>

        {/* Description */}
        {!compact && (
          <p className="text-sm text-gray-400 mb-3 line-clamp-2">{prompt.description}</p>
        )}

        {/* Tags */}
        {prompt.tags.length > 0 && (
          <div className="flex flex-wrap gap-1 mb-2">
            {prompt.tags.slice(0, compact ? 2 : 4).map((tag) => (
              <span
                key={tag}
                className="px-2 py-0.5 text-xs bg-gray-700 text-gray-300 rounded"
              >
                {tag}
              </span>
            ))}
            {prompt.tags.length > (compact ? 2 : 4) && (
              <span className="px-2 py-0.5 text-xs text-gray-500">
                +{prompt.tags.length - (compact ? 2 : 4)}
              </span>
            )}
          </div>
        )}

        {/* Variables preview */}
        {!compact && prompt.variables && prompt.variables.length > 0 && (
          <div className="flex items-center gap-1 text-xs text-gray-500">
            <span>Variables:</span>
            {prompt.variables.slice(0, 3).map((v) => (
              <code key={v} className="px-1 bg-gray-700 rounded text-cyan-400">
                {`{{${v}}}`}
              </code>
            ))}
          </div>
        )}

        {/* Footer */}
        {!compact && (prompt.usageCount || prompt.lastUsed) && (
          <div className="flex items-center justify-between mt-3 pt-2 border-t border-gray-700 text-xs text-gray-500">
            {prompt.usageCount !== undefined && (
              <span>Used {prompt.usageCount} times</span>
            )}
            {prompt.lastUsed && (
              <span className="flex items-center gap-1">
                <Clock className="w-3 h-3" />
                {new Date(prompt.lastUsed).toLocaleDateString()}
              </span>
            )}
          </div>
        )}

        {/* Select indicator */}
        {isSelected && (
          <div className="flex items-center justify-end mt-2">
            <ChevronRight className="w-4 h-4 text-blue-400" />
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="flex flex-col h-full bg-gray-800/50 rounded-xl border border-gray-700">
      {/* Header */}
      <div className="p-4 border-b border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <BookOpen className="w-5 h-5 text-purple-400" />
            <h3 className="font-semibold text-white">Prompt Library</h3>
            <span className="text-xs text-gray-500">({filteredPrompts.length})</span>
          </div>
          {onCreatePrompt && (
            <button
              onClick={onCreatePrompt}
              className="flex items-center gap-1 px-3 py-1.5 text-sm bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors"
            >
              <Plus className="w-4 h-4" />
              New
            </button>
          )}
        </div>

        {/* Search */}
        {showSearch && (
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search prompts..."
              className="w-full pl-10 pr-4 py-2 bg-gray-900/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-purple-500"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"
              >
                <X className="w-4 h-4" />
              </button>
            )}
          </div>
        )}
      </div>

      {/* Category Filters */}
      {showCategories && (
        <div className="p-3 border-b border-gray-700 flex items-center gap-2 overflow-x-auto">
          <button
            onClick={() => setSelectedCategory('all')}
            className={`px-3 py-1.5 text-sm rounded-lg whitespace-nowrap transition-colors ${
              selectedCategory === 'all'
                ? 'bg-purple-500 text-white'
                : 'text-gray-400 hover:bg-gray-700'
            }`}
          >
            All ({categories.all || 0})
          </button>
          {Object.entries(CATEGORY_CONFIG).map(([key, config]) => (
            <button
              key={key}
              onClick={() => setSelectedCategory(key as PromptCategory)}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg whitespace-nowrap transition-colors ${
                selectedCategory === key
                  ? `${config.bgColor} ${config.color}`
                  : 'text-gray-400 hover:bg-gray-700'
              }`}
            >
              {config.icon}
              <span>{config.label}</span>
              <span className="text-xs opacity-75">({categories[key] || 0})</span>
            </button>
          ))}
        </div>
      )}

      {/* Filter Bar */}
      <div className="px-4 py-2 flex items-center gap-2 border-b border-gray-700">
        <button
          onClick={() => setShowFavoritesOnly(!showFavoritesOnly)}
          className={`flex items-center gap-1.5 px-3 py-1 text-sm rounded-lg transition-colors ${
            showFavoritesOnly
              ? 'bg-yellow-500/20 text-yellow-400'
              : 'text-gray-400 hover:bg-gray-700'
          }`}
        >
          <Star className={`w-4 h-4 ${showFavoritesOnly ? 'fill-current' : ''}`} />
          Favorites
        </button>
      </div>

      {/* Prompts Grid */}
      <div className="flex-1 overflow-y-auto p-4">
        {filteredPrompts.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-gray-500">
            <BookOpen className="w-12 h-12 mb-3 opacity-50" />
            <p className="text-sm">No prompts found</p>
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="mt-2 text-sm text-purple-400 hover:text-purple-300"
              >
                Clear search
              </button>
            )}
          </div>
        ) : (
          <div className={`grid gap-3 ${compact ? 'grid-cols-1' : 'grid-cols-1 lg:grid-cols-2'}`}>
            {filteredPrompts.map((prompt) => (
              <PromptCard key={prompt.id} prompt={prompt} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default PromptLibrary;
