import { useState, useCallback, useEffect } from "react";
import vmsg from "vmsg";

const recorder = new vmsg.Recorder({
  wasmURL: "https://unpkg.com/vmsg@0.3.0/vmsg.wasm"
});

export function useAudioRecorder() {
  const [isLoading, setIsLoading] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [recordings, setRecordings] = useState<string[]>([]);
  const [currentRecording, setCurrentRecording] = useState<string | null>(null);

  const startRecording = useCallback(async () => {
    setIsLoading(true);
    try {
      // Nécessaire sur mobile : initAudio DOIT être dans un handler utilisateur (tap/click)
      await recorder.initAudio();
      await recorder.initWorker();
      await recorder.startRecording();
      setIsRecording(true);
    } catch (error) {
      console.error("Erreur lors du démarrage de l'enregistrement :", error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  }, []);

  const stopRecording = useCallback(async () => {
    if (!isRecording) return;

    setIsLoading(true);
    try {
      const blob = await recorder.stopRecording();
      const url = URL.createObjectURL(blob);

      setRecordings(prev => [...prev, url]);
      setCurrentRecording(url);

      return { blob, url };
    } catch (error) {
      console.error("Erreur lors de l'arrêt de l'enregistrement :", error);
      throw error;
    } finally {
      setIsRecording(false);
      setIsLoading(false);
    }
  }, [isRecording]);

  const toggleRecording = useCallback(async () => {
    if (isRecording) {
      return await stopRecording();
    } else {
      return await startRecording();
    }
  }, [isRecording, startRecording, stopRecording]);

  const clearRecordings = useCallback(() => {
    recordings.forEach(url => URL.revokeObjectURL(url));
    setRecordings([]);
    setCurrentRecording(null);
  }, [recordings]);

  useEffect(() => {
    return () => {
      recordings.forEach(url => URL.revokeObjectURL(url));
    };
  }, [recordings]);

  return {
    isLoading,
    isRecording,
    recordings,
    currentRecording,
    startRecording,
    stopRecording,
    toggleRecording,
    clearRecordings
  };
}
