import {
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';

import { rpc } from '@/api/request';
import { audioRecordDialogRef } from '@/componentsRoot/AudioRecordDialog';
import { Lang } from '@/lang/Lang';
import { copyTextToClipboard } from '@/utils/helpers';

import type { ItemDataProps } from '../../../types';
import { selectFile } from '../../utils/selectFile';
import {
  clearAudioValue,
  getAudioUrl,
  haveAudioValue,
  mapAudioUploadValue,
} from '../audioHelpers';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

export function useFileDataAudio(props: ItemDataProps) {
  const [localValue, setLocalValue] = useState(props.getValue());
  const [uploading, setUploading] = useState(false);

  const structureType = props.structure.type ?? 'fileAudio';

  useEffect(() => {
    props.setValue(localValue);
  }, [localValue]);

  const url = useMemo(() => getAudioUrl(localValue, structureType), [localValue, structureType]);
  const hasValue = useMemo(() => haveAudioValue(localValue, structureType), [localValue, structureType]);

  const { isMobile } = useAppConfigStore();
  const col = props.structure?.col ?? 24;
  const buttonTitle = Lang.key('select_audio');

  const delFile = useCallback(() => {
    setLocalValue(clearAudioValue(structureType));
  }, [structureType]);

  const uploadRequest = useCallback((file: File) => {
    if (!file) {
      return;
    }
    const formData = new FormData();
    formData.append('file', file);
    setUploading(true);
    rpc
      .audioUpload(formData)
      .then((json) => {
        if (json) {
          setLocalValue(mapAudioUploadValue(json, structureType));
        }
      })
      .finally(() => {
        setUploading(false);
      });
  }, [structureType]);

  const onUploadNewFile = useCallback(() => {
    selectFile('audio/mp3').then((file) => {
      if (file) {
        uploadRequest(file);
      }
    });
  }, [uploadRequest]);

  const onRecordAudio = useCallback(() => {
    audioRecordDialogRef.current?.open({
      onSelect: (file) => {
        if (file) {
          uploadRequest(file);
        }
      },
    });
  }, [uploadRequest]);

  const onCopyLink = useCallback(() => {
    copyTextToClipboard(url);
  }, [url]);

  return {
    url,
    hasValue,
    uploading,
    buttonTitle,
    isMobile,
    col,
    delFile,
    onUploadNewFile,
    onRecordAudio,
    onCopyLink,
  };
}
