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 {
  clearDocumentValue,
  getDocumentFileName,
  getDocumentUrl,
  haveDocumentValue,
} from '../documentHelpers';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

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

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

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

  const url = useMemo(() => getDocumentUrl(localValue, structureType), [localValue, structureType]);
  const fileName = useMemo(() => getDocumentFileName(url), [url]);
  const hasValue = useMemo(
    () => haveDocumentValue(localValue, structureType),
    [localValue, structureType],
  );

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

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

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

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

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

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