import { useState, useEffect } from 'react';

export const useAudioRecorder = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [audioBlob, setAudioBlob] = useState<Blob | null>(null);
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [audioURL, setAudioURL] = useState<string | null>(null);

  useEffect(() => {
    const initializeRecorder = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        const recorder = new MediaRecorder(stream);
        
        const chunks: BlobPart[] = [];
        
        recorder.ondataavailable = (e) => {
          if (e.data.size > 0) {
            chunks.push(e.data);
          }
        };

        recorder.onstop = () => {
          const blob = new Blob(chunks, { type: 'audio/webm' });
          setAudioBlob(blob);
          setAudioURL(URL.createObjectURL(blob));
          chunks.length = 0; // Clear chunks
        };

        setMediaRecorder(recorder);
        setError(null);
      } catch (err) {
        setError('Erreur lors de l\'accès au microphone');
        console.error('Erreur MediaRecorder:', err);
      }
    };

    initializeRecorder();

    return () => {
      if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
      }
      if (audioURL) {
        URL.revokeObjectURL(audioURL);
      }
    };
  }, []);

  const startRecording = async () => {
    try {
      if (mediaRecorder && mediaRecorder.state === 'inactive') {
        mediaRecorder.start();
        setIsRecording(true);
        setError(null);
      }
    } catch (err) {
      setError('Erreur lors du démarrage de l\'enregistrement');
      console.error('Erreur de démarrage:', err);
    }
  };

  const stopRecording = () => {
    try {
      if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
        setIsRecording(false);
        setError(null);
      }
    } catch (err) {
      setError('Erreur lors de l\'arrêt de l\'enregistrement');
      console.error('Erreur d\'arrêt:', err);
    }
  };

  const resetRecording = () => {
    setAudioBlob(null);
    if (audioURL) {
      URL.revokeObjectURL(audioURL);
      setAudioURL(null);
    }
  };

  return {
    isRecording,
    audioBlob,
    audioURL,
    error,
    startRecording,
    stopRecording,
    resetRecording
  };
};
