/**
 * WatchlistItem Component
 * Displays a single symbol in the watchlist with price data
 */

import { useState } from 'react';
import type { WatchlistSymbolData } from '../../../types/trading.types';

interface WatchlistItemProps {
  data: WatchlistSymbolData;
  isSelected?: boolean;
  onSelect: (symbol: string) => void;
  onRemove: (symbol: string) => void;
}

export default function WatchlistItem({
  data,
  isSelected = false,
  onSelect,
  onRemove,
}: WatchlistItemProps) {
  const [isHovered, setIsHovered] = useState(false);

  const isPositive = data.priceChangePercent >= 0;
  const textColorClass = isPositive ? 'text-green-400' : 'text-red-400';
  const bgColorClass = isPositive ? 'bg-green-900/20' : 'bg-red-900/20';

  // Format symbol for display (e.g., BTCUSDT -> BTC/USDT)
  const formatSymbol = (symbol: string): string => {
    // Common quote assets
    const quoteAssets = ['USDT', 'BUSD', 'USD', 'EUR', 'BTC', 'ETH'];
    for (const quote of quoteAssets) {
      if (symbol.endsWith(quote)) {
        const base = symbol.slice(0, -quote.length);
        return `${base}/${quote}`;
      }
    }
    return symbol;
  };

  // Format price with appropriate decimal places
  const formatPrice = (price: number): string => {
    if (price >= 1000) {
      return price.toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      });
    } else if (price >= 1) {
      return price.toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 4,
      });
    } else {
      return price.toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 8,
      });
    }
  };

  // Format change amount
  const formatChange = (change: number): string => {
    const sign = change >= 0 ? '+' : '';
    if (Math.abs(change) >= 1000) {
      return `${sign}$${(change / 1000).toFixed(2)}K`;
    }
    return `${sign}$${change.toFixed(2)}`;
  };

  const handleClick = () => {
    onSelect(data.symbol);
  };

  const handleRemove = (e: React.MouseEvent) => {
    e.stopPropagation();
    onRemove(data.symbol);
  };

  return (
    <div
      className={`
        relative px-3 py-2.5 cursor-pointer transition-all duration-150
        border-l-2 ${isSelected ? 'border-blue-500 bg-blue-900/20' : 'border-transparent hover:bg-gray-800/50'}
        ${isHovered ? '' : ''}
      `}
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* Symbol and Price */}
      <div className="flex justify-between items-start mb-1">
        <span className="text-sm font-medium text-white">
          {formatSymbol(data.symbol)}
        </span>
        {isHovered && (
          <button
            onClick={handleRemove}
            className="text-gray-400 hover:text-red-400 transition-colors p-0.5"
            aria-label="Remove from watchlist"
          >
            <svg
              className="w-4 h-4"
              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>

      {/* Price */}
      <div className="text-base font-mono text-white mb-1">
        ${formatPrice(data.lastPrice)}
      </div>

      {/* Changes */}
      <div className="flex items-center justify-between text-xs">
        <span className={`font-medium ${textColorClass}`}>
          {data.priceChangePercent >= 0 ? '+' : ''}
          {data.priceChangePercent.toFixed(2)}%
        </span>
        <span className={`text-xs ${textColorClass}`}>
          {formatChange(data.priceChange)}
        </span>
      </div>

      {/* Mini sparkline placeholder (optional) */}
      <div className="mt-1.5 h-6 flex items-end gap-0.5">
        {Array.from({ length: 12 }).map((_, i) => {
          const height = Math.random() * 100;
          return (
            <div
              key={i}
              className={`flex-1 rounded-t-sm ${bgColorClass}`}
              style={{ height: `${height}%`, minHeight: '2px' }}
            />
          );
        })}
      </div>
    </div>
  );
}
