import { useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useSettings } from '@/contexts/SettingsContext';
import { useAudioAnalyzer } from '@/contexts/AudioAnalyzerContext';

// Get CSS variable value
function getCSSVar(name: string): string {
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}

export function MiniOscilloscope() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const animationRef = useRef<number>();
  const navigate = useNavigate();
  const location = useLocation();
  const { playSound } = useSettings();
  const { analyzerNode } = useAudioAnalyzer();

  // Draw waveform
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const draw = () => {
      const width = canvas.width;
      const height = canvas.height;

      // Get theme colors
      const primaryHsl = getCSSVar('--primary');
      const primaryColor = primaryHsl ? `hsl(${primaryHsl})` : 'hsl(120, 100%, 50%)';
      const primaryColorDim = primaryHsl ? `hsl(${primaryHsl} / 0.3)` : 'hsl(120, 100%, 50%, 0.3)';
      const primaryColorFaint = primaryHsl ? `hsl(${primaryHsl} / 0.1)` : 'hsl(120, 100%, 50%, 0.1)';
      const bgHsl = getCSSVar('--background');
      const bgColor = bgHsl ? `hsl(${bgHsl} / 0.8)` : 'rgba(0, 0, 0, 0.6)';

      // Clear with transparent background
      ctx.clearRect(0, 0, width, height);

      // Draw background with theme color
      ctx.fillStyle = bgColor;
      ctx.fillRect(0, 0, width, height);

      // Draw grid lines with theme color
      ctx.strokeStyle = primaryColorFaint;
      ctx.lineWidth = 1;
      
      // Vertical grid lines
      for (let x = 0; x < width; x += 20) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, height);
        ctx.stroke();
      }

      // Center line with theme color
      ctx.strokeStyle = primaryColorDim;
      ctx.beginPath();
      ctx.moveTo(0, height / 2);
      ctx.lineTo(width, height / 2);
      ctx.stroke();

      // Draw waveform from analyzer or flat line
      if (analyzerNode) {
        const bufferLength = analyzerNode.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);
        analyzerNode.getByteTimeDomainData(dataArray);

        // Check if there's actual audio (not just silence)
        const hasAudio = dataArray.some(v => Math.abs(v - 128) > 2);

        ctx.strokeStyle = primaryColor;
        ctx.lineWidth = 2;
        ctx.shadowColor = primaryColor;
        ctx.shadowBlur = hasAudio ? 10 : 0;
        ctx.beginPath();

        if (hasAudio) {
          const sliceWidth = width / bufferLength;
          let x = 0;

          for (let i = 0; i < bufferLength; i++) {
            const v = dataArray[i] / 128.0;
            const y = (v * height) / 2;

            if (i === 0) {
              ctx.moveTo(x, y);
            } else {
              ctx.lineTo(x, y);
            }

            x += sliceWidth;
          }
        } else {
          // Flat line when no audio
          ctx.moveTo(0, height / 2);
          ctx.lineTo(width, height / 2);
        }

        ctx.stroke();
        ctx.shadowBlur = 0;
      } else {
        // Flat line when no analyzer
        ctx.strokeStyle = primaryColor;
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.moveTo(0, height / 2);
        ctx.lineTo(width, height / 2);
        ctx.stroke();
      }

      animationRef.current = requestAnimationFrame(draw);
    };

    draw();

    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
    };
  }, [analyzerNode]);

  // Handle resize
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const resizeCanvas = () => {
      const container = canvas.parentElement;
      if (container) {
        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;
      }
    };

    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    return () => {
      window.removeEventListener('resize', resizeCanvas);
    };
  }, []);

  const handleClick = () => {
    playSound('click');
    navigate('/oscilloscope');
  };

  // Hide on oscilloscope page
  if (location.pathname === '/oscilloscope') {
    return null;
  }

  return (
    <div 
      onClick={handleClick}
      className="fixed bottom-6 left-1/2 -translate-x-1/2 w-[200px] h-[50px] md:w-[600px] md:h-[80px] z-50 cursor-pointer group"
      title="Open Oscilloscope"
    >
      <div className="relative w-full h-full rounded-lg border border-primary/50 overflow-hidden bg-background/80 backdrop-blur-sm transition-all duration-300 group-hover:border-primary group-hover:shadow-[0_0_20px_hsl(var(--primary)/0.4)]">
        <canvas 
          ref={canvasRef} 
          className="w-full h-full"
        />
        {/* Hover overlay */}
        <div className="absolute inset-0 flex items-center justify-center bg-primary/0 group-hover:bg-primary/10 transition-colors duration-300">
          <span className="opacity-0 group-hover:opacity-100 transition-opacity duration-300 font-crt text-xs text-primary text-glow">
            OPEN OSCILLOSCOPE
          </span>
        </div>
      </div>
    </div>
  );
}
