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 {
  clearImageValue,
  getImageUrl,
  haveImageValue,
} from '../imageHelpers';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

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

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

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

  const url = useMemo(() => getImageUrl(localValue, structureType), [localValue, structureType]);
  const hasValue = useMemo(() => haveImageValue(localValue, structureType), [localValue, structureType]);

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

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

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

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

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

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