import { useStore } from '@nanostores/react'
import { selectedImage, panelOpen, generatedImages, synthesisParams } from '../stores'
import { synthesizeFromImage, downloadWAV, playAudio, type WindowType } from '../spectral-synthesis'
import { useState } from 'react'

export default function AudioPanel() {
  const selected = useStore(selectedImage)
  const images = useStore(generatedImages)
  const params = useStore(synthesisParams)
  const [isProcessing, setIsProcessing] = useState(false)

  const handleClearSelection = () => {
    selectedImage.set(null)
  }

  const updateParam = <K extends keyof typeof params>(key: K, value: typeof params[K]) => {
    synthesisParams.set({ ...params, [key]: value })
  }

  const handleDownloadSingle = async () => {
    if (!selected) return

    setIsProcessing(true)
    try {
      const audio = synthesizeFromImage(selected.imageData, params)
      downloadWAV(audio, params.sampleRate, `audio-${selected.id}.wav`)
    } catch (error) {
      console.error('Error generating audio:', error)
    }
    setIsProcessing(false)
  }

  const handlePlaySingle = async () => {
    if (!selected) return

    setIsProcessing(true)
    try {
      const audio = synthesizeFromImage(selected.imageData, params)
      await playAudio(audio, params.sampleRate)
    } catch (error) {
      console.error('Error playing audio:', error)
    }
    setIsProcessing(false)
  }

  const handleDownloadAll = async () => {
    if (images.length === 0) return

    setIsProcessing(true)
    try {
      for (let i = 0; i < images.length; i++) {
        const image = images[i]
        const audio = synthesizeFromImage(image.imageData, params)
        downloadWAV(audio, params.sampleRate, `audio-${image.id}.wav`)

        if (i < images.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 500))
        }
      }
    } catch (error) {
      console.error('Error generating all audio:', error)
    }
    setIsProcessing(false)
  }

  return (
    <div className="w-96 bg-black border-l border-gray-800 flex flex-col h-screen">
      {/* Selected Image or Placeholder */}
      <div className="p-4 border-b border-gray-800 flex-shrink-0">
        {selected ? (
          <div className="flex items-center space-x-3">
            <div className="w-16 h-16 border border-gray-600">
              <canvas
                ref={(canvas) => {
                  if (canvas && selected.canvas) {
                    const ctx = canvas.getContext('2d')!
                    canvas.width = selected.canvas.width
                    canvas.height = selected.canvas.height
                    canvas.style.width = '100%'
                    canvas.style.height = '100%'

                    if (selected.generator === 'tixy' || selected.generator === 'geometric-tiles') {
                      ctx.imageSmoothingEnabled = false
                    } else {
                      ctx.imageSmoothingEnabled = true
                    }

                    ctx.drawImage(selected.canvas, 0, 0)
                  }
                }}
                className="w-full h-full block"
                style={{ imageRendering: (selected.generator === 'tixy' || selected.generator === 'geometric-tiles') ? 'pixelated' : 'auto' }}
              />
            </div>
            <div className="text-gray-300">
              <div className="text-sm font-medium">{selected.generator}</div>
              <div className="text-xs text-gray-500">ID: {selected.id.slice(-8)}</div>
            </div>
          </div>
        ) : (
          <div className="text-center text-gray-500 py-8">
            <div className="text-sm">No image selected</div>
            <div className="text-xs mt-1">Click an image from the grid to export audio</div>
          </div>
        )}
      </div>

      {/* Synthesis Parameters - Scrollable */}
      <div className="flex-1 overflow-y-auto">
        <div className="p-4 space-y-4">
        <h4 className="text-white font-medium text-sm">Synthesis Parameters</h4>

        <div className="space-y-3">
          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Duration: {params.duration}s
            </label>
            <input
              type="range"
              min="1"
              max="30"
              step="1"
              value={params.duration}
              onChange={(e) => updateParam('duration', Number(e.target.value))}
              className="w-full"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Max Partials: {params.maxPartials}
            </label>
            <input
              type="range"
              min="10"
              max="500"
              step="10"
              value={params.maxPartials}
              onChange={(e) => updateParam('maxPartials', Number(e.target.value))}
              className="w-full"
            />
            <p className="text-xs text-gray-500 mt-1">Controls audio complexity vs performance</p>
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Frequency Resolution: {params.frequencyResolution}x
            </label>
            <input
              type="range"
              min="1"
              max="10"
              step="1"
              value={params.frequencyResolution}
              onChange={(e) => updateParam('frequencyResolution', Number(e.target.value))}
              className="w-full"
            />
            <p className="text-xs text-gray-500 mt-1">Skip frequency bins for performance</p>
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Time Resolution: {params.timeResolution}x
            </label>
            <input
              type="range"
              min="1"
              max="10"
              step="1"
              value={params.timeResolution}
              onChange={(e) => updateParam('timeResolution', Number(e.target.value))}
              className="w-full"
            />
            <p className="text-xs text-gray-500 mt-1">Skip time slices for performance</p>
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Min Frequency: {params.minFreq}Hz
            </label>
            <input
              type="range"
              min="20"
              max="200"
              step="10"
              value={params.minFreq}
              onChange={(e) => updateParam('minFreq', Number(e.target.value))}
              className="w-full"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Max Frequency: {params.maxFreq}Hz
            </label>
            <input
              type="range"
              min="1000"
              max="20000"
              step="500"
              value={params.maxFreq}
              onChange={(e) => updateParam('maxFreq', Number(e.target.value))}
              className="w-full"
            />
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Amplitude Threshold: {params.amplitudeThreshold}
            </label>
            <input
              type="range"
              min="0.001"
              max="0.1"
              step="0.001"
              value={params.amplitudeThreshold}
              onChange={(e) => updateParam('amplitudeThreshold', Number(e.target.value))}
              className="w-full"
            />
            <p className="text-xs text-gray-500 mt-1">Minimum amplitude to include</p>
          </div>

          <div>
            <label className="block text-xs text-gray-400 mb-1">
              Window Type: {params.windowType}
            </label>
            <select
              value={params.windowType}
              onChange={(e) => updateParam('windowType', e.target.value as WindowType)}
              className="w-full px-2 py-1 bg-gray-800 border border-gray-600 text-white text-xs focus:outline-none focus:border-gray-400"
            >
              <option value="rectangular">Rectangular (No windowing)</option>
              <option value="hann">Hann (Smooth, good general purpose)</option>
              <option value="hamming">Hamming (Sharper frequency response)</option>
              <option value="blackman">Blackman (Minimal artifacts)</option>
            </select>
            <p className="text-xs text-gray-500 mt-1">Reduces clicking/popping between time frames</p>
          </div>
        </div>
        </div>
      </div>

      {/* Action Buttons - Always Visible */}
      <div className="p-4 border-t border-gray-800 space-y-3 flex-shrink-0">
        <div className="flex space-x-2">
          <button
            onClick={handlePlaySingle}
            disabled={isProcessing || !selected}
            className="flex-1 bg-gray-700 text-white py-2 px-3 text-sm hover:bg-gray-600 disabled:bg-gray-800 disabled:cursor-not-allowed"
          >
            {isProcessing ? 'Processing...' : 'Play'}
          </button>
          <button
            onClick={handleDownloadSingle}
            disabled={isProcessing || !selected}
            className="flex-1 bg-white text-black py-2 px-3 text-sm hover:bg-gray-200 disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed"
          >
            Download
          </button>
        </div>

        <button
          onClick={handleDownloadAll}
          disabled={isProcessing || images.length === 0}
          className="w-full bg-gray-700 text-white py-2 px-3 text-sm hover:bg-gray-600 disabled:bg-gray-800 disabled:cursor-not-allowed border border-gray-600"
        >
          Download All ({images.length})
        </button>
      </div>
    </div>
  )
}