import React, { useState, useEffect, useMemo } from 'react';
import { Play, Pause, RotateCcw, Music, Zap, Waves } from 'lucide-react';

interface Note {
  name: string;
  frequency: number;
  phase: number;
  quantumState: string;
}

interface HarmonicSeries {
  fundamental: number;
  harmonics: number[];
  ratios: string[];
}

const QuantumHarmonyExplorer: React.FC = () => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [selectedNote, setSelectedNote] = useState<Note | null>(null);
  const [time, setTime] = useState(0);
  const [showQuantumView, setShowQuantumView] = useState(false);

  // Musical notes and their quantum phase mappings
  const notes: Note[] = useMemo(() => [
    { name: 'C4', frequency: 261.63, phase: 0, quantumState: '|0⟩' },
    { name: 'D4', frequency: 293.66, phase: Math.PI/4, quantumState: '(|0⟩+|1⟩)/√2' },
    { name: 'E4', frequency: 329.63, phase: Math.PI/2, quantumState: '|1⟩' },
    { name: 'F4', frequency: 349.23, phase: 3*Math.PI/4, quantumState: '(|0⟩-|1⟩)/√2' },
    { name: 'G4', frequency: 392.00, phase: Math.PI, quantumState: '|0⟩' },
    { name: 'A4', frequency: 440.00, phase: 5*Math.PI/4, quantumState: '(|0⟩+i|1⟩)/√2' },
    { name: 'B4', frequency: 493.88, phase: 3*Math.PI/2, quantumState: '|1⟩' },
    { name: 'C5', frequency: 523.25, phase: 2*Math.PI, quantumState: '|0⟩' },
  ], []);

  // Calculate harmonic series for fundamental frequency
  const harmonicSeries: HarmonicSeries = useMemo(() => {
    if (!selectedNote) return { fundamental: 0, harmonics: [], ratios: [] };
    
    const fundamental = selectedNote.frequency;
    const harmonics = Array.from({ length: 8 }, (_, i) => fundamental * (i + 1));
    const ratios = harmonics.map((h, i) => `${i + 1}:1`);
    
    return { fundamental, harmonics, ratios };
  }, [selectedNote]);

  // Animation loop
  useEffect(() => {
    let animationFrame: number;
    
    if (isPlaying) {
      const animate = () => {
        setTime(prev => prev + 0.016); // ~60fps
        animationFrame = requestAnimationFrame(animate);
      };
      animationFrame = requestAnimationFrame(animate);
    }
    
    return () => {
      if (animationFrame) cancelAnimationFrame(animationFrame);
    };
  }, [isPlaying]);

  const calculateWaveAmplitude = (frequency: number, t: number, phase: number = 0): number => {
    return Math.sin(2 * Math.PI * frequency * t / 100 + phase) * 0.3;
  };

  const getConsonanceColor = (ratio: number): string => {
    // Color based on harmonic consonance ratios
    if (ratio === 1) return 'rgb(59, 130, 246)'; // Perfect unison - blue
    if (Math.abs(ratio - 2) < 0.1) return 'rgb(16, 185, 129)'; // Octave - green
    if (Math.abs(ratio - 1.5) < 0.1) return 'rgb(245, 158, 11)'; // Perfect fifth - amber
    if (Math.abs(ratio - 4/3) < 0.1) return 'rgb(168, 85, 247)'; // Perfect fourth - purple
    if (Math.abs(ratio - 5/4) < 0.1) return 'rgb(236, 72, 153)'; // Major third - pink
    return 'rgb(156, 163, 175)'; // Other intervals - gray
  };

  const renderWaveform = (note: Note, index: number) => {
    const points = Array.from({ length: 200 }, (_, i) => {
      const x = i * 2;
      const y = 100 + calculateWaveAmplitude(note.frequency, time + i, note.phase) * 80;
      return `${x},${y}`;
    }).join(' ');

    return (
      <svg key={note.name} width="400" height="200" className="border rounded-lg bg-gradient-to-r from-slate-50 to-blue-50">
        <defs>
          <linearGradient id={`gradient-${index}`} x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor={getConsonanceColor(1)} stopOpacity="0.3" />
            <stop offset="100%" stopColor={getConsonanceColor(1)} stopOpacity="0.8" />
          </linearGradient>
        </defs>
        
        <polyline
          points={points}
          fill="none"
          stroke={`url(#gradient-${index})`}
          strokeWidth="2"
        />
        
        <text x="10" y="25" className="text-sm font-medium fill-slate-700">
          {note.name} - {note.frequency.toFixed(1)}Hz
        </text>
        
        {showQuantumView && (
          <text x="10" y="45" className="text-xs fill-slate-600">
            φ = {note.phase.toFixed(2)} | {note.quantumState}
          </text>
        )}
      </svg>
    );
  };

  const renderHarmonicSpectrum = () => {
    if (!selectedNote) return null;

    return (
      <div className="bg-white p-6 rounded-xl shadow-lg">
        <h3 className="text-xl font-semibold mb-4 flex items-center gap-2">
          <Waves className="w-5 h-5 text-blue-600" />
          Harmonic Series Analysis
        </h3>
        
        <div className="grid grid-cols-4 gap-4 mb-6">
          {harmonicSeries.harmonics.slice(0, 8).map((freq, i) => (
            <div key={i} className="text-center">
              <div 
                className="w-full h-16 rounded-lg mb-2 border-2 flex items-center justify-center"
                style={{ 
                  backgroundColor: getConsonanceColor((i + 1)),
                  opacity: 0.7 + (0.3 * Math.sin(time * freq / 100))
                }}
              >
                <span className="text-white font-semibold">{i + 1}</span>
              </div>
              <div className="text-xs text-slate-600">
                {freq.toFixed(0)}Hz
              </div>
              <div className="text-xs text-slate-500">
                {harmonicSeries.ratios[i]}
              </div>
            </div>
          ))}
        </div>

        <div className="text-sm text-slate-600">
          <p className="mb-2">
            <strong>Quantum Phase Relationship:</strong> Each harmonic corresponds to a different quantum phase state.
          </p>
          <p>
            <strong>Consonance Theory:</strong> Simple ratios (2:1, 3:2, 4:3) create more consonant harmonies and more stable quantum interference patterns.
          </p>
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-purple-50 to-pink-50 p-6">
      <div className="max-w-7xl mx-auto">
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-4">
            Quantum-Musical Harmony Explorer
          </h1>
          <p className="text-lg text-slate-600 max-w-3xl mx-auto">
            Explore the fascinating mathematical connections between musical harmony and quantum mechanics. 
            While not a practical quantum computer, this demonstrates real relationships between wave physics, 
            harmonic ratios, and quantum phase states.
          </p>
        </div>

        {/* Controls */}
        <div className="bg-white p-6 rounded-xl shadow-lg mb-8">
          <div className="flex flex-wrap items-center gap-4 mb-6">
            <button
              onClick={() => setIsPlaying(!isPlaying)}
              className="flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors"
            >
              {isPlaying ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
              {isPlaying ? 'Pause' : 'Play'} Animation
            </button>
            
            <button
              onClick={() => setTime(0)}
              className="flex items-center gap-2 px-4 py-2 border border-slate-300 hover:bg-slate-50 rounded-lg transition-colors"
            >
              <RotateCcw className="w-4 h-4" />
              Reset
            </button>
            
            <button
              onClick={() => setShowQuantumView(!showQuantumView)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                showQuantumView 
                  ? 'bg-purple-100 text-purple-700 border border-purple-300' 
                  : 'border border-slate-300 hover:bg-slate-50'
              }`}
            >
              <Zap className="w-4 h-4" />
              Quantum View
            </button>
          </div>

          {/* Note Selection */}
          <div className="grid grid-cols-4 md:grid-cols-8 gap-2">
            {notes.map((note) => (
              <button
                key={note.name}
                onClick={() => setSelectedNote(note)}
                className={`p-3 rounded-lg border-2 transition-all ${
                  selectedNote?.name === note.name
                    ? 'border-blue-500 bg-blue-50 text-blue-700'
                    : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'
                }`}
              >
                <div className="font-medium">{note.name}</div>
                <div className="text-xs text-slate-500">{note.frequency.toFixed(0)}Hz</div>
              </button>
            ))}
          </div>
        </div>

        {/* Waveform Display */}
        <div className="bg-white p-6 rounded-xl shadow-lg mb-8">
          <h2 className="text-2xl font-semibold mb-6 flex items-center gap-2">
            <Music className="w-6 h-6 text-blue-600" />
            Wave Interference Patterns
          </h2>
          
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {notes.slice(0, 4).map((note, index) => renderWaveform(note, index))}
          </div>
          
          <div className="mt-6 p-4 bg-blue-50 rounded-lg">
            <h3 className="font-semibold text-blue-800 mb-2">Scientific Connection:</h3>
            <p className="text-blue-700 text-sm">
              Musical waves and quantum wave functions both follow wave equations. The phase relationships 
              in harmony (consonance/dissonance) mirror constructive/destructive interference in quantum systems.
              However, actual quantum computers require precise control at the atomic level, not just wave mathematics.
            </p>
          </div>
        </div>

        {/* Harmonic Analysis */}
        {selectedNote && renderHarmonicSpectrum()}

        {/* Educational Information */}
        <div className="bg-white p-6 rounded-xl shadow-lg">
          <h2 className="text-2xl font-semibold mb-4">Real Science vs Speculation</h2>
          
          <div className="grid md:grid-cols-2 gap-6">
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <h3 className="font-semibold text-green-800 mb-3">✅ Real Connections</h3>
              <ul className="text-green-700 text-sm space-y-2">
                <li>• Wave equations govern both sound and quantum mechanics</li>
                <li>• Phase relationships are fundamental to both domains</li>
                <li>• Harmonic ratios relate to frequency relationships</li>
                <li>• Interference patterns follow similar mathematics</li>
                <li>• Fourier transforms are used in both music and quantum computing</li>
              </ul>
            </div>
            
            <div className="p-4 bg-amber-50 border border-amber-200 rounded-lg">
              <h3 className="font-semibold text-amber-800 mb-3">⚠️ Current Limitations</h3>
              <ul className="text-amber-700 text-sm space-y-2">
                <li>• Quantum computers require atomic-scale precision</li>
                <li>• Decoherence is caused by environmental interactions, not musical dissonance</li>
                <li>• Current systems need extreme cooling for isolation</li>
                <li>• Musical harmony alone cannot create quantum entanglement</li>
                <li>• Scaling quantum systems remains an engineering challenge</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default QuantumHarmonyExplorer;