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

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

import type { ItemDataProps } from '../../../types';
import { selectFile } from '../../utils/selectFile';
import {
  clearVideoValue,
  getVideoUrl,
  haveVideoValue,
} from '../videoHelpers';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

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

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

  const url = useMemo(() => getVideoUrl(localValue), [localValue]);
  const hasValue = useMemo(() => haveVideoValue(localValue), [localValue]);

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

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

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

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

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

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