import { useEffect, useState } from 'react';

import { useRealtimeValue } from '@/hooks/useRealtimeValue';

import { EQBand } from '../../studio/types';
import { FilterControls, ValueItem } from './eqComponents';
import { formatFrequency } from './eqHelpers';
import { positionToFreq, positionToGain } from './eqUtils';
import { EQKey } from './useEQStateManagement';

interface EQDisplayInfoProps {
  containerRef: React.RefObject<HTMLDivElement | null>;
  displayKey: EQKey | null;
  getBandValue: (key: EQKey) => EQBand;
}

export default function EQDisplayInfo({
  containerRef,
  displayKey,
  getBandValue,
}: EQDisplayInfoProps) {
  const [mousePosition, setMousePosition] = useState<{
    freq: number;
    gain: number;
  } | null>(null);

  // Watch the display band value at screen refresh rate for smooth updates
  const displayValue = useRealtimeValue(
    () => (displayKey !== null ? getBandValue(displayKey) : null),
    displayKey !== null
  );

  // Track mouse position over the container (local to this component)
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleMouseMove = (e: MouseEvent) => {
      const rect = container.getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width;
      const y = 1 - (e.clientY - rect.top) / rect.height;

      // Clamp to bounds
      const clampedX = Math.max(0, Math.min(1, x));
      const clampedY = Math.max(0, Math.min(1, y));

      const freq = positionToFreq(clampedX);
      const gain = positionToGain(clampedY);

      setMousePosition({
        freq: Math.round(freq),
        gain: Math.round(gain * 10) / 10,
      });
    };

    const handleMouseLeave = () => {
      setMousePosition(null);
    };

    container.addEventListener('mousemove', handleMouseMove);
    container.addEventListener('mouseleave', handleMouseLeave);

    return () => {
      container.removeEventListener('mousemove', handleMouseMove);
      container.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, [containerRef]);

  const showMousePosition = displayKey === null && mousePosition !== null;

  return (
    <FilterControls>
      <div className='flex w-full justify-center gap-2 text-[10px]'>
        {displayValue ? (
          <>
            <ValueItem>{formatFrequency(displayValue.frequency)}Hz</ValueItem>
            {/* Show gain for gain-based bands, skip for filter-type bands */}
            {displayValue.type === 'peaking' ||
            displayValue.type === 'lowshelf' ||
            displayValue.type === 'highshelf' ? (
              <>
                <ValueItem>
                  {displayValue.gain >= 0 ? '+' : ''}
                  {displayValue.gain.toFixed(1)}dB
                </ValueItem>
                <ValueItem>Q: {displayValue.q.toFixed(2)}</ValueItem>
              </>
            ) : (
              <>
                <ValueItem>
                  {displayValue.type === 'highpass'
                    ? 'High-Pass'
                    : displayValue.type === 'lowpass'
                      ? 'Low-Pass'
                      : displayValue.type === 'notch'
                        ? 'Notch'
                        : ''}
                </ValueItem>
                <ValueItem>Q: {displayValue.q.toFixed(2)}</ValueItem>
              </>
            )}
          </>
        ) : showMousePosition && mousePosition ? (
          <>
            <ValueItem>{formatFrequency(mousePosition.freq)}Hz</ValueItem>
            <ValueItem>
              {mousePosition.gain >= 0 ? '+' : ''}
              {mousePosition.gain.toFixed(1)}dB
            </ValueItem>
          </>
        ) : (
          <span style={{ opacity: 0.5 }}>—</span>
        )}
      </div>
    </FilterControls>
  );
}
