/**
 * ChartToolbar Component
 * Toolbar for chart controls (symbol, timeframe, indicators)
 */

import { useState, useEffect } from 'react';
import type { Interval, ChartToolbarProps } from '../../../types/trading.types';

// ============================================================================
// Constants
// ============================================================================

const INTERVALS: { value: Interval; label: string }[] = [
  { value: '1m', label: '1m' },
  { value: '5m', label: '5m' },
  { value: '15m', label: '15m' },
  { value: '30m', label: '30m' },
  { value: '1h', label: '1H' },
  { value: '4h', label: '4H' },
  { value: '1d', label: '1D' },
  { value: '1w', label: '1W' },
];

const DEFAULT_SYMBOLS = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'XRPUSDT'];

const INDICATORS = [
  { id: 'sma', label: 'SMA' },
  { id: 'ema', label: 'EMA' },
  { id: 'rsi', label: 'RSI' },
  { id: 'macd', label: 'MACD' },
  { id: 'bollinger', label: 'BB' },
];

// ============================================================================
// Component
// ============================================================================

export const ChartToolbar: React.FC<ChartToolbarProps> = ({
  symbol,
  interval,
  symbols = DEFAULT_SYMBOLS,
  onSymbolChange,
  onIntervalChange,
  onIndicatorToggle,
  theme = 'dark',
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<string[]>([]);
  const [showDropdown, setShowDropdown] = useState(false);
  const [showIndicators, setShowIndicators] = useState(false);
  const [activeIndicators, setActiveIndicators] = useState<Set<string>>(new Set());

  // Theme classes
  const bgColor = theme === 'dark' ? 'bg-gray-900' : 'bg-gray-50';
  const borderColor = theme === 'dark' ? 'border-gray-700' : 'border-gray-200';
  const textColor = theme === 'dark' ? 'text-white' : 'text-gray-900';
  const textMutedColor = theme === 'dark' ? 'text-gray-400' : 'text-gray-600';
  const hoverBgColor = theme === 'dark' ? 'hover:bg-gray-800' : 'hover:bg-gray-100';
  const inputBgColor = theme === 'dark' ? 'bg-gray-800' : 'bg-white';
  const dropdownBgColor = theme === 'dark' ? 'bg-gray-800' : 'bg-white';

  // Search symbols
  useEffect(() => {
    if (searchQuery.length > 0) {
      const filtered = symbols.filter((s) =>
        s.toLowerCase().includes(searchQuery.toLowerCase())
      );
      setSearchResults(filtered);
    } else {
      setSearchResults(symbols);
    }
  }, [searchQuery, symbols]);

  // Handle symbol selection
  const handleSymbolSelect = (selectedSymbol: string) => {
    onSymbolChange(selectedSymbol);
    setShowDropdown(false);
    setSearchQuery('');
  };

  // Handle indicator toggle
  const handleIndicatorToggle = (indicatorId: string) => {
    const newActiveIndicators = new Set(activeIndicators);
    if (newActiveIndicators.has(indicatorId)) {
      newActiveIndicators.delete(indicatorId);
    } else {
      newActiveIndicators.add(indicatorId);
    }
    setActiveIndicators(newActiveIndicators);
    onIndicatorToggle?.(indicatorId);
  };

  return (
    <div
      className={`flex items-center justify-between px-4 py-3 ${bgColor} border-b ${borderColor}`}
    >
      {/* Left side - Symbol and Timeframe */}
      <div className="flex items-center gap-4">
        {/* Symbol Selector */}
        <div className="relative">
          <button
            onClick={() => setShowDropdown(!showDropdown)}
            className={`flex items-center gap-2 px-4 py-2 ${inputBgColor} ${textColor} rounded-lg ${hoverBgColor} transition-colors border ${borderColor}`}
          >
            <span className="font-semibold">{symbol}</span>
            <svg
              className={`w-4 h-4 transition-transform ${showDropdown ? 'rotate-180' : ''}`}
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </button>

          {/* Dropdown */}
          {showDropdown && (
            <div
              className={`absolute top-full left-0 mt-2 w-64 ${dropdownBgColor} rounded-lg shadow-lg border ${borderColor} z-50`}
            >
              {/* Search input */}
              <div className="p-2 border-b ${borderColor}">
                <input
                  type="text"
                  placeholder="Search symbol..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className={`w-full px-3 py-2 ${inputBgColor} ${textColor} rounded border ${borderColor} focus:outline-none focus:ring-2 focus:ring-blue-500`}
                  autoFocus
                />
              </div>

              {/* Results */}
              <div className="max-h-64 overflow-y-auto">
                {searchResults.length > 0 ? (
                  searchResults.map((s) => (
                    <button
                      key={s}
                      onClick={() => handleSymbolSelect(s)}
                      className={`w-full text-left px-4 py-2 ${textColor} ${hoverBgColor} transition-colors ${
                        s === symbol ? 'bg-blue-600 text-white' : ''
                      }`}
                    >
                      {s}
                    </button>
                  ))
                ) : (
                  <div className={`px-4 py-3 text-center ${textMutedColor}`}>
                    No symbols found
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Timeframe Selector */}
        <div className={`flex gap-1 ${inputBgColor} rounded-lg p-1 border ${borderColor}`}>
          {INTERVALS.map((int) => (
            <button
              key={int.value}
              onClick={() => onIntervalChange(int.value)}
              className={`px-3 py-1 text-sm font-medium rounded transition-colors ${
                interval === int.value
                  ? 'bg-blue-600 text-white'
                  : `${textMutedColor} ${hoverBgColor}`
              }`}
            >
              {int.label}
            </button>
          ))}
        </div>
      </div>

      {/* Right side - Indicators and Actions */}
      <div className="flex items-center gap-2">
        {/* Indicators Button */}
        <div className="relative">
          <button
            onClick={() => setShowIndicators(!showIndicators)}
            className={`flex items-center gap-2 px-4 py-2 ${inputBgColor} ${textColor} rounded-lg ${hoverBgColor} transition-colors border ${borderColor}`}
          >
            <svg
              className="w-4 h-4"
              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>
            <span className="text-sm">Indicators</span>
            {activeIndicators.size > 0 && (
              <span className="flex items-center justify-center w-5 h-5 text-xs bg-blue-600 text-white rounded-full">
                {activeIndicators.size}
              </span>
            )}
          </button>

          {/* Indicators Dropdown */}
          {showIndicators && (
            <div
              className={`absolute top-full right-0 mt-2 w-48 ${dropdownBgColor} rounded-lg shadow-lg border ${borderColor} z-50`}
            >
              <div className="p-2">
                {INDICATORS.map((indicator) => (
                  <button
                    key={indicator.id}
                    onClick={() => handleIndicatorToggle(indicator.id)}
                    className={`w-full flex items-center justify-between px-3 py-2 ${textColor} ${hoverBgColor} rounded transition-colors`}
                  >
                    <span className="text-sm">{indicator.label}</span>
                    {activeIndicators.has(indicator.id) && (
                      <svg
                        className="w-4 h-4 text-green-500"
                        fill="currentColor"
                        viewBox="0 0 20 20"
                      >
                        <path
                          fillRule="evenodd"
                          d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                          clipRule="evenodd"
                        />
                      </svg>
                    )}
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Fullscreen Button */}
        <button
          className={`p-2 ${inputBgColor} ${textColor} rounded-lg ${hoverBgColor} transition-colors border ${borderColor}`}
          title="Fullscreen"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"
            />
          </svg>
        </button>
      </div>

      {/* Close dropdowns when clicking outside */}
      {(showDropdown || showIndicators) && (
        <div
          className="fixed inset-0 z-40"
          onClick={() => {
            setShowDropdown(false);
            setShowIndicators(false);
          }}
        />
      )}
    </div>
  );
};

export default ChartToolbar;
