import React from 'react';
import { processAudio } from '../../services/audioService';
import { Button } from '../ui/button';

interface AudioUploaderProps {
  storyId: string;
  onUploadComplete?: (transcription: string) => void;
  onError?: (error: string) => void;
}

export function AudioUploader({ 
  storyId,
  onUploadComplete,
  onError 
}: AudioUploaderProps): JSX.Element {
  const [isProcessing, setIsProcessing] = React.useState(false);
  const [error, setError] = React.useState<string>();

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      setIsProcessing(true);
      setError(undefined);
      
      const response = await processAudio(file, storyId);
      
      if (response.error) {
        setError(response.error);
        onError?.(response.error);
      } else if (response.transcription) {
        onUploadComplete?.(response.transcription);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Erro ao processar áudio';
      setError(errorMessage);
      onError?.(errorMessage);
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className="space-y-4">
      <div>
        <input
          type="file"
          accept="audio/*"
          onChange={handleFileUpload}
          disabled={isProcessing}
          className="hidden"
          id="audio-upload"
        />
        <label htmlFor="audio-upload">
          <Button 
            as="span"
            disabled={isProcessing}
            className="cursor-pointer"
          >
            {isProcessing ? 'Processando...' : 'Enviar Áudio'}
          </Button>
        </label>
      </div>

      {error && (
        <p className="text-sm text-red-600">{error}</p>
      )}
    </div>
  );
} 