import React from 'react';

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

import { EQBand } from '../../studio/types';
import { EQDot } from './eqComponents';
import { freqToPosition, gainToPosition, qToPosition } from './eqUtils';
import { useEQBandDrag } from './useDotDrag';

interface DraggableEQBandDotProps {
  getBandValue: () => EQBand;
  bandKey: 'band1' | 'band2' | 'band3' | 'band4' | 'band5' | 'band6';
  containerRef: React.RefObject<HTMLDivElement | null>;
  onDragStart: () => void;
  onDragEnd: () => void;
  onUpdate: (updates: Partial<EQBand>) => void;
  onDoubleClick: (e: React.MouseEvent) => void;
  onMouseEnter: () => void;
  onMouseLeave: () => void;
  isHovered: boolean;
  isDragging: boolean;
  isSelected?: boolean;
  exitQModeRef?: React.MutableRefObject<(() => void) | null>;
  isQModeRef?: React.MutableRefObject<boolean>;
}

export default function DraggableEQBandDot({
  getBandValue,
  bandKey,
  containerRef,
  onDragStart,
  onDragEnd,
  onUpdate,
  onDoubleClick,
  onMouseEnter,
  onMouseLeave,
  isHovered,
  isDragging,
  isSelected,
  exitQModeRef,
  isQModeRef,
}: DraggableEQBandDotProps) {
  // Watch band value at screen refresh rate for smooth animations
  const band = useRealtimeValue(getBandValue);

  const x = freqToPosition(band.frequency);

  // For filter types (highpass, lowpass, notch), Y-axis represents Q
  // For gain-based types (peaking, lowshelf, highshelf), Y-axis represents gain
  const isFilterType =
    band.type === 'highpass' ||
    band.type === 'lowpass' ||
    band.type === 'notch';
  const y = isFilterType ? qToPosition(band.q) : gainToPosition(band.gain);

  const {
    dragRef,
    exitQMode,
    isQModeRef: internalIsQModeRef,
  } = useEQBandDrag(band, containerRef, {
    onDragStart,
    onDragEnd,
    onUpdate,
  });

  // Expose exitQMode and isQModeRef to parent if refs are provided
  if (exitQModeRef) {
    exitQModeRef.current = exitQMode;
  }
  if (isQModeRef) {
    isQModeRef.current = internalIsQModeRef.current;
  }

  // For gain-based types, inactive when gain is 0
  // For filter types, never inactive (always show as active)
  const isInactive = isFilterType ? false : band.gain === 0;

  // Extract numeric label from band key (e.g., "band1" -> "1")
  const label = bandKey.replace('band', '');

  return (
    <EQDot
      x={x}
      y={y}
      ref={dragRef as React.Ref<HTMLDivElement>}
      isHovered={isHovered}
      isDragging={isDragging}
      isSelected={isSelected}
      isInactive={isInactive}
      label={label}
      onDoubleClick={onDoubleClick}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    />
  );
}
