/**
 * AddSymbolModal Component
 * Modal for searching and adding symbols to watchlist
 */

import { useState, useEffect } from 'react';
import { tradingService } from '../../../services/trading.service';
import type { TradingSymbol } from '../../../types/trading.types';

interface AddSymbolModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddSymbol: (symbol: string) => void;
}

export default function AddSymbolModal({
  isOpen,
  onClose,
  onAddSymbol,
}: AddSymbolModalProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<TradingSymbol[]>([]);
  const [popularSymbols, setPopularSymbols] = useState<TradingSymbol[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load popular symbols on mount
  useEffect(() => {
    if (isOpen) {
      loadPopularSymbols();
    }
  }, [isOpen]);

  // Search symbols when query changes
  useEffect(() => {
    const performSearch = async () => {
      if (searchQuery.length >= 2) {
        try {
          setLoading(true);
          setError(null);
          const results = await tradingService.searchSymbols(searchQuery);
          setSearchResults(results);
        } catch (err) {
          setError('Failed to search symbols');
          console.error('Search error:', err);
        } finally {
          setLoading(false);
        }
      } else {
        setSearchResults([]);
      }
    };

    performSearch();
  }, [searchQuery]);

  const loadPopularSymbols = async () => {
    try {
      setLoading(true);
      const symbols = await tradingService.getPopularSymbols();
      setPopularSymbols(symbols);
    } catch (err) {
      console.error('Failed to load popular symbols:', err);
      // Fallback to default popular symbols
      setPopularSymbols([
        { symbol: 'BTCUSDT', baseAsset: 'BTC', quoteAsset: 'USDT', status: 'TRADING' },
        { symbol: 'ETHUSDT', baseAsset: 'ETH', quoteAsset: 'USDT', status: 'TRADING' },
        { symbol: 'BNBUSDT', baseAsset: 'BNB', quoteAsset: 'USDT', status: 'TRADING' },
        { symbol: 'SOLUSDT', baseAsset: 'SOL', quoteAsset: 'USDT', status: 'TRADING' },
        { symbol: 'ADAUSDT', baseAsset: 'ADA', quoteAsset: 'USDT', status: 'TRADING' },
        { symbol: 'XRPUSDT', baseAsset: 'XRP', quoteAsset: 'USDT', status: 'TRADING' },
      ]);
    } finally {
      setLoading(false);
    }
  };


  const handleAddSymbol = (symbol: string) => {
    onAddSymbol(symbol);
    setSearchQuery('');
    setSearchResults([]);
    onClose();
  };

  const handleClose = () => {
    setSearchQuery('');
    setSearchResults([]);
    setError(null);
    onClose();
  };

  if (!isOpen) return null;

  const displaySymbols = searchQuery.length >= 2 ? searchResults : popularSymbols;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50">
      <div className="bg-gray-800 rounded-lg shadow-xl border border-gray-700 w-full max-w-md mx-4">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-700">
          <h3 className="text-lg font-semibold text-white">Add Symbol</h3>
          <button
            onClick={handleClose}
            className="text-gray-400 hover:text-white transition-colors"
            aria-label="Close modal"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        {/* Search Input */}
        <div className="p-4 border-b border-gray-700">
          <div className="relative">
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value.toUpperCase())}
              placeholder="Search symbols (e.g., BTC, ETH)..."
              className="w-full px-4 py-2 pl-10 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500"
              autoFocus
            />
            <svg
              className="absolute left-3 top-2.5 w-5 h-5 text-gray-500"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
          </div>
        </div>

        {/* Results */}
        <div className="max-h-96 overflow-y-auto">
          {loading ? (
            <div className="flex items-center justify-center p-8">
              <svg
                className="animate-spin h-8 w-8 text-blue-500"
                xmlns="http://www.w3.org/2000/svg"
                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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
            </div>
          ) : error ? (
            <div className="p-8 text-center text-red-400">{error}</div>
          ) : displaySymbols.length === 0 ? (
            <div className="p-8 text-center text-gray-400">
              {searchQuery.length >= 2 ? 'No symbols found' : 'Loading popular symbols...'}
            </div>
          ) : (
            <div className="p-2">
              {!searchQuery && (
                <div className="px-3 py-2 text-xs font-semibold text-gray-400 uppercase">
                  Popular Symbols
                </div>
              )}
              {displaySymbols.map((symbol) => (
                <button
                  key={symbol.symbol}
                  onClick={() => handleAddSymbol(symbol.symbol)}
                  className="w-full flex items-center justify-between px-3 py-3 rounded-lg hover:bg-gray-700 transition-colors text-left"
                >
                  <div>
                    <div className="font-medium text-white">
                      {symbol.baseAsset}/{symbol.quoteAsset}
                    </div>
                    <div className="text-sm text-gray-400">{symbol.symbol}</div>
                  </div>
                  <svg
                    className="w-5 h-5 text-gray-400"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M12 4v16m8-8H4"
                    />
                  </svg>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-gray-700 flex justify-end gap-2">
          <button
            onClick={handleClose}
            className="px-4 py-2 text-gray-300 hover:text-white transition-colors"
          >
            Cancel
          </button>
        </div>
      </div>
    </div>
  );
}
