import {useCallback, useState} from 'react';
import {useMutation} from '@tanstack/react-query';
import {
  compressAudio,
  uploadAudioAsset,
  summarizeAudio,
} from '@modules/chats/services/aiSummary';
import {AiSummaryState} from '@modules/chats/interfaces';

const IDLE_STATE: AiSummaryState = {status: 'idle'};

export const useAudioSummary = () => {
  const [state, setState] = useState<AiSummaryState>(IDLE_STATE);

  const {mutate} = useMutation({
    mutationFn: async (uri: string): Promise<AiSummaryState> => {
      setState({status: 'compressing'});
      const compressedAudioUri = await compressAudio(uri);

      setState({status: 'uploading', audioUri: compressedAudioUri});
      const fileAsset = await uploadAudioAsset(compressedAudioUri);

      if (!fileAsset.key) {
        throw new Error('Uploaded asset is missing S3 key');
      }

      setState({status: 'summarizing', audioUri: compressedAudioUri});
      const {transcript, summary} = await summarizeAudio(
        fileAsset.key,
        fileAsset.contentType,
      );

      return {
        status: 'done',
        audioUri: compressedAudioUri,
        transcript,
        summary,
      };
    },
    onSuccess: doneState => {
      setState(doneState);
    },
    onError: error => {
      setState(prev => ({
        status: 'error',
        error: error.message,
        audioUri: 'audioUri' in prev ? prev.audioUri : undefined,
      }));
    },
  });

  const summarize = useCallback(
    (uri: string) => {
      setState(IDLE_STATE);
      mutate(uri);
    },
    [mutate],
  );

  const clear = useCallback(() => {
    setState(IDLE_STATE);
  }, []);

  const setAsRecording = useCallback(() => {
    setState({status: 'recording'});
  }, []);

  return {summarize, clear, state, setAsRecording} as const;
};
