/**
 * WatchlistSidebar Component
 * Sidebar displaying watchlist symbols with real-time prices
 */

import { useEffect, useState } from 'react';
import { useTradingStore } from '../../../stores/tradingStore';
import WatchlistItem from './WatchlistItem';
import AddSymbolModal from './AddSymbolModal';

interface WatchlistSidebarProps {
  selectedSymbol: string;
  onSymbolSelect: (symbol: string) => void;
}

export default function WatchlistSidebar({
  selectedSymbol,
  onSymbolSelect,
}: WatchlistSidebarProps) {
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [searchFilter, setSearchFilter] = useState('');

  const {
    watchlist,
    watchlistData,
    loadingWatchlist,
    fetchWatchlist,
    addToWatchlist,
    removeFromWatchlist,
    refreshWatchlistData,
  } = useTradingStore();

  // Load watchlist on mount
  useEffect(() => {
    fetchWatchlist();
  }, [fetchWatchlist]);

  // Refresh watchlist data periodically (every 5 seconds)
  useEffect(() => {
    const interval = setInterval(() => {
      if (watchlist && watchlist.items.length > 0) {
        refreshWatchlistData();
      }
    }, 5000);

    return () => clearInterval(interval);
  }, [watchlist, refreshWatchlistData]);

  const handleAddSymbol = async (symbol: string) => {
    await addToWatchlist(symbol);
  };

  const handleRemoveSymbol = async (symbol: string) => {
    await removeFromWatchlist(symbol);
  };

  // Filter watchlist data based on search
  const filteredData = watchlistData.filter((item) =>
    item.symbol.toLowerCase().includes(searchFilter.toLowerCase())
  );

  return (
    <>
      <div className="h-full flex flex-col bg-gray-900 border-r border-gray-800">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-800">
          <div className="flex items-center gap-2">
            <svg
              className="w-5 h-5 text-blue-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
              />
            </svg>
            <h2 className="text-sm font-semibold text-white">Watchlist</h2>
          </div>
          <button
            onClick={() => setIsAddModalOpen(true)}
            className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-800 rounded transition-colors"
            aria-label="Add symbol"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 4v16m8-8H4"
              />
            </svg>
          </button>
        </div>

        {/* Search */}
        <div className="p-3 border-b border-gray-800">
          <div className="relative">
            <input
              type="text"
              value={searchFilter}
              onChange={(e) => setSearchFilter(e.target.value)}
              placeholder="Search..."
              className="w-full px-3 py-2 pl-9 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
            />
            <svg
              className="absolute left-3 top-2.5 w-4 h-4 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>

        {/* Watchlist Items */}
        <div className="flex-1 overflow-y-auto">
          {loadingWatchlist ? (
            <div className="flex flex-col items-center justify-center py-12">
              <svg
                className="animate-spin h-8 w-8 text-blue-500 mb-3"
                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>
              <p className="text-sm text-gray-400">Loading watchlist...</p>
            </div>
          ) : !watchlist || watchlistData.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 px-4">
              <svg
                className="w-12 h-12 text-gray-600 mb-3"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
                />
              </svg>
              <p className="text-sm text-gray-400 text-center mb-3">
                Your watchlist is empty
              </p>
              <button
                onClick={() => setIsAddModalOpen(true)}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-lg transition-colors"
              >
                Add Symbol
              </button>
            </div>
          ) : filteredData.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 px-4">
              <p className="text-sm text-gray-400 text-center">
                No symbols match your search
              </p>
            </div>
          ) : (
            <div className="divide-y divide-gray-800">
              {filteredData.map((symbolData) => (
                <WatchlistItem
                  key={symbolData.symbol}
                  data={symbolData}
                  isSelected={symbolData.symbol === selectedSymbol}
                  onSelect={onSymbolSelect}
                  onRemove={handleRemoveSymbol}
                />
              ))}
            </div>
          )}
        </div>

        {/* Footer Info */}
        {watchlist && watchlistData.length > 0 && (
          <div className="p-3 border-t border-gray-800">
            <div className="flex items-center justify-between text-xs text-gray-500">
              <span>{watchlistData.length} symbols</span>
              <span className="flex items-center gap-1">
                <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
                Live
              </span>
            </div>
          </div>
        )}
      </div>

      {/* Add Symbol Modal */}
      <AddSymbolModal
        isOpen={isAddModalOpen}
        onClose={() => setIsAddModalOpen(false)}
        onAddSymbol={handleAddSymbol}
      />
    </>
  );
}
