/**
 * TradingScreener Component
 * Advanced screener with filters for stocks/forex/crypto
 * Epic: OQI-003 Trading Charts
 */

import React, { useState, useMemo, useCallback } from 'react';
import {
  FunnelIcon,
  MagnifyingGlassIcon,
  ArrowPathIcon,
  ChevronUpIcon,
  ChevronDownIcon,
  StarIcon,
  PlusIcon,
  AdjustmentsHorizontalIcon,
  ArrowDownTrayIcon,
  BookmarkIcon,
  TrashIcon,
  ChartBarIcon,
} from '@heroicons/react/24/solid';
import { StarIcon as StarOutlineIcon } from '@heroicons/react/24/outline';

// Types
export interface ScreenerResult {
  symbol: string;
  name: string;
  sector?: string;
  industry?: string;
  exchange: string;
  price: number;
  change: number;
  changePercent: number;
  volume: number;
  avgVolume: number;
  marketCap?: number;
  pe?: number;
  eps?: number;
  high52w: number;
  low52w: number;
  rsi?: number;
  macdSignal?: 'bullish' | 'bearish' | 'neutral';
  trend?: 'bullish' | 'bearish' | 'sideways';
  sma20?: number;
  sma50?: number;
  sma200?: number;
  atr?: number;
  beta?: number;
  dividendYield?: number;
  isFavorite?: boolean;
  volumeRatio?: number;
  mlSignal?: 'buy' | 'sell' | 'hold' | null;
  mlConfidence?: number;
}

export interface ScreenerFilter {
  id: string;
  field: keyof ScreenerResult;
  operator: 'gt' | 'lt' | 'eq' | 'gte' | 'lte' | 'between' | 'contains';
  value: number | string | [number, number];
  enabled: boolean;
}

export interface SavedScreener {
  id: string;
  name: string;
  filters: ScreenerFilter[];
  createdAt: Date;
}

type SortDirection = 'asc' | 'desc';
type SortField = keyof ScreenerResult;

interface TradingScreenerProps {
  results: ScreenerResult[];
  savedScreeners?: SavedScreener[];
  onSearch?: (query: string) => void;
  onFilterChange?: (filters: ScreenerFilter[]) => void;
  onSaveScreener?: (name: string, filters: ScreenerFilter[]) => void;
  onLoadScreener?: (screener: SavedScreener) => void;
  onDeleteScreener?: (id: string) => void;
  onSymbolClick?: (symbol: string) => void;
  onAddToWatchlist?: (symbol: string) => void;
  onToggleFavorite?: (symbol: string) => void;
  onExport?: (format: 'csv' | 'json') => void;
  onRefresh?: () => void;
  isLoading?: boolean;
  compact?: boolean;
}

const FILTER_PRESETS: { name: string; filters: Omit<ScreenerFilter, 'id'>[] }[] = [
  {
    name: 'High Volume',
    filters: [
      { field: 'volume', operator: 'gt', value: 1000000, enabled: true },
      { field: 'changePercent', operator: 'gt', value: 0, enabled: true },
    ],
  },
  {
    name: 'Oversold (RSI < 30)',
    filters: [{ field: 'rsi', operator: 'lt', value: 30, enabled: true }],
  },
  {
    name: 'Overbought (RSI > 70)',
    filters: [{ field: 'rsi', operator: 'gt', value: 70, enabled: true }],
  },
  {
    name: 'Golden Cross',
    filters: [
      { field: 'sma50', operator: 'gt', value: 0, enabled: true },
      { field: 'sma200', operator: 'gt', value: 0, enabled: true },
    ],
  },
  {
    name: 'Near 52W High',
    filters: [{ field: 'changePercent', operator: 'gt', value: 5, enabled: true }],
  },
  {
    name: 'Bullish Trend',
    filters: [{ field: 'trend', operator: 'eq', value: 'bullish', enabled: true }],
  },
  {
    name: 'Bearish Trend',
    filters: [{ field: 'trend', operator: 'eq', value: 'bearish', enabled: true }],
  },
  {
    name: 'Change > 2%',
    filters: [{ field: 'changePercent', operator: 'gt', value: 2, enabled: true }],
  },
  {
    name: 'ML Buy Signal',
    filters: [{ field: 'mlSignal', operator: 'eq', value: 'buy', enabled: true }],
  },
];

const FILTERABLE_FIELDS: { field: keyof ScreenerResult; label: string; type: 'number' | 'string' }[] = [
  { field: 'price', label: 'Price', type: 'number' },
  { field: 'changePercent', label: 'Change %', type: 'number' },
  { field: 'volume', label: 'Volume', type: 'number' },
  { field: 'volumeRatio', label: 'Vol Ratio', type: 'number' },
  { field: 'marketCap', label: 'Market Cap', type: 'number' },
  { field: 'pe', label: 'P/E Ratio', type: 'number' },
  { field: 'rsi', label: 'RSI', type: 'number' },
  { field: 'beta', label: 'Beta', type: 'number' },
  { field: 'dividendYield', label: 'Dividend Yield', type: 'number' },
  { field: 'sector', label: 'Sector', type: 'string' },
  { field: 'exchange', label: 'Exchange', type: 'string' },
  { field: 'trend', label: 'Trend', type: 'string' },
  { field: 'mlSignal', label: 'ML Signal', type: 'string' },
  { field: 'mlConfidence', label: 'ML Confidence', type: 'number' },
];

const TradingScreener: React.FC<TradingScreenerProps> = ({
  results,
  savedScreeners = [],
  onSearch,
  onFilterChange,
  onSaveScreener,
  onLoadScreener,
  onDeleteScreener,
  onSymbolClick,
  onAddToWatchlist,
  onToggleFavorite,
  onExport,
  onRefresh,
  isLoading = false,
  compact = false,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filters, setFilters] = useState<ScreenerFilter[]>([]);
  const [showFilters, setShowFilters] = useState(false);
  const [showSavedScreeners, setShowSavedScreeners] = useState(false);
  const [sortField, setSortField] = useState<SortField>('changePercent');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  const [newScreenerName, setNewScreenerName] = useState('');

  // Apply filters and sorting
  const filteredResults = useMemo(() => {
    // Enrich results with computed fields if not present
    let filtered = results.map((r) => ({
      ...r,
      volumeRatio: r.volumeRatio ?? (r.avgVolume > 0 ? r.volume / r.avgVolume : undefined),
    }));

    // Search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (r) =>
          r.symbol.toLowerCase().includes(query) ||
          r.name.toLowerCase().includes(query) ||
          r.sector?.toLowerCase().includes(query) ||
          r.industry?.toLowerCase().includes(query)
      );
    }

    // Apply custom filters
    for (const filter of filters.filter((f) => f.enabled)) {
      filtered = filtered.filter((r) => {
        const value = r[filter.field];
        if (value === undefined || value === null) return false;

        switch (filter.operator) {
          case 'gt':
            return typeof value === 'number' && value > (filter.value as number);
          case 'lt':
            return typeof value === 'number' && value < (filter.value as number);
          case 'gte':
            return typeof value === 'number' && value >= (filter.value as number);
          case 'lte':
            return typeof value === 'number' && value <= (filter.value as number);
          case 'eq':
            return value === filter.value;
          case 'between':
            const [min, max] = filter.value as [number, number];
            return typeof value === 'number' && value >= min && value <= max;
          case 'contains':
            return typeof value === 'string' && value.toLowerCase().includes((filter.value as string).toLowerCase());
          default:
            return true;
        }
      });
    }

    // Sort
    filtered.sort((a, b) => {
      const aVal = a[sortField];
      const bVal = b[sortField];
      if (aVal === undefined || aVal === null) return 1;
      if (bVal === undefined || bVal === null) return -1;
      const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
      return sortDirection === 'asc' ? comparison : -comparison;
    });

    return filtered;
  }, [results, searchQuery, filters, sortField, sortDirection]);

  // Handle sort
  const handleSort = useCallback((field: SortField) => {
    if (field === sortField) {
      setSortDirection((d) => (d === 'asc' ? 'desc' : 'asc'));
    } else {
      setSortField(field);
      setSortDirection('desc');
    }
  }, [sortField]);

  // Add new filter
  const addFilter = useCallback(() => {
    const newFilter: ScreenerFilter = {
      id: `filter-${Date.now()}`,
      field: 'price',
      operator: 'gt',
      value: 0,
      enabled: true,
    };
    const newFilters = [...filters, newFilter];
    setFilters(newFilters);
    onFilterChange?.(newFilters);
  }, [filters, onFilterChange]);

  // Update filter
  const updateFilter = useCallback((id: string, updates: Partial<ScreenerFilter>) => {
    const newFilters = filters.map((f) => (f.id === id ? { ...f, ...updates } : f));
    setFilters(newFilters);
    onFilterChange?.(newFilters);
  }, [filters, onFilterChange]);

  // Remove filter
  const removeFilter = useCallback((id: string) => {
    const newFilters = filters.filter((f) => f.id !== id);
    setFilters(newFilters);
    onFilterChange?.(newFilters);
  }, [filters, onFilterChange]);

  // Load preset
  const loadPreset = useCallback((preset: typeof FILTER_PRESETS[0]) => {
    const newFilters = preset.filters.map((f, i) => ({
      ...f,
      id: `preset-${Date.now()}-${i}`,
    }));
    setFilters(newFilters);
    onFilterChange?.(newFilters);
  }, [onFilterChange]);

  // Save screener
  const handleSaveScreener = useCallback(() => {
    if (newScreenerName.trim() && filters.length > 0) {
      onSaveScreener?.(newScreenerName.trim(), filters);
      setNewScreenerName('');
    }
  }, [newScreenerName, filters, onSaveScreener]);

  // Format helpers
  const formatNumber = (num: number | undefined, decimals = 2): string => {
    if (num === undefined || num === null) return '-';
    if (Math.abs(num) >= 1e9) return `${(num / 1e9).toFixed(1)}B`;
    if (Math.abs(num) >= 1e6) return `${(num / 1e6).toFixed(1)}M`;
    if (Math.abs(num) >= 1e3) return `${(num / 1e3).toFixed(1)}K`;
    return num.toFixed(decimals);
  };

  const formatPrice = (price: number): string => {
    if (price >= 1000) return price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    if (price >= 1) return price.toFixed(2);
    return price.toFixed(4);
  };

  // Render sort indicator
  const renderSortIndicator = (field: SortField) => {
    if (sortField !== field) return null;
    return sortDirection === 'asc' ? (
      <ChevronUpIcon className="w-3 h-3 inline ml-1" />
    ) : (
      <ChevronDownIcon className="w-3 h-3 inline ml-1" />
    );
  };

  return (
    <div className={`bg-gray-800/50 rounded-lg ${compact ? 'p-2' : 'p-4'} flex flex-col h-full`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <FunnelIcon className="w-5 h-5 text-amber-400" />
          <h3 className={`font-semibold text-white ${compact ? 'text-xs' : 'text-sm'}`}>
            Stock Screener
          </h3>
          <span className="text-xs text-gray-400">
            {filteredResults.length} / {results.length} results
          </span>
        </div>

        <div className="flex items-center gap-1">
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`p-1.5 rounded transition-colors ${showFilters ? 'bg-amber-500/20 text-amber-400' : 'text-gray-400 hover:text-white hover:bg-gray-700'}`}
            title="Filters"
          >
            <AdjustmentsHorizontalIcon className="w-4 h-4" />
          </button>
          <button
            onClick={() => setShowSavedScreeners(!showSavedScreeners)}
            className={`p-1.5 rounded transition-colors ${showSavedScreeners ? 'bg-blue-500/20 text-blue-400' : 'text-gray-400 hover:text-white hover:bg-gray-700'}`}
            title="Saved Screeners"
          >
            <BookmarkIcon className="w-4 h-4" />
          </button>
          {onExport && (
            <button
              onClick={() => onExport('csv')}
              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
              title="Export"
            >
              <ArrowDownTrayIcon className="w-4 h-4" />
            </button>
          )}
          {onRefresh && (
            <button
              onClick={onRefresh}
              disabled={isLoading}
              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
              title="Refresh"
            >
              <ArrowPathIcon className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
            </button>
          )}
        </div>
      </div>

      {/* Search Bar */}
      <div className="relative mb-3">
        <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => {
            setSearchQuery(e.target.value);
            onSearch?.(e.target.value);
          }}
          placeholder="Search by symbol, name, sector..."
          className="w-full bg-gray-900/50 border border-gray-700 rounded-lg pl-9 pr-4 py-2 text-sm text-white placeholder-gray-500 focus:border-amber-500 focus:outline-none"
        />
      </div>

      {/* Filter Presets */}
      <div className="flex flex-wrap gap-1 mb-3">
        {FILTER_PRESETS.map((preset) => (
          <button
            key={preset.name}
            onClick={() => loadPreset(preset)}
            className="px-2 py-1 text-xs bg-gray-700 text-gray-300 hover:bg-gray-600 rounded transition-colors"
          >
            {preset.name}
          </button>
        ))}
      </div>

      {/* Saved Screeners Panel */}
      {showSavedScreeners && (
        <div className="mb-3 p-3 bg-gray-900/50 rounded-lg">
          <div className="text-xs text-gray-400 mb-2">Saved Screeners</div>
          {savedScreeners.length > 0 ? (
            <div className="space-y-1">
              {savedScreeners.map((screener) => (
                <div
                  key={screener.id}
                  className="flex items-center justify-between p-2 bg-gray-800 rounded hover:bg-gray-700 transition-colors"
                >
                  <button
                    onClick={() => onLoadScreener?.(screener)}
                    className="text-sm text-white hover:text-blue-400"
                  >
                    {screener.name}
                  </button>
                  <button
                    onClick={() => onDeleteScreener?.(screener.id)}
                    className="p-1 text-gray-400 hover:text-red-400"
                  >
                    <TrashIcon className="w-3 h-3" />
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-xs text-gray-500">No saved screeners</div>
          )}

          {/* Save Current */}
          {filters.length > 0 && onSaveScreener && (
            <div className="flex gap-2 mt-2">
              <input
                type="text"
                value={newScreenerName}
                onChange={(e) => setNewScreenerName(e.target.value)}
                placeholder="Screener name..."
                className="flex-1 bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-white"
              />
              <button
                onClick={handleSaveScreener}
                disabled={!newScreenerName.trim()}
                className="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 disabled:opacity-50"
              >
                Save
              </button>
            </div>
          )}
        </div>
      )}

      {/* Filters Panel */}
      {showFilters && (
        <div className="mb-3 p-3 bg-gray-900/50 rounded-lg">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs text-gray-400">Active Filters</span>
            <button
              onClick={addFilter}
              className="flex items-center gap-1 px-2 py-1 text-xs bg-gray-700 text-white rounded hover:bg-gray-600"
            >
              <PlusIcon className="w-3 h-3" />
              Add Filter
            </button>
          </div>

          {filters.length > 0 ? (
            <div className="space-y-2">
              {filters.map((filter) => (
                <div
                  key={filter.id}
                  className="flex items-center gap-2 p-2 bg-gray-800 rounded"
                >
                  <input
                    type="checkbox"
                    checked={filter.enabled}
                    onChange={(e) => updateFilter(filter.id, { enabled: e.target.checked })}
                    className="rounded bg-gray-700 border-gray-600"
                  />
                  <select
                    value={filter.field as string}
                    onChange={(e) => updateFilter(filter.id, { field: e.target.value as keyof ScreenerResult })}
                    className="bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-white"
                  >
                    {FILTERABLE_FIELDS.map((f) => (
                      <option key={f.field as string} value={f.field as string}>
                        {f.label}
                      </option>
                    ))}
                  </select>
                  <select
                    value={filter.operator}
                    onChange={(e) => updateFilter(filter.id, { operator: e.target.value as ScreenerFilter['operator'] })}
                    className="bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-white"
                  >
                    <option value="gt">&gt;</option>
                    <option value="gte">&gt;=</option>
                    <option value="lt">&lt;</option>
                    <option value="lte">&lt;=</option>
                    <option value="eq">=</option>
                    <option value="contains">contains</option>
                  </select>
                  <input
                    type={FILTERABLE_FIELDS.find((f) => f.field === filter.field)?.type === 'number' ? 'number' : 'text'}
                    value={filter.value as string | number}
                    onChange={(e) =>
                      updateFilter(filter.id, {
                        value: e.target.type === 'number' ? parseFloat(e.target.value) || 0 : e.target.value,
                      })
                    }
                    className="w-24 bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-white"
                  />
                  <button
                    onClick={() => removeFilter(filter.id)}
                    className="p-1 text-gray-400 hover:text-red-400"
                  >
                    <TrashIcon className="w-3 h-3" />
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-xs text-gray-500 text-center py-2">No filters applied</div>
          )}
        </div>
      )}

      {/* Results Table */}
      <div className="flex-1 overflow-auto">
        <table className="w-full text-xs">
          <thead className="sticky top-0 bg-gray-800">
            <tr className="border-b border-gray-700">
              <th className="text-left py-2 px-2 text-gray-400 font-medium">
                <button onClick={() => handleSort('symbol')} className="hover:text-white">
                  Symbol{renderSortIndicator('symbol')}
                </button>
              </th>
              <th className="text-right py-2 px-2 text-gray-400 font-medium">
                <button onClick={() => handleSort('price')} className="hover:text-white">
                  Price{renderSortIndicator('price')}
                </button>
              </th>
              <th className="text-right py-2 px-2 text-gray-400 font-medium">
                <button onClick={() => handleSort('changePercent')} className="hover:text-white">
                  Change{renderSortIndicator('changePercent')}
                </button>
              </th>
              <th className="text-right py-2 px-2 text-gray-400 font-medium hidden sm:table-cell">
                <button onClick={() => handleSort('volume')} className="hover:text-white">
                  Volume{renderSortIndicator('volume')}
                </button>
              </th>
              <th className="text-right py-2 px-2 text-gray-400 font-medium hidden md:table-cell">
                <button onClick={() => handleSort('marketCap')} className="hover:text-white">
                  Mkt Cap{renderSortIndicator('marketCap')}
                </button>
              </th>
              <th className="text-right py-2 px-2 text-gray-400 font-medium hidden lg:table-cell">
                <button onClick={() => handleSort('rsi')} className="hover:text-white">
                  RSI{renderSortIndicator('rsi')}
                </button>
              </th>
              <th className="text-right py-2 px-2 text-gray-400 font-medium hidden xl:table-cell">
                <button onClick={() => handleSort('volumeRatio')} className="hover:text-white">
                  Vol Ratio{renderSortIndicator('volumeRatio')}
                </button>
              </th>
              <th className="text-center py-2 px-2 text-gray-400 font-medium hidden xl:table-cell">
                <button onClick={() => handleSort('mlSignal')} className="hover:text-white">
                  ML Signal{renderSortIndicator('mlSignal')}
                </button>
              </th>
              <th className="text-center py-2 px-2 text-gray-400 font-medium w-20">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredResults.map((result) => (
              <tr
                key={result.symbol}
                className="border-b border-gray-700/50 hover:bg-gray-700/30 transition-colors cursor-pointer"
                onClick={() => onSymbolClick?.(result.symbol)}
              >
                <td className="py-2 px-2">
                  <div className="flex items-center gap-2">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        onToggleFavorite?.(result.symbol);
                      }}
                      className="text-gray-400 hover:text-yellow-400"
                    >
                      {result.isFavorite ? (
                        <StarIcon className="w-4 h-4 text-yellow-400" />
                      ) : (
                        <StarOutlineIcon className="w-4 h-4" />
                      )}
                    </button>
                    <div>
                      <div className="text-white font-medium">{result.symbol}</div>
                      <div className="text-gray-500 text-[10px] truncate max-w-[100px]">{result.name}</div>
                    </div>
                  </div>
                </td>
                <td className="py-2 px-2 text-right text-white font-mono">{formatPrice(result.price)}</td>
                <td className={`py-2 px-2 text-right font-mono ${result.changePercent >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                  {result.changePercent >= 0 ? '+' : ''}{result.changePercent.toFixed(2)}%
                </td>
                <td className="py-2 px-2 text-right text-gray-300 font-mono hidden sm:table-cell">
                  {formatNumber(result.volume, 0)}
                </td>
                <td className="py-2 px-2 text-right text-gray-300 font-mono hidden md:table-cell">
                  {formatNumber(result.marketCap, 1)}
                </td>
                <td className="py-2 px-2 text-right hidden lg:table-cell">
                  {result.rsi !== undefined && (
                    <span
                      className={`font-mono ${
                        result.rsi > 70 ? 'text-red-400' : result.rsi < 30 ? 'text-green-400' : 'text-gray-300'
                      }`}
                    >
                      {result.rsi.toFixed(0)}
                    </span>
                  )}
                </td>
                <td className="py-2 px-2 text-right hidden xl:table-cell">
                  {result.volumeRatio !== undefined && (
                    <span
                      className={`font-mono ${
                        result.volumeRatio > 2 ? 'text-amber-400' : result.volumeRatio > 1 ? 'text-green-400' : 'text-gray-300'
                      }`}
                    >
                      {result.volumeRatio.toFixed(2)}x
                    </span>
                  )}
                </td>
                <td className="py-2 px-2 text-center hidden xl:table-cell">
                  {result.mlSignal && (
                    <span
                      className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${
                        result.mlSignal === 'buy'
                          ? 'bg-green-500/20 text-green-400'
                          : result.mlSignal === 'sell'
                          ? 'bg-red-500/20 text-red-400'
                          : 'bg-gray-500/20 text-gray-400'
                      }`}
                    >
                      {result.mlSignal.toUpperCase()}
                      {result.mlConfidence !== undefined && (
                        <span className="text-[8px] opacity-75">
                          {(result.mlConfidence * 100).toFixed(0)}%
                        </span>
                      )}
                    </span>
                  )}
                </td>
                <td className="py-2 px-2">
                  <div className="flex items-center justify-center gap-1">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        onSymbolClick?.(result.symbol);
                      }}
                      className="p-1 text-gray-400 hover:text-blue-400 hover:bg-blue-500/20 rounded"
                      title="View Chart"
                    >
                      <ChartBarIcon className="w-4 h-4" />
                    </button>
                    {onAddToWatchlist && (
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          onAddToWatchlist(result.symbol);
                        }}
                        className="p-1 text-gray-400 hover:text-green-400 hover:bg-green-500/20 rounded"
                        title="Add to Watchlist"
                      >
                        <PlusIcon className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Empty State */}
        {!isLoading && filteredResults.length === 0 && (
          <div className="flex flex-col items-center justify-center py-12 text-gray-500">
            <FunnelIcon className="w-12 h-12 mb-2 opacity-50" />
            <p className="text-sm">No results match your criteria</p>
            <button
              onClick={() => {
                setSearchQuery('');
                setFilters([]);
              }}
              className="mt-2 text-xs text-blue-400 hover:underline"
            >
              Clear all filters
            </button>
          </div>
        )}

        {/* Loading State */}
        {isLoading && (
          <div className="flex items-center justify-center py-12">
            <ArrowPathIcon className="w-8 h-8 text-amber-400 animate-spin" />
          </div>
        )}
      </div>
    </div>
  );
};

export default TradingScreener;
