import { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { getApiUrl } from '@/config/api';

export default function Watchlist() {
  const [watchlist, setWatchlist] = useState([]);
  const [prices, setPrices] = useState({});

  useEffect(() => {
    const saved = localStorage.getItem('watchlist');
    if (saved) {
      try {
        setWatchlist(JSON.parse(saved));
      } catch (e) {
        console.error('Error loading watchlist:', e);
      }
    }

    // WebSocket for real-time price updates
    // Note: This assumes a WebSocket endpoint exists for watchlist prices
    // For now, we'll use a polling approach or you can implement WebSocket later
    const fetchPrices = async () => {
      if (watchlist.length === 0) return;
      
      try {
        // Fetch prices for all watchlist symbols
        const symbols = watchlist.join(',');
        const response = await fetch(`${getApiUrl('/api/prices')}?symbols=${symbols}`);
        const data = await response.json();
        
        if (data.success && data.data) {
          const priceMap = {};
          data.data.forEach(item => {
            if (item.symbol && item.price) {
              priceMap[item.symbol] = {
                price: parseFloat(item.price),
                change: parseFloat(item.change || 0),
                changePercent: parseFloat(item.changePercent || 0)
              };
            }
          });
          setPrices(priceMap);
        }
      } catch (error) {
        console.error('Error fetching prices:', error);
      }
    };

    // Initial fetch
    fetchPrices();
    
    // Poll every 5 seconds for price updates
    const interval = setInterval(fetchPrices, 5000);
    
    return () => clearInterval(interval);
  }, [watchlist]);

  // Listen for watchlist updates from localStorage changes
  useEffect(() => {
    const handleStorageChange = (e) => {
      if (e.key === 'watchlist') {
        try {
          setWatchlist(JSON.parse(e.newValue || '[]'));
        } catch (err) {
          console.error('Error parsing watchlist from storage:', err);
        }
      }
    };

    window.addEventListener('storage', handleStorageChange);
    
    // Also listen for custom events (for same-tab updates)
    const handleCustomStorage = () => {
      const saved = localStorage.getItem('watchlist');
      if (saved) {
        try {
          setWatchlist(JSON.parse(saved));
        } catch (e) {
          console.error('Error loading watchlist:', e);
        }
      }
    };

    window.addEventListener('watchlistUpdated', handleCustomStorage);
    
    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('watchlistUpdated', handleCustomStorage);
    };
  }, []);

  const removeFromWatchlist = (symbol) => {
    const updated = watchlist.filter(s => s !== symbol);
    setWatchlist(updated);
    localStorage.setItem('watchlist', JSON.stringify(updated));
    
    // Dispatch custom event for same-tab updates
    window.dispatchEvent(new Event('watchlistUpdated'));
    
    // Remove price data for removed symbol
    setPrices(prev => {
      const newPrices = { ...prev };
      delete newPrices[symbol];
      return newPrices;
    });
  };

  return (
    <div className="bg-slate-900 rounded-lg border border-slate-800 p-4">
      <h3 className="font-semibold text-slate-100 mb-4">Watchlist</h3>
      <div className="space-y-2">
        {watchlist.length === 0 ? (
          <div className="text-center text-slate-400 py-8">
            No symbols in watchlist
          </div>
        ) : (
          watchlist.map(symbol => (
            <div
              key={symbol}
              className="flex items-center justify-between p-3 bg-slate-800/50 rounded hover:bg-slate-800 transition-colors"
            >
              <div className="flex-1">
                <div className="font-semibold text-slate-100">{symbol}</div>
                {prices[symbol] && (
                  <div className="flex items-center gap-2 mt-1">
                    <span className="text-sm text-slate-300">
                      ${prices[symbol].price.toFixed(2)}
                    </span>
                    <span
                      className={`text-xs ${
                        prices[symbol].changePercent >= 0
                          ? 'text-green-400'
                          : 'text-red-400'
                      }`}
                    >
                      {prices[symbol].changePercent >= 0 ? '+' : ''}
                      {prices[symbol].changePercent.toFixed(2)}%
                    </span>
                  </div>
                )}
              </div>
              <button
                onClick={() => removeFromWatchlist(symbol)}
                className="text-slate-400 hover:text-red-400 transition-colors"
                title="Remove from watchlist"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

