/**
 * VEZA V5 ULTRA - EQUALIZER UI
 * 10-band equalizer with presets and visual feedback
 */

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { getAudioEngine } from '@/services/audio-engine-v5';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Slider } from '@/components/ui/slider';
import { RotateCcw } from 'lucide-react';
import { cn } from '@/lib/utils';

const FREQUENCIES = [
  { hz: 32, label: '32' },
  { hz: 64, label: '64' },
  { hz: 125, label: '125' },
  { hz: 250, label: '250' },
  { hz: 500, label: '500' },
  { hz: 1000, label: '1k' },
  { hz: 2000, label: '2k' },
  { hz: 4000, label: '4k' },
  { hz: 8000, label: '8k' },
  { hz: 16000, label: '16k' },
];

interface EqualizerPreset {
  name: string;
  values: number[];
}

const PRESETS: EqualizerPreset[] = [
  { name: 'Flat', values: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] },
  { name: 'Pop', values: [-1, -1, 0, 2, 4, 4, 2, 0, -1, -1] },
  { name: 'Rock', values: [4, 3, 2, 1, -1, -2, -1, 1, 3, 4] },
  { name: 'Jazz', values: [3, 2, 1, 1, -1, -1, 0, 1, 2, 3] },
  { name: 'Classical', values: [4, 3, 2, 1, -1, -1, 0, 2, 3, 4] },
  { name: 'Bass Boost', values: [6, 5, 4, 2, 0, 0, 0, 0, 0, 0] },
  { name: 'Treble Boost', values: [0, 0, 0, 0, 0, 0, 2, 4, 5, 6] },
  { name: 'Vocal', values: [-2, -3, -2, 1, 3, 3, 2, 1, -1, -2] },
];

interface EqualizerV5Props {
  className?: string;
  compact?: boolean;
}

export function EqualizerV5({ className = '', compact = false }: EqualizerV5Props) {
  const [gains, setGains] = useState<number[]>(Array(10).fill(0));
  const [activePreset, setActivePreset] = useState<string>('Flat');
  
  const engine = getAudioEngine();

  // Initialize equalizer
  useEffect(() => {
    gains.forEach((gain, index) => {
      engine.setEqualizerBand(index, gain);
    });
  }, [gains]);

  // Handle band change
  const handleBandChange = (index: number, value: number[]) => {
    const newGains = [...gains];
    newGains[index] = value[0];
    setGains(newGains);
    engine.setEqualizerBand(index, value[0]);
    setActivePreset('Custom');
  };

  // Apply preset
  const applyPreset = (preset: EqualizerPreset) => {
    setGains(preset.values);
    preset.values.forEach((gain, index) => {
      engine.setEqualizerBand(index, gain);
    });
    setActivePreset(preset.name);
  };

  // Reset equalizer
  const handleReset = () => {
    const flatPreset = PRESETS.find(p => p.name === 'Flat')!;
    applyPreset(flatPreset);
  };

  if (compact) {
    return (
      <Card variant="glass" className={cn('p-4', className)}>
        <div className="flex items-center gap-4">
          <div className="text-sm font-medium">EQ</div>
          
          {/* Mini sliders */}
          <div className="flex-1 flex items-end gap-2 h-16">
            {gains.map((gain, index) => (
              <div
                key={index}
                className="flex-1 flex flex-col items-center gap-1"
              >
                <div
                  className="w-full bg-gradient-brand rounded-full transition-all"
                  style={{
                    height: `${((gain + 12) / 24) * 100}%`,
                    minHeight: '4px',
                  }}
                />
                <span className="text-xs text-muted-foreground">
                  {FREQUENCIES[index].label}
                </span>
              </div>
            ))}
          </div>

          <Button variant="ghost" size="icon" onClick={handleReset}>
            <RotateCcw className="w-4 h-4" />
          </Button>
        </div>
      </Card>
    );
  }

  return (
    <Card variant="glass" className={cn('p-6', className)}>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-bold text-gradient">
          10-Band Equalizer
        </h3>
        <Button
          variant="outline"
          size="sm"
          onClick={handleReset}
          icon={<RotateCcw className="w-4 h-4" />}
        >
          Reset
        </Button>
      </div>

      {/* Presets */}
      <div className="mb-6">
        <div className="text-sm font-medium mb-3">Presets</div>
        <div className="flex flex-wrap gap-2">
          {PRESETS.map((preset) => (
            <Button
              key={preset.name}
              variant={activePreset === preset.name ? 'gradient' : 'outline'}
              size="sm"
              onClick={() => applyPreset(preset)}
            >
              {preset.name}
            </Button>
          ))}
        </div>
      </div>

      {/* Equalizer Bands */}
      <div className="grid grid-cols-10 gap-3">
        {FREQUENCIES.map((freq, index) => (
          <div key={freq.hz} className="flex flex-col items-center gap-2">
            {/* Value Display */}
            <div className="text-xs font-mono text-muted-foreground w-full text-center">
              {gains[index] > 0 ? '+' : ''}
              {gains[index].toFixed(1)}
            </div>

            {/* Slider (Vertical) */}
            <div className="h-48 flex items-center justify-center">
              <div className="h-full w-12 relative">
                <input
                  type="range"
                  min={-12}
                  max={12}
                  step={0.5}
                  value={gains[index]}
                  onChange={(e) => handleBandChange(index, [parseFloat(e.target.value)])}
                  className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-48 h-12 origin-center -rotate-90"
                  style={{
                    appearance: 'none',
                    background: 'transparent',
                  }}
                />
                
                {/* Visual Bar */}
                <div className="absolute inset-0 flex flex-col justify-center items-center">
                  <div className="w-2 h-full bg-muted rounded-full relative overflow-hidden">
                    {/* Fill */}
                    <motion.div
                      className="absolute bottom-0 left-0 right-0 gradient-brand rounded-full"
                      initial={{ height: '50%' }}
                      animate={{
                        height: `${((gains[index] + 12) / 24) * 100}%`,
                      }}
                      transition={{ duration: 0.2 }}
                    />
                    {/* Center line */}
                    <div className="absolute top-1/2 left-0 right-0 h-px bg-white/20" />
                  </div>
                </div>
              </div>
            </div>

            {/* Frequency Label */}
            <div className="text-xs font-medium">
              {freq.label}
              <br />
              <span className="text-muted-foreground text-[10px]">Hz</span>
            </div>
          </div>
        ))}
      </div>

      {/* Info */}
      <div className="mt-6 text-center text-xs text-muted-foreground">
        <p>Adjust each frequency band from -12dB to +12dB</p>
        <p className="mt-1">Current preset: <span className="font-medium text-foreground">{activePreset}</span></p>
      </div>
    </Card>
  );
}

