import { useEffect, useRef, useState } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';
import { apiService } from '@/services/api';

interface WaveformDisplayProps {
  trackId: string;
  height?: number;
  color?: string;
  progressColor?: string;
  progress?: number; // 0-1
  onSeek?: (position: number) => void;
}

export function WaveformDisplay({ 
  trackId, 
  height = 80, 
  color = '#3b82f6',
  progressColor = '#60a5fa',
  progress = 0,
  onSeek 
}: WaveformDisplayProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [waveformData, setWaveformData] = useState<number[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchWaveform();
  }, [trackId]);

  useEffect(() => {
    if (waveformData.length > 0) {
      drawWaveform();
    }
  }, [waveformData, progress]);

  const fetchWaveform = async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      // Try to fetch waveform data from API
      // If not available, generate from audio analysis
      try {
        const url = `${apiService.getHLSManifestURL(trackId).replace('/manifest.m3u8', '/waveform')}`;
        const response = await fetch(url);
        if (response.ok) {
          const data = await response.json();
          setWaveformData(data.peaks || generateMockWaveform());
        } else {
          setWaveformData(generateMockWaveform());
        }
      } catch {
        // If waveform endpoint doesn't exist, generate mock data
        setWaveformData(generateMockWaveform());
      }
    } catch (err: any) {
      setError(err.message || 'Failed to load waveform');
      setWaveformData(generateMockWaveform());
    } finally {
      setIsLoading(false);
    }
  };

  const generateMockWaveform = (): number[] => {
    // Generate realistic-looking waveform data
    const points = 200;
    const data: number[] = [];
    
    for (let i = 0; i < points; i++) {
      // Create peaks and valleys
      const base = Math.sin(i / 10) * 0.5;
      const variation = Math.random() * 0.5;
      const peak = base + variation;
      data.push(Math.abs(peak));
    }
    
    return data;
  };

  const drawWaveform = () => {
    const canvas = canvasRef.current;
    const container = containerRef.current;
    if (!canvas || !container) return;

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

    // Set canvas size to match container
    const dpr = window.devicePixelRatio || 1;
    const rect = container.getBoundingClientRect();
    canvas.width = rect.width * dpr;
    canvas.height = height * dpr;
    canvas.style.width = `${rect.width}px`;
    canvas.style.height = `${height}px`;
    ctx.scale(dpr, dpr);

    // Clear canvas
    ctx.clearRect(0, 0, rect.width, height);

    // Calculate bar width
    const barWidth = rect.width / waveformData.length;
    const barGap = barWidth * 0.2;
    const actualBarWidth = barWidth - barGap;

    // Draw waveform bars
    waveformData.forEach((value, index) => {
      const x = index * barWidth;
      const barHeight = value * (height - 4);
      const y = (height - barHeight) / 2;

      // Determine color based on progress
      const barProgress = index / waveformData.length;
      ctx.fillStyle = barProgress <= progress ? progressColor : color;

      // Draw bar with rounded corners
      ctx.beginPath();
      ctx.roundRect(x, y, actualBarWidth, barHeight, 2);
      ctx.fill();
    });
  };

  const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!onSeek || !containerRef.current) return;

    const rect = containerRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const position = x / rect.width;

    onSeek(Math.max(0, Math.min(1, position)));
  };

  if (isLoading) {
    return (
      <Card>
        <CardContent className="py-6">
          <div className="flex items-center justify-center" style={{ height: `${height}px` }}>
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card>
        <CardContent className="py-6">
          <div 
            className="flex items-center justify-center text-sm text-muted-foreground" 
            style={{ height: `${height}px` }}
          >
            Waveform unavailable
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div
      ref={containerRef}
      className="relative cursor-pointer rounded-lg overflow-hidden bg-muted/20"
      onClick={handleClick}
      style={{ height: `${height}px` }}
    >
      <canvas
        ref={canvasRef}
        className="w-full h-full"
      />
      
      {/* Progress indicator */}
      {progress > 0 && (
        <div
          className="absolute top-0 bottom-0 w-0.5 bg-white opacity-75 pointer-events-none"
          style={{ left: `${progress * 100}%` }}
        />
      )}
    </div>
  );
}

